


'''simple docstring'''
import inspect
import unittest
from typing import List

import numpy as np

from transformers import EfficientFormerConfig
from transformers.testing_utils import require_tf, require_vision, slow
from transformers.utils import cached_property, is_tf_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
					import tensorflow as tf

					from transformers import (
					    TFEfficientFormerForImageClassification,
					    TFEfficientFormerForImageClassificationWithTeacher,
					    TFEfficientFormerModel,
					)
					from transformers.models.efficientformer.modeling_tf_efficientformer import (
					    TF_EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
					)


if is_vision_available():
					from PIL import Image

					from transformers import EfficientFormerImageProcessor




class        _UpperCamelCase	:


				'''simple docstring'''


				def __init__(     self							,      a_							,      a_ = 1_3							,      a_ = 6_4							,      a_ = 2							,      a_ = 3							,      a_ = 3							,      a_ = True							,      a_ = True							,      a_ = 1_2_8							,      a_=[1_6, 3_2, 6_4, 1_2_8]							,      a_ = 7							,      a_ = 4							,      a_ = 3_7							,      a_ = "gelu"							,      a_ = 0.1							,      a_ = 0.1							,      a_ = 1_0							,      a_ = 0.02							,      a_ = 2							,      a_ = 1							,      a_ = 1_2_8							,      a_ = [2, 2, 2, 2]							,      a_ = 2							,      a_ = 2							,      )    ->  int:
					lowercase						:		Optional[Any]   					=		parent
					lowercase						:		Union[str, Any]   					=		batch_size
					lowercase						:		List[str]   					=		image_size
					lowercase						:		Optional[int]   					=		patch_size
					lowercase						:		Optional[Any]   					=		num_channels
					lowercase						:		str   					=		is_training
					lowercase						:		List[Any]   					=		use_labels
					lowercase						:		str   					=		hidden_size
					lowercase						:		List[Any]   					=		num_hidden_layers
					lowercase						:		List[str]   					=		num_attention_heads
					lowercase						:		List[Any]   					=		intermediate_size
					lowercase						:		List[str]   					=		hidden_act
					lowercase						:		Optional[Any]   					=		hidden_dropout_prob
					lowercase						:		int   					=		attention_probs_dropout_prob
					lowercase						:		List[Any]   					=		type_sequence_label_size
					lowercase						:		List[str]   					=		initializer_range
					lowercase						:		Optional[int]   					=		encoder_stride
					lowercase						:		Union[str, Any]   					=		num_attention_outputs
					lowercase						:		Any   					=		embed_dim
					lowercase						:		Union[str, Any]   					=		embed_dim + 1
					lowercase						:		Dict   					=		resolution
					lowercase						:		Union[str, Any]   					=		depths
					lowercase						:		Optional[int]   					=		hidden_sizes
					lowercase						:		Optional[Any]   					=		dim
					lowercase						:		Dict   					=		mlp_expansion_ratio

				def 	a__		(     self							)    ->  str:
					lowercase						:		Optional[int]   					=		floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]							)

					lowercase						:		List[str]   					=		None
					if self.use_labels:
						lowercase						:		Tuple   					=		ids_tensor([self.batch_size]							,      self.type_sequence_label_size							)

					lowercase						:		int   					=		self.get_config()

					return config, pixel_values, labels

				def 	a__		(     self							)    ->  Any:
					return EfficientFormerConfig(
					    image_size=self.image_size							,      patch_size=self.patch_size							,      num_channels=self.num_channels							,      hidden_size=self.hidden_size							,      num_hidden_layers=self.num_hidden_layers							,      num_attention_heads=self.num_attention_heads							,      intermediate_size=self.intermediate_size							,      hidden_act=self.hidden_act							,      hidden_dropout_prob=self.hidden_dropout_prob							,      attention_probs_dropout_prob=self.attention_probs_dropout_prob							,      is_decoder=a_							,      initializer_range=self.initializer_range							,      encoder_stride=self.encoder_stride							,      resolution=self.resolution							,      depths=self.depths							,      hidden_sizes=self.hidden_sizes							,      dim=self.dim							,      mlp_expansion_ratio=self.mlp_expansion_ratio							,      )

				def 	a__		(     self							,      a_							,      a_							,      a_							)    ->  int:
					lowercase						:		str   					=		TFEfficientFormerModel(config=a_							)
					lowercase						:		Tuple   					=		model(a_							,      training=a_							)
					self.parent.assertEqual(result.last_hidden_state.shape							,      (self.batch_size, self.seq_length, self.hidden_size)							)

				def 	a__		(     self							,      a_							,      a_							,      a_							)    ->  Optional[Any]:
					lowercase						:		int   					=		self.type_sequence_label_size
					lowercase						:		List[Any]   					=		TFEfficientFormerForImageClassification(a_							)
					lowercase						:		Union[str, Any]   					=		model(a_							,      labels=a_							,      training=a_							)
					self.parent.assertEqual(result.logits.shape							,      (self.batch_size, self.type_sequence_label_size)							)

					# test greyscale images
					lowercase						:		List[str]   					=		1
					lowercase						:		Tuple   					=		TFEfficientFormerForImageClassification(a_							)

					lowercase						:		Optional[int]   					=		floats_tensor([self.batch_size, 1, self.image_size, self.image_size]							)
					lowercase						:		Optional[Any]   					=		model(a_							,      labels=a_							)
					self.parent.assertEqual(result.logits.shape							,      (self.batch_size, self.type_sequence_label_size)							)


				def 	a__		(     self							)    ->  Union[str, Any]:
					lowercase						:		Dict   					=		self.prepare_config_and_inputs()
					lowercase					,		lowercase					,		lowercase						:		List[str]   					=		config_and_inputs
					lowercase						:		Any   					=		{"pixel_values": pixel_values}
					return config, inputs_dict




