



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        __snake_case		(  UpperCamelCase_		):




							def      UpperCAmelCase__    ( self  : Dict):
									lowerCAmelCase_    :  int             =				self.config_class(**self.inputs_dict)
									self.parent.assertTrue(hasattr(A_       ,       '''hidden_sizes'''))
									self.parent.assertTrue(hasattr(A_       ,       '''num_encoder_blocks'''))





class        __snake_case		:




							def __init__( self  : str       ,       A_  : int       ,       A_  : Dict=1_3       ,       A_  : Tuple=6_4       ,       A_  : Dict=3       ,       A_  : Dict=4       ,       A_  : Tuple=[2, 2, 2, 2]       ,       A_  : Optional[Any]=[8, 4, 2, 1]       ,       A_  : str=[1_6, 3_2, 6_4, 1_2_8]       ,       A_  : int=[1, 4, 8, 1_6]       ,       A_  : Tuple=False       ,       A_  : Tuple=True       ,       A_  : str="gelu"       ,       A_  : int=0.1       ,       A_  : Optional[int]=0.02       ,       A_  : List[Any]=3       ,       A_  : Dict=None       ,       ):
									lowerCAmelCase_    :  Optional[int]             =				parent
									lowerCAmelCase_    :  Optional[Any]             =				batch_size
									lowerCAmelCase_    :  Dict             =				image_size
									lowerCAmelCase_    :  List[Any]             =				num_channels
									lowerCAmelCase_    :  Tuple             =				num_encoder_blocks
									lowerCAmelCase_    :  Union[str, Any]             =				sr_ratios
									lowerCAmelCase_    :  Dict             =				depths
									lowerCAmelCase_    :  str             =				hidden_sizes
									lowerCAmelCase_    :  Tuple             =				downsampling_rates
									lowerCAmelCase_    :  List[str]             =				is_training
									lowerCAmelCase_    :  int             =				use_labels
									lowerCAmelCase_    :  Optional[int]             =				hidden_act
									lowerCAmelCase_    :  int             =				hidden_dropout_prob
									lowerCAmelCase_    :  Optional[int]             =				initializer_range
									lowerCAmelCase_    :  Dict             =				num_labels
									lowerCAmelCase_    :  Optional[Any]             =				scope




							def      UpperCAmelCase__    ( self  : Union[str, Any]):
									lowerCAmelCase_    :  Dict             =				floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])

									lowerCAmelCase_    :  Any             =				None
									if self.use_labels:
											lowerCAmelCase_    :  Dict             =				ids_tensor([self.batch_size, self.image_size, self.image_size]       ,       self.num_labels)

									lowerCAmelCase_    :  Dict             =				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  : int       ,       A_  : List[str]       ,       A_  : List[Any]       ,       A_  : str):
									lowerCAmelCase_    :  Optional[Any]             =				PoolFormerModel(config=A_)
									model.to(A_)
									model.eval()
									lowerCAmelCase_    :  Dict             =				model(A_)
									lowerCAmelCase_    :  int             =				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  : Any):
									lowerCAmelCase_    :  int             =				self.prepare_config_and_inputs()
									lowerCAmelCase_      ,						lowerCAmelCase_      ,						lowerCAmelCase_    :  List[Any]             =				config_and_inputs
									lowerCAmelCase_    :  Optional[Any]             =				{'''pixel_values''': pixel_values}
									return config, inputs_dict





