





'''simple docstring'''







import inspect
import unittest

from transformers import EfficientNetConfig
from transformers.testing_utils import is_pipeline_test, require_torch, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

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 EfficientNetForImageClassification, EfficientNetModel
	from transformers.models.efficientnet.modeling_efficientnet import EFFICIENTNET_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
	from PIL import Image

	from transformers import AutoImageProcessor





class     _UpperCAmelCase							:
		def __init__(  self,__SCREAMING_SNAKE_CASE,__SCREAMING_SNAKE_CASE=13,__SCREAMING_SNAKE_CASE=32,__SCREAMING_SNAKE_CASE=3,__SCREAMING_SNAKE_CASE=[3, 3, 5],__SCREAMING_SNAKE_CASE=[32, 16, 24],__SCREAMING_SNAKE_CASE=[16, 24, 40],__SCREAMING_SNAKE_CASE=[1, 1, 2],__SCREAMING_SNAKE_CASE=[1, 1, 2],__SCREAMING_SNAKE_CASE=[1, 6, 6],__SCREAMING_SNAKE_CASE=True,__SCREAMING_SNAKE_CASE=True,__SCREAMING_SNAKE_CASE=37,__SCREAMING_SNAKE_CASE="gelu",__SCREAMING_SNAKE_CASE=10,):



					'''simple docstring'''

					__lowerCAmelCase											=				parent
					__lowerCAmelCase											=				batch_size
					__lowerCAmelCase											=				image_size
					__lowerCAmelCase											=				num_channels
					__lowerCAmelCase											=				kernel_sizes
					__lowerCAmelCase											=				in_channels
					__lowerCAmelCase											=				out_channels
					__lowerCAmelCase											=				strides
					__lowerCAmelCase											=				num_block_repeats
					__lowerCAmelCase											=				expand_ratios
					__lowerCAmelCase											=				is_training
					__lowerCAmelCase											=				hidden_act
					__lowerCAmelCase											=				num_labels
					__lowerCAmelCase											=				use_labels
		def   lowerCamelCase__			(  self			):



					'''simple docstring'''

					__lowerCAmelCase											=				floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]			)

					__lowerCAmelCase											=				None
					if self.use_labels:
								__lowerCAmelCase											=				ids_tensor([self.batch_size],self.num_labels			)

					__lowerCAmelCase											=				self.get_config()
					return config, pixel_values, labels
		def   lowerCamelCase__			(  self			):



					'''simple docstring'''

					return EfficientNetConfig(
					    num_channels=self.num_channels,kernel_sizes=self.kernel_sizes,in_channels=self.in_channels,out_channels=self.out_channels,strides=self.strides,num_block_repeats=self.num_block_repeats,expand_ratios=self.expand_ratios,hidden_act=self.hidden_act,num_labels=self.num_labels,)
		def   lowerCamelCase__			(  self,__SCREAMING_SNAKE_CASE,__SCREAMING_SNAKE_CASE,__SCREAMING_SNAKE_CASE			):



					'''simple docstring'''

					__lowerCAmelCase											=				EfficientNetModel(config=__SCREAMING_SNAKE_CASE			)
					model.to(__SCREAMING_SNAKE_CASE			)
					model.eval()
					__lowerCAmelCase											=				model(__SCREAMING_SNAKE_CASE			)
					# expected last hidden states: B, C, H // 4, W // 4
					self.parent.assertEqual(
					    result.last_hidden_state.shape,(self.batch_size, config.hidden_dim, self.image_size // 4, self.image_size // 4),)
		def   lowerCamelCase__			(  self,__SCREAMING_SNAKE_CASE,__SCREAMING_SNAKE_CASE,__SCREAMING_SNAKE_CASE			):



					'''simple docstring'''

					__lowerCAmelCase											=				EfficientNetForImageClassification(__SCREAMING_SNAKE_CASE			)
					model.to(__SCREAMING_SNAKE_CASE			)
					model.eval()
					__lowerCAmelCase											=				model(__SCREAMING_SNAKE_CASE,labels=__SCREAMING_SNAKE_CASE			)
					self.parent.assertEqual(result.logits.shape,(self.batch_size, self.num_labels)			)







		def   lowerCamelCase__			(  self			):



					'''simple docstring'''

					__lowerCAmelCase											=				self.prepare_config_and_inputs()
					__lowerCAmelCase						,       __lowerCAmelCase						,       __lowerCAmelCase											=				config_and_inputs
					__lowerCAmelCase											=				{"""pixel_values""": pixel_values}
					return config, inputs_dict





@require_torch
class     _UpperCAmelCase							(						lowerCAmelCase_	,					lowerCAmelCase_	,					unittest.TestCase   ):
		a   :   str     =(EfficientNetModel, EfficientNetForImageClassification) if is_torch_available() else ()
		a   :   int     =(
		    {"""feature-extraction""": EfficientNetModel, """image-classification""": EfficientNetForImageClassification}
		    if is_torch_available()
		    else {}
		)

		a   :   List[Any]     =False
		a   :   Optional[Any]     =False
		a   :   Any     =False
		a   :   str     =False
		a   :   Dict     =False
		def   lowerCamelCase__			(  self			):



					'''simple docstring'''

					__lowerCAmelCase											=				EfficientNetModelTester(self			)
					__lowerCAmelCase											=				ConfigTester(
					    self,config_class=__SCREAMING_SNAKE_CASE,has_text_modality=__SCREAMING_SNAKE_CASE,hidden_size=37			)
		def   lowerCamelCase__			(  self			):



					'''simple docstring'''

					self.create_and_test_config_common_properties()
					self.config_tester.create_and_test_config_to_json_string()
					self.config_tester.create_and_test_config_to_json_file()
					self.config_tester.create_and_test_config_from_and_save_pretrained()
					self.config_tester.create_and_test_config_with_num_labels()
					self.config_tester.check_config_can_be_init_without_params()
					self.config_tester.check_config_arguments_init()
		def   lowerCamelCase__			(  self			):



					'''simple docstring'''

					return
		@unittest.skip(reason="""EfficientNet does not use inputs_embeds"""			)
		def   lowerCamelCase__			(  self			):



					'''simple docstring'''

					pass
		@unittest.skip(reason="""EfficientNet does not support input and output embeddings"""			)
		def   lowerCamelCase__			(  self			):



					'''simple docstring'''

					pass
		@unittest.skip(reason="""EfficientNet does not use feedforward chunking"""			)
		def   lowerCamelCase__			(  self			):



					'''simple docstring'''

					pass
		def   lowerCamelCase__			(  self			):



					'''simple docstring'''

					__lowerCAmelCase						,       __lowerCAmelCase											=				self.model_tester.prepare_config_and_inputs_for_common()

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

								__lowerCAmelCase											=				["""pixel_values"""]
								self.assertListEqual(arg_names[:1],__SCREAMING_SNAKE_CASE			)
		def   lowerCamelCase__			(  self			):



					'''simple docstring'''

					__lowerCAmelCase											=				self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_model(*__SCREAMING_SNAKE_CASE			)
		def   lowerCamelCase__			(  self			):



					'''simple docstring'''

					def check_hidden_states_output(__SCREAMING_SNAKE_CASE,__SCREAMING_SNAKE_CASE,__SCREAMING_SNAKE_CASE			):
								__lowerCAmelCase											=				model_class(__SCREAMING_SNAKE_CASE			)
								model.to(__SCREAMING_SNAKE_CASE			)
								model.eval()

								with torch.no_grad():
											__lowerCAmelCase											=				model(**self._prepare_for_class(__SCREAMING_SNAKE_CASE,__SCREAMING_SNAKE_CASE			)			)

								__lowerCAmelCase											=				outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states
								__lowerCAmelCase											=				sum(config.num_block_repeats			) * 4
								self.assertEqual(len(__SCREAMING_SNAKE_CASE			),__SCREAMING_SNAKE_CASE			)

								# EfficientNet's feature maps are of shape (batch_size, num_channels, height, width)
								self.assertListEqual(
								    list(hidden_states[0].shape[-2:]			),[self.model_tester.image_size // 2, self.model_tester.image_size // 2],)

					__lowerCAmelCase						,       __lowerCAmelCase											=				self.model_tester.prepare_config_and_inputs_for_common()

					for model_class in self.all_model_classes:
								__lowerCAmelCase											=				True
								check_hidden_states_output(__SCREAMING_SNAKE_CASE,__SCREAMING_SNAKE_CASE,__SCREAMING_SNAKE_CASE			)

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

								check_hidden_states_output(__SCREAMING_SNAKE_CASE,__SCREAMING_SNAKE_CASE,__SCREAMING_SNAKE_CASE			)
		def   lowerCamelCase__			(  self			):



					'''simple docstring'''

					__lowerCAmelCase											=				self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_for_image_classification(*__SCREAMING_SNAKE_CASE			)
		@unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests."""			)
		def   lowerCamelCase__			(  self			):



					'''simple docstring'''

					pass
		@slow
		def   lowerCamelCase__			(  self			):



					'''simple docstring'''

					for model_name in EFFICIENTNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
								__lowerCAmelCase											=				EfficientNetModel.from_pretrained(__SCREAMING_SNAKE_CASE			)
								self.assertIsNotNone(__SCREAMING_SNAKE_CASE			)







		@is_pipeline_test
		@require_vision
		@slow
		def   lowerCamelCase__			(  self			):



					'''simple docstring'''

					super().test_pipeline_image_classification()





def    _lowerCAmelCase						(						)					->					Dict:
			__lowerCAmelCase											=				Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""	)
			return image







@require_torch
@require_vision
class     _UpperCAmelCase							(						unittest.TestCase   ):
		@cached_property
		def   lowerCamelCase__			(  self			):



					'''simple docstring'''

					return AutoImageProcessor.from_pretrained("""google/efficientnet-b7"""			) if is_vision_available() else None







		@slow
		def   lowerCamelCase__			(  self			):



					'''simple docstring'''

					__lowerCAmelCase											=				EfficientNetForImageClassification.from_pretrained("""google/efficientnet-b7"""			).to(__SCREAMING_SNAKE_CASE			)

					__lowerCAmelCase											=				self.default_image_processor
					__lowerCAmelCase											=				prepare_img()
					__lowerCAmelCase											=				image_processor(images=__SCREAMING_SNAKE_CASE,return_tensors="""pt"""			).to(__SCREAMING_SNAKE_CASE			)

					# forward pass
					with torch.no_grad():
								__lowerCAmelCase											=				model(**__SCREAMING_SNAKE_CASE			)

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

					__lowerCAmelCase											=				torch.tensor([0.0001, 0.0002, 0.0002]			).to(__SCREAMING_SNAKE_CASE			)
					self.assertTrue(torch.allclose(outputs.logits[0, :3],__SCREAMING_SNAKE_CASE,atol=1e-4			)			)








'''simple docstring'''







import json
import os
import tempfile

import datasets
from datasets.arrow_writer import ArrowWriter
from datasets.features import ArrayaD
from utils import generate_examples, get_duration


_a					: Dict      =    (3_0, 4_8_7)
_a					: int      =    (3_6, 1_0_2_4)
_a					: str      =    (1_0_0, 1_0_0)
_a					: Tuple      =    1_0_0

_a					: List[str]      =    datasets.Features(
    {"""text""": ArrayaD(SHAPE_TEST_1, dtype="""float32"""), """image""": ArrayaD(SHAPE_TEST_2, dtype="""float32""")}
)

_a    ,_a					: Optional[int]      =    os.path.split(__file__)
_a					: List[Any]      =    os.path.join(RESULTS_BASEPATH, """results""", RESULTS_FILENAME.replace(""".py""", """.json"""))





@get_duration
def    _lowerCAmelCase						(						lowercase					,	lowercase					,	lowercase	)					->					Optional[Any]:
			with ArrowWriter(features=lowercase					,	path=os.path.join(lowercase					,	"""beta.arrow"""	)	) as writer:
						for key, record in dummy_data:
									__lowerCAmelCase											=				my_features.encode_example(lowercase	)
									writer.write(lowercase	)
						__lowerCAmelCase						,       __lowerCAmelCase											=				writer.finalize()





@get_duration
def    _lowerCAmelCase						(						lowercase					,	lowercase	)					->					List[str]:
			__lowerCAmelCase											=				datasets.Dataset.from_file(
			    filename=os.path.join(lowercase					,	"""beta.arrow"""	)					,	info=datasets.DatasetInfo(features=lowercase	)	)
			for _ in dataset:
						pass





@get_duration
def    _lowerCAmelCase						(						lowercase					,	lowercase	)					->					Any:
			__lowerCAmelCase											=				datasets.Dataset.from_file(
			    filename=os.path.join(lowercase					,	"""beta.arrow"""	)					,	info=datasets.DatasetInfo(features=lowercase	)	)
			dataset.set_format("""numpy"""	)
			for _ in dataset:
						pass





@get_duration
def    _lowerCAmelCase						(						lowercase					,	lowercase	)					->					List[str]:
			__lowerCAmelCase											=				10
			__lowerCAmelCase											=				datasets.Dataset.from_file(
			    filename=os.path.join(lowercase					,	"""beta.arrow"""	)					,	info=datasets.DatasetInfo(features=lowercase	)	)
			for i in range(0					,	len(lowercase	)					,	lowercase	):
						__lowerCAmelCase											=				dataset[i : i + batch_size]





@get_duration
def    _lowerCAmelCase						(						lowercase					,	lowercase	)					->					List[str]:
			__lowerCAmelCase											=				10
			__lowerCAmelCase											=				datasets.Dataset.from_file(
			    filename=os.path.join(lowercase					,	"""beta.arrow"""	)					,	info=datasets.DatasetInfo(features=lowercase	)	)
			dataset.set_format("""numpy"""	)
			for i in range(0					,	len(lowercase	)					,	lowercase	):
						__lowerCAmelCase											=				dataset[i : i + batch_size]





@get_duration
def    _lowerCAmelCase						(						lowercase					,	lowercase	)					->					Union[str, Any]:
			__lowerCAmelCase											=				datasets.Dataset.from_file(
			    filename=os.path.join(lowercase					,	"""beta.arrow"""	)					,	info=datasets.DatasetInfo(features=lowercase	)	)
			for col in feats:
						__lowerCAmelCase											=				dataset[col]





@get_duration
def    _lowerCAmelCase						(						lowercase					,	lowercase	)					->					Optional[int]:
			__lowerCAmelCase											=				datasets.Dataset.from_file(
			    filename=os.path.join(lowercase					,	"""beta.arrow"""	)					,	info=datasets.DatasetInfo(features=lowercase	)	)
			dataset.set_format("""numpy"""	)
			for col in feats:
						__lowerCAmelCase											=				dataset[col]





def    _lowerCAmelCase						(						)					->					Optional[Any]:
			__lowerCAmelCase											=				{}
			__lowerCAmelCase											=				(
			    read_unformated,
			    read_formatted_as_numpy,
			    read_batch_unformated,
			    read_batch_formatted_as_numpy,
			    read_col_unformated,
			    read_col_formatted_as_numpy,
			)
			with tempfile.TemporaryDirectory() as tmp_dir:
						__lowerCAmelCase											=				datasets.Features({"""image""": ArrayaD(lowercase					,	dtype="""float32"""	)}	)
						__lowerCAmelCase											=				generate_examples(features=lowercase					,	num_examples=lowercase	)
						__lowerCAmelCase											=				write(lowercase					,	lowercase					,	lowercase	)
						for read_func in read_functions:
									__lowerCAmelCase											=				read_func(lowercase					,	lowercase	)

			with tempfile.TemporaryDirectory() as tmp_dir:
						# don't use fixed length for fair comparison
						# feats = datasets.Features(
						#     {"image": datasets.Sequence(datasets.Sequence(datasets.Value("float32"), SPEED_TEST_SHAPE[1]), SPEED_TEST_SHAPE[0])}
						# )
						__lowerCAmelCase											=				datasets.Features({"""image""": datasets.Sequence(datasets.Sequence(datasets.Value("""float32"""	)	)	)}	)
						__lowerCAmelCase											=				generate_examples(
						    features=lowercase					,	num_examples=lowercase					,	seq_shapes={"""image""": SPEED_TEST_SHAPE}	)
						__lowerCAmelCase											=				write(lowercase					,	lowercase					,	lowercase	)
						for read_func in read_functions:
									__lowerCAmelCase											=				read_func(lowercase					,	lowercase	)

			with tempfile.TemporaryDirectory() as tmp_dir:
						# don't use fixed length for fair comparison
						# feats = datasets.Features(
						#     {"image": datasets.Sequence(datasets.Value("float32"), SPEED_TEST_SHAPE[0] * SPEED_TEST_SHAPE[1])}
						# )
						__lowerCAmelCase											=				datasets.Features({"""image""": datasets.Sequence(datasets.Value("""float32"""	)	)}	)
						__lowerCAmelCase											=				generate_examples(
						    features=lowercase					,	num_examples=lowercase					,	seq_shapes={"""image""": [SPEED_TEST_SHAPE[0] * SPEED_TEST_SHAPE[1]]}					,	)
						__lowerCAmelCase											=				write(lowercase					,	lowercase					,	lowercase	)
						for read_func in read_functions:
									__lowerCAmelCase											=				read_func(lowercase					,	lowercase	)

			with open(lowercase					,	"""wb"""	) as f:
						f.write(json.dumps(lowercase	).encode("""utf-8"""	)	)


if __name__ == "__main__":  # useful to run the profiler
	benchmark_array_xd()