@require_tf
class        _UpperCamelCase	(    SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE						,			unittest.TestCase):


				'''simple docstring'''


				_snake_case						       =				(
				    (
				        TFEfficientFormerModel,
				        TFEfficientFormerForImageClassificationWithTeacher,
				        TFEfficientFormerForImageClassification,
				    )
				    if is_tf_available()
				    else ()
				)
				_snake_case						       =				(
				    {
				        '''feature-extraction''': TFEfficientFormerModel,
				        '''image-classification''': (
				            TFEfficientFormerForImageClassification,
				            TFEfficientFormerForImageClassificationWithTeacher,
				        ),
				    }
				    if is_tf_available()
				    else {}
				)

				_snake_case						       =				False

				_snake_case						       =				False
				_snake_case						       =				False
				_snake_case						       =				False
				_snake_case						       =				False

				def 	a__		(     self							)    ->  Optional[int]:
					lowercase						:		Optional[Any]   					=		TFEfficientFormerModelTester(self							)
					lowercase						:		Any   					=		ConfigTester(
					    self							,      config_class=a_							,      has_text_modality=a_							,      hidden_size=3_7							)

				def 	a__		(     self							)    ->  Optional[Any]:
					self.config_tester.run_common_tests()

				@unittest.skip(reason="EfficientFormer does not use inputs_embeds"							)
				def 	a__		(     self							)    ->  int:
					pass

				@unittest.skip(reason="EfficientFormer does not support input and output embeddings"							)
				def 	a__		(     self							)    ->  Tuple:
					pass

				def 	a__		(     self							)    ->  Dict:
					lowercase					,		lowercase						:		Optional[int]   					=		self.model_tester.prepare_config_and_inputs_for_common()

					for model_class in self.all_model_classes:
						lowercase						:		List[Any]   					=		model_class(a_							)
						lowercase						:		Dict   					=		inspect.signature(model.call							)
						# signature.parameters is an OrderedDict => so arg_names order is deterministic
						lowercase						:		Dict   					=		[*signature.parameters.keys()]

						lowercase						:		Any   					=		["pixel_values"]
						self.assertListEqual(arg_names[:1]							,      a_							)

				def 	a__		(     self							)    ->  Optional[Any]:
					def check_hidden_states_output(a_							,      a_							,      a_							):
						lowercase						:		List[str]   					=		model_class(a_							)

						lowercase						:		Any   					=		model(**self._prepare_for_class(a_							,      a_							)							,      training=a_							)
						lowercase						:		List[str]   					=		outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

						lowercase						:		Optional[Any]   					=		getattr(
						    self.model_tester							,      "expected_num_hidden_layers"							,      self.model_tester.num_hidden_layers + 1							)
						self.assertEqual(len(a_							)							,      a_							)

						if hasattr(self.model_tester							,      "encoder_seq_length"							):
							lowercase						:		List[str]   					=		self.model_tester.encoder_seq_length
							if hasattr(self.model_tester							,      "chunk_length"							) and self.model_tester.chunk_length > 1:
								lowercase						:		str   					=		seq_length * self.model_tester.chunk_length
						else:
							lowercase						:		Any   					=		self.model_tester.seq_length

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

						if config.is_encoder_decoder:
							lowercase						:		int   					=		outputs.decoder_hidden_states

							self.asseretIsInstance(a_							,      (list, tuple)							)
							self.assertEqual(len(a_							)							,      a_							)
							lowercase						:		str   					=		getattr(self.model_tester							,      "seq_length"							,      a_							)
							lowercase						:		Dict   					=		getattr(self.model_tester							,      "decoder_seq_length"							,      a_							)

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

					lowercase					,		lowercase						:		str   					=		self.model_tester.prepare_config_and_inputs_for_common()

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

						# check that output_hidden_states also work using config
						del inputs_dict["output_hidden_states"]
						lowercase						:		Union[str, Any]   					=		True

						check_hidden_states_output(a_							,      a_							,      a_							)

				def 	a__		(     self							,      a_							,      a_							,      a_=False							)    ->  Optional[Any]:
					lowercase						:		Dict   					=		super()._prepare_for_class(a_							,      a_							,      return_labels=a_							)

					if return_labels:
						if model_class.__name__ == "TFEfficientFormerForImageClassificationWithTeacher":
							del inputs_dict["labels"]

					return inputs_dict

				def 	a__		(     self							)    ->  Any:
					lowercase						:		Any   					=		self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_model(*a_							)

				@unittest.skip(reason="EfficientFormer does not implement masked image modeling yet"							)
				def 	a__		(     self							)    ->  Union[str, Any]:
					lowercase						:		int   					=		self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_for_masked_image_modeling(*a_							)

				def 	a__		(     self							)    ->  List[Any]:
					lowercase						:		Optional[int]   					=		self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_for_image_classification(*a_							)

				@slow
				def 	a__		(     self							)    ->  Dict:
					for model_name in TF_EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
						lowercase						:		Union[str, Any]   					=		TFEfficientFormerModel.from_pretrained(a_							)
						self.assertIsNotNone(a_							)

				def 	a__		(     self							)    ->  Dict:
					lowercase					,		lowercase						:		Optional[int]   					=		self.model_tester.prepare_config_and_inputs_for_common()
					lowercase						:		List[str]   					=		True

					lowercase						:		Optional[int]   					=		getattr(self.model_tester							,      "seq_length"							,      a_							)
					lowercase						:		Optional[Any]   					=		getattr(self.model_tester							,      "encoder_seq_length"							,      a_							)
					lowercase						:		int   					=		getattr(self.model_tester							,      "key_length"							,      a_							)
					lowercase						:		Union[str, Any]   					=		getattr(self.model_tester							,      "chunk_length"							,      a_							)

					if chunk_length is not None and hasattr(self.model_tester							,      "num_hashes"							):
						lowercase						:		int   					=		encoder_seq_length * self.model_tester.num_hashes

					for model_class in self.all_model_classes:
						lowercase						:		Optional[Any]   					=		True
						lowercase						:		str   					=		False
						lowercase						:		Tuple   					=		True
						lowercase						:		Union[str, Any]   					=		model_class(a_							)

						lowercase						:		Optional[int]   					=		model(**self._prepare_for_class(a_							,      a_							)							,      training=a_							)
						lowercase						:		int   					=		outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions
						self.assertEqual(len(a_							)							,      self.model_tester.num_attention_outputs							)

						# check that output_attentions also work using config
						del inputs_dict["output_attentions"]
						lowercase						:		List[Any]   					=		True
						lowercase						:		Union[str, Any]   					=		model_class(a_							)
						lowercase						:		str   					=		model(**self._prepare_for_class(a_							,      a_							)							,      training=a_							)

						lowercase						:		Optional[Any]   					=		outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions
						self.assertEqual(len(a_							)							,      self.model_tester.num_attention_outputs							)

						if chunk_length is not None:
							self.assertListEqual(
							    list(attentions[0].shape[-4:]							)							,      [self.model_tester.num_attention_heads, encoder_seq_length, chunk_length, encoder_key_length]							,      )
						else:
							self.assertListEqual(
							    list(attentions[0].shape[-3:]							)							,      [self.model_tester.num_attention_heads, encoder_seq_length, encoder_key_length]							,      )


				def 	a__		(     self							)    ->  int:
					# We use a simplified version of this test for EfficientFormer because it requires training=False
					# and Keras refuses to let us force that during functional construction
					lowercase					,		lowercase						:		List[str]   					=		self.model_tester.prepare_config_and_inputs_for_common()

					for model_class in self.all_model_classes:
						# Prepare our model
						lowercase						:		str   					=		model_class(a_							)
						# These are maximally general inputs for the model, with multiple None dimensions
						# Hopefully this will catch any conditionals that fail for flexible shapes
						lowercase						:		Optional[Any]   					=		{
						    key: tf.keras.Input(shape=val.shape[1:]							,      dtype=val.dtype							,      name=a_							)
						    for key, val in model.input_signature.items()
						    if key in model.dummy_inputs
						}
						lowercase						:		Dict   					=		model(a_							)
						self.assertTrue(outputs_dict is not None							)