@require_torch
class        __snake_case		(  UpperCamelCase_		,UpperCamelCase_		,unittest.TestCase		):
							_a       =				(PoolFormerModel, PoolFormerForImageClassification) if is_torch_available() else ()
							_a       =				(
							    {'''feature-extraction''': PoolFormerModel, '''image-classification''': PoolFormerForImageClassification}
							    if is_torch_available()
							    else {}
							)

							_a       =				False
							_a       =				False
							_a       =				False
							_a       =				False
							_a       =				False




							def      UpperCAmelCase__    ( self  : int):
									lowerCAmelCase_    :  Tuple             =				PoolFormerModelTester(self)
									lowerCAmelCase_    :  Any             =				PoolFormerConfigTester(self       ,       config_class=A_)




							def      UpperCAmelCase__    ( self  : Dict):
									self.config_tester.run_common_tests()




							def      UpperCAmelCase__    ( self  : int):
									lowerCAmelCase_    :  Dict             =				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  : Optional[Any]):
									pass




							@unittest.skip('''PoolFormer does not have get_input_embeddings method and get_output_embeddings methods''')
							def      UpperCAmelCase__    ( self  : Optional[int]):
									pass




							def      UpperCAmelCase__    ( self  : Optional[Any]):
									def check_hidden_states_output(A_  : List[Any]       ,       A_  : Union[str, Any]       ,       A_  : Union[str, Any]):
											lowerCAmelCase_    :  Tuple             =				model_class(A_)
											model.to(A_)
											model.eval()

											with torch.no_grad():
													lowerCAmelCase_    :  Optional[Any]             =				model(**self._prepare_for_class(A_       ,       A_))

											lowerCAmelCase_    :  Optional[Any]             =				outputs.hidden_states

											lowerCAmelCase_    :  Dict             =				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,
											    ]       ,       )

									lowerCAmelCase_      ,						lowerCAmelCase_    :  int             =				self.model_tester.prepare_config_and_inputs_for_common()

									for model_class in self.all_model_classes:
											lowerCAmelCase_    :  List[str]             =				True
											check_hidden_states_output(A_       ,       A_       ,       A_)

											# check that output_hidden_states also work using config
											del inputs_dict["output_hidden_states"]
											lowerCAmelCase_    :  List[str]             =				True

											check_hidden_states_output(A_       ,       A_       ,       A_)




							def      UpperCAmelCase__    ( self  : str):
									if not self.model_tester.is_training:
											return

									lowerCAmelCase_      ,						lowerCAmelCase_    :  Any             =				self.model_tester.prepare_config_and_inputs_for_common()
									lowerCAmelCase_    :  List[str]             =				True

									for model_class in self.all_model_classes:
											if model_class in get_values(A_):
													continue
											lowerCAmelCase_    :  int             =				model_class(A_)
											model.to(A_)
											model.train()
											lowerCAmelCase_    :  Optional[Any]             =				self._prepare_for_class(A_       ,       A_       ,       return_labels=A_)
											lowerCAmelCase_    :  List[Any]             =				model(**A_).loss
											loss.backward()




							def      UpperCAmelCase__    ( self  : List[Any]):
									lowerCAmelCase_      ,						lowerCAmelCase_    :  List[Any]             =				self.model_tester.prepare_config_and_inputs_for_common()

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

											lowerCAmelCase_    :  str             =				['''pixel_values''']
											self.assertListEqual(arg_names[:1]       ,       A_)







							@slow
							def      UpperCAmelCase__    ( self  : str):
									for model_name in POOLFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
											lowerCAmelCase_    :  List[Any]             =				PoolFormerModel.from_pretrained(A_)
											self.assertIsNotNone(A_)





def     UpperCamelCase(						):
		lowerCAmelCase_    :  str             =				Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''				)
		return image





@require_torch
class        __snake_case		(  unittest.TestCase		):




							@slow
							def      UpperCAmelCase__    ( self  : Any):
									lowerCAmelCase_    :  int             =				PoolFormerImageProcessor()
									lowerCAmelCase_    :  int             =				PoolFormerForImageClassification.from_pretrained('''sail/poolformer_s12''').to(A_)

									lowerCAmelCase_    :  Dict             =				image_processor(images=prepare_img()       ,       return_tensors='''pt''').to(A_)

									# forward pass
									with torch.no_grad():
											lowerCAmelCase_    :  Tuple             =				model(**A_)

									# verify the logits
									lowerCAmelCase_    :  Union[str, Any]             =				torch.Size((1, 1_0_0_0))
									self.assertEqual(outputs.logits.shape       ,       A_)

									lowerCAmelCase_    :  Tuple             =				torch.tensor([-0.6113, 0.1685, -0.0492]).to(A_)
									self.assertTrue(torch.allclose(outputs.logits[0, :3]       ,       A_       ,       atol=1e-4))










from collections import OrderedDict
from typing import Mapping

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging


A__						:						int          =      logging.get_logger(__name__)

A__						:						Dict          =      {
    '''mnaylor/mega-base-wikitext''': '''https://huggingface.co/mnaylor/mega-base-wikitext/resolve/main/config.json''',
}