def 	_A  (       )  ->				Union[str, Any]:
	lowercase						:		Optional[Any]   					=		Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"							)
	return image






@require_tf
@require_vision
class        _UpperCamelCase	(    unittest.TestCase):


				'''simple docstring'''


				@cached_property
				def 	a__		(     self							)    ->  List[Any]:
					return (
					    EfficientFormerImageProcessor.from_pretrained("snap-research/efficientformer-l1-300"							)
					    if is_vision_available()
					    else None
					)

				@slow
				def 	a__		(     self							)    ->  int:
					lowercase						:		Any   					=		TFEfficientFormerForImageClassification.from_pretrained("snap-research/efficientformer-l1-300"							)
					lowercase						:		Union[str, Any]   					=		self.default_image_processor
					lowercase						:		Optional[Any]   					=		prepare_img()
					lowercase						:		Tuple   					=		image_processor(images=a_							,      return_tensors="tf"							)
					# forward pass
					lowercase						:		Dict   					=		model(**a_							,      training=a_							)
					# verify the logits
					lowercase						:		List[Any]   					=		tf.TensorShape((1, 1_0_0_0)							)
					self.assertEqual(outputs.logits.shape							,      a_							)
					lowercase						:		Tuple   					=		tf.constant([-0.05_55, 0.48_25, -0.08_52]							)
					self.assertTrue(np.allclose(outputs.logits[0, :3]							,      a_							,      atol=1e-4							)							)


				@slow
				def 	a__		(     self							)    ->  int:
					lowercase						:		Union[str, Any]   					=		TFEfficientFormerForImageClassificationWithTeacher.from_pretrained(
					    "snap-research/efficientformer-l1-300"							)
					lowercase						:		List[str]   					=		self.default_image_processor
					lowercase						:		str   					=		prepare_img()
					lowercase						:		Optional[int]   					=		image_processor(images=a_							,      return_tensors="tf"							)
					# forward pass
					lowercase						:		List[str]   					=		model(**a_							,      training=a_							)
					# verify the logits
					lowercase						:		Optional[Any]   					=		tf.TensorShape((1, 1_0_0_0)							)
					self.assertEqual(outputs.logits.shape							,      a_							)
					lowercase						:		Any   					=		tf.constant([-0.13_12, 0.43_53, -1.04_99]							)
					self.assertTrue(np.allclose(outputs.logits[0, :3]							,      a_							,      atol=1e-4							)							)






'''simple docstring'''
import unittest

import numpy as np

from transformers import DistilBertConfig, is_flax_available
from transformers.testing_utils import require_flax, slow

from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask


if is_flax_available():
					import jax.numpy as jnp

					from transformers.models.distilbert.modeling_flax_distilbert import (
					    FlaxDistilBertForMaskedLM,
					    FlaxDistilBertForMultipleChoice,
					    FlaxDistilBertForQuestionAnswering,
					    FlaxDistilBertForSequenceClassification,
					    FlaxDistilBertForTokenClassification,
					    FlaxDistilBertModel,
					)




class        _UpperCamelCase	(    unittest.TestCase):


				'''simple docstring'''


				def __init__(     self							,      a_							,      a_=1_3							,      a_=7							,      a_=True							,      a_=True							,      a_=True							,      a_=True							,      a_=9_9							,      a_=3_2							,      a_=5							,      a_=4							,      a_=3_7							,      a_="gelu"							,      a_=0.1							,      a_=0.1							,      a_=5_1_2							,      a_=1_6							,      a_=2							,      a_=0.02							,      a_=4							,      )    ->  Tuple:
					lowercase						:		Optional[Any]   					=		parent
					lowercase						:		int   					=		batch_size
					lowercase						:		int   					=		seq_length
					lowercase						:		List[str]   					=		is_training
					lowercase						:		str   					=		use_attention_mask
					lowercase						:		List[str]   					=		use_token_type_ids
					lowercase						:		Optional[Any]   					=		use_labels
					lowercase						:		Dict   					=		vocab_size
					lowercase						:		Union[str, Any]   					=		hidden_size
					lowercase						:		int   					=		num_hidden_layers
					lowercase						:		Optional[Any]   					=		num_attention_heads
					lowercase						:		Optional[Any]   					=		intermediate_size
					lowercase						:		int   					=		hidden_act
					lowercase						:		Dict   					=		hidden_dropout_prob
					lowercase						:		Optional[Any]   					=		attention_probs_dropout_prob
					lowercase						:		Dict   					=		max_position_embeddings
					lowercase						:		Tuple   					=		type_vocab_size
					lowercase						:		int   					=		type_sequence_label_size
					lowercase						:		Optional[Any]   					=		initializer_range
					lowercase						:		Union[str, Any]   					=		num_choices

				def 	a__		(     self							)    ->  Optional[int]:
					lowercase						:		List[Any]   					=		ids_tensor([self.batch_size, self.seq_length]							,      self.vocab_size							)

					lowercase						:		Any   					=		None
					if self.use_attention_mask:
						lowercase						:		str   					=		random_attention_mask([self.batch_size, self.seq_length]							)

					lowercase						:		Optional[Any]   					=		DistilBertConfig(
					    vocab_size=self.vocab_size							,      dim=self.hidden_size							,      n_layers=self.num_hidden_layers							,      n_heads=self.num_attention_heads							,      hidden_dim=self.intermediate_size							,      hidden_act=self.hidden_act							,      dropout=self.hidden_dropout_prob							,      attention_dropout=self.attention_probs_dropout_prob							,      max_position_embeddings=self.max_position_embeddings							,      initializer_range=self.initializer_range							,      tie_weights_=a_							,      )

					return config, input_ids, attention_mask


				def 	a__		(     self							)    ->  List[str]:
					lowercase						:		Dict   					=		self.prepare_config_and_inputs()
					lowercase					,		lowercase					,		lowercase						:		Dict   					=		config_and_inputs
					lowercase						:		Any   					=		{"input_ids": input_ids, "attention_mask": attention_mask}
					return config, inputs_dict