class        __snake_case		(  UpperCamelCase_		):
							_a       =				'''mega'''




							def __init__( self  : Any       ,       A_  : Dict=3_0_5_2_2       ,       A_  : int=1_2_8       ,       A_  : str=4       ,       A_  : int=2_5_6       ,       A_  : int=1_6       ,       A_  : str=True       ,       A_  : List[str]=6_4       ,       A_  : Optional[Any]=False       ,       A_  : str=-1       ,       A_  : Optional[int]=None       ,       A_  : Tuple=True       ,       A_  : Tuple="scalenorm"       ,       A_  : Optional[Any]=True       ,       A_  : int="silu"       ,       A_  : Optional[int]="softmax"       ,       A_  : Optional[int]=0.1       ,       A_  : Union[str, Any]=0.1       ,       A_  : Any=0.1       ,       A_  : Dict=False       ,       A_  : int=True       ,       A_  : Tuple=2_5_6       ,       A_  : int=True       ,       A_  : List[Any]=0.1       ,       A_  : Optional[Any]=2_0_4_8       ,       A_  : Dict=False       ,       A_  : Dict=2       ,       A_  : Tuple=0.02       ,       A_  : List[Any]=0.2       ,       A_  : str=0.02       ,       A_  : List[str]=1.0       ,       A_  : Union[str, Any]=1       ,       A_  : List[Any]=0       ,       A_  : int=2       ,       A_  : Tuple="rotary"       ,       A_  : Any=None       ,       A_  : Tuple=True       ,       A_  : Any=True       ,       **A_  : Optional[int]       ,       ):
									super().__init__(pad_token_id=A_       ,       bos_token_id=A_       ,       eos_token_id=A_       ,       **A_)

									lowerCAmelCase_    :  Tuple             =				vocab_size
									lowerCAmelCase_    :  str             =				hidden_size
									lowerCAmelCase_    :  Any             =				num_hidden_layers
									lowerCAmelCase_    :  Optional[int]             =				activation
									lowerCAmelCase_    :  Any             =				attention_activation
									lowerCAmelCase_    :  List[Any]             =				intermediate_size
									lowerCAmelCase_    :  Any             =				ema_projection_size
									lowerCAmelCase_    :  Optional[int]             =				bidirectional
									lowerCAmelCase_    :  Tuple             =				shared_representation_size
									lowerCAmelCase_    :  Any             =				use_chunking
									lowerCAmelCase_    :  List[str]             =				chunk_size
									lowerCAmelCase_    :  int             =				truncation
									lowerCAmelCase_    :  Tuple             =				normalize_before_mega
									lowerCAmelCase_    :  Tuple             =				normalization_type
									lowerCAmelCase_    :  List[str]             =				norm_affine
									lowerCAmelCase_    :  List[str]             =				dropout_prob
									lowerCAmelCase_    :  List[str]             =				hidden_dropout_prob
									lowerCAmelCase_    :  Tuple             =				attention_probs_dropout_prob
									lowerCAmelCase_    :  str             =				use_feature_dropout
									lowerCAmelCase_    :  Union[str, Any]             =				use_normalized_ffn
									lowerCAmelCase_    :  Union[str, Any]             =				nffn_hidden_size
									lowerCAmelCase_    :  int             =				normalize_before_ffn
									lowerCAmelCase_    :  Tuple             =				nffn_activation_dropout_prob
									lowerCAmelCase_    :  List[str]             =				max_positions
									lowerCAmelCase_    :  Union[str, Any]             =				add_token_type_embeddings
									lowerCAmelCase_    :  str             =				type_vocab_size
									lowerCAmelCase_    :  int             =				initializer_range
									lowerCAmelCase_    :  str             =				ema_delta_alpha_range
									lowerCAmelCase_    :  Tuple             =				ema_beta_range
									lowerCAmelCase_    :  Any             =				ema_gamma_omega_range
									lowerCAmelCase_    :  Any             =				relative_positional_bias
									lowerCAmelCase_    :  Optional[int]             =				use_cache
									lowerCAmelCase_    :  int             =				classifier_dropout
									lowerCAmelCase_    :  List[Any]             =				add_lm_hidden_dense_layer
									lowerCAmelCase_    :  Optional[Any]             =				1  # not used but required by Hugging Face





class        __snake_case		(  UpperCamelCase_		):




							@property
							def      UpperCAmelCase__    ( self  : Any):
									if self.task == "multiple-choice":
											lowerCAmelCase_    :  Dict             =				{0: '''batch''', 1: '''choice''', 2: '''sequence'''}
									else:
											lowerCAmelCase_    :  int             =				{0: '''batch''', 1: '''sequence'''}
									return OrderedDict(
									    [
									        ('''input_ids''', dynamic_axis),
									        ('''attention_mask''', dynamic_axis),
									    ])