@require_flax
class        _UpperCamelCase	(    SCREAMING_SNAKE_CASE						,			unittest.TestCase):


				'''simple docstring'''


				_snake_case						       =				(
				    (
				        FlaxDistilBertModel,
				        FlaxDistilBertForMaskedLM,
				        FlaxDistilBertForMultipleChoice,
				        FlaxDistilBertForQuestionAnswering,
				        FlaxDistilBertForSequenceClassification,
				        FlaxDistilBertForTokenClassification,
				        FlaxDistilBertForQuestionAnswering,
				    )
				    if is_flax_available()
				    else ()
				)

				def 	a__		(     self							)    ->  Dict:
					lowercase						:		Optional[int]   					=		FlaxDistilBertModelTester(self							)


				@slow
				def 	a__		(     self							)    ->  Union[str, Any]:
					for model_class_name in self.all_model_classes:
						lowercase						:		int   					=		model_class_name.from_pretrained("distilbert-base-uncased"							)
						lowercase						:		Tuple   					=		model(np.ones((1, 1)							)							)
						self.assertIsNotNone(a_							)




@require_flax
class        _UpperCamelCase	(    unittest.TestCase):


				'''simple docstring'''


				@slow
				def 	a__		(     self							)    ->  Union[str, Any]:
					lowercase						:		str   					=		FlaxDistilBertModel.from_pretrained("distilbert-base-uncased"							)
					lowercase						:		int   					=		np.array([[0, 3_4_5, 2_3_2, 3_2_8, 7_4_0, 1_4_0, 1_6_9_5, 6_9, 6_0_7_8, 1_5_8_8, 2]]							)
					lowercase						:		int   					=		np.array([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]							)
					lowercase						:		List[str]   					=		model(a_							,      attention_mask=a_							)[0]
					lowercase						:		int   					=		(1, 1_1, 7_6_8)
					self.assertEqual(output.shape							,      a_							)
					lowercase						:		List[str]   					=		np.array([[[-0.16_39, 0.32_99, 0.16_48], [-0.17_46, 0.32_89, 0.17_10], [-0.18_84, 0.33_57, 0.18_10]]]							)

					self.assertTrue(jnp.allclose(output[:, 1:4, 1:4]							,      a_							,      atol=1e-4							)							)


