
"""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 	A_       :




	'''simple docstring'''


	def __init__(	self		,   snake_case		,   snake_case=13		,   snake_case=32		,   snake_case=3		,   snake_case=[3, 3, 5]		,   snake_case=[32, 16, 24]		,   snake_case=[16, 24, 40]		,   snake_case=[1, 1, 2]		,   snake_case=[1, 1, 2]		,   snake_case=[1, 6, 6]		,   snake_case=True		,   snake_case=True		,   snake_case=37		,   snake_case="gelu"		,   snake_case=10		,   ):
		lowercase					  =   parent
		lowercase					  =   batch_size
		lowercase					  =   image_size
		lowercase					  =   num_channels
		lowercase					  =   kernel_sizes
		lowercase					  =   in_channels
		lowercase					  =   out_channels
		lowercase					  =   strides
		lowercase					  =   num_block_repeats
		lowercase					  =   expand_ratios
		lowercase					  =   is_training
		lowercase					  =   hidden_act
		lowercase					  =   num_labels
		lowercase					  =   use_labels





	def      SCREAMING_SNAKE_CASE__						(	self	):
		lowercase					  =   floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]	)

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

		lowercase					  =   self.get_config()
		return config, pixel_values, labels





	def      SCREAMING_SNAKE_CASE__						(	self	):
		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      SCREAMING_SNAKE_CASE__						(	self		,   snake_case		,   snake_case		,   snake_case	):
		lowercase					  =   EfficientNetModel(config=__lowercase	)
		model.to(__lowercase	)
		model.eval()
		lowercase					  =   model(__lowercase	)
		# 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      SCREAMING_SNAKE_CASE__						(	self		,   snake_case		,   snake_case		,   snake_case	):
		lowercase					  =   EfficientNetForImageClassification(__lowercase	)
		model.to(__lowercase	)
		model.eval()
		lowercase					  =   model(__lowercase		,   labels=__lowercase	)
		self.parent.assertEqual(result.logits.shape		,   (self.batch_size, self.num_labels)	)





	def      SCREAMING_SNAKE_CASE__						(	self	):
		lowercase					  =   self.prepare_config_and_inputs()
		lowercase  , lowercase  , lowercase					  =   config_and_inputs
		lowercase					  =   {'pixel_values': pixel_values}
		return config, inputs_dict







@require_torch
class 	A_       (      UpperCAmelCase__				,     UpperCAmelCase__				,     unittest.TestCase       ):




	'''simple docstring'''


	_UpperCamelCase					:					Optional[Any]										=	(EfficientNetModel, EfficientNetForImageClassification) if is_torch_available() else ()
	_UpperCamelCase					:					str										=	(
	    {"""feature-extraction""": EfficientNetModel, """image-classification""": EfficientNetForImageClassification}
	    if is_torch_available()
	    else {}
	)

	_UpperCamelCase					:					str										=	False
	_UpperCamelCase					:					Tuple										=	False
	_UpperCamelCase					:					int										=	False
	_UpperCamelCase					:					Tuple										=	False
	_UpperCamelCase					:					List[Any]										=	False





	def      SCREAMING_SNAKE_CASE__						(	self	):
		lowercase					  =   EfficientNetModelTester(self	)
		lowercase					  =   ConfigTester(
		    self		,   config_class=__lowercase		,   has_text_modality=__lowercase		,   hidden_size=37	)





	def      SCREAMING_SNAKE_CASE__						(	self	):
		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      SCREAMING_SNAKE_CASE__						(	self	):
		return





	@unittest.skip(reason='EfficientNet does not use inputs_embeds'	)
	def      SCREAMING_SNAKE_CASE__						(	self	):
		pass





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





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





	def      SCREAMING_SNAKE_CASE__						(	self	):
		lowercase  , lowercase					  =   self.model_tester.prepare_config_and_inputs_for_common()

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

			lowercase					  =   ['pixel_values']
			self.assertListEqual(arg_names[:1]		,   __lowercase	)





	def      SCREAMING_SNAKE_CASE__						(	self	):
		lowercase					  =   self.model_tester.prepare_config_and_inputs()
		self.model_tester.create_and_check_model(*__lowercase	)





	def      SCREAMING_SNAKE_CASE__						(	self	):






		def check_hidden_states_output(snake_case		,   snake_case		,   snake_case	):
			lowercase					  =   model_class(__lowercase	)
			model.to(__lowercase	)
			model.eval()

			with torch.no_grad():
				lowercase					  =   model(**self._prepare_for_class(__lowercase		,   __lowercase	)	)

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

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

		lowercase  , lowercase					  =   self.model_tester.prepare_config_and_inputs_for_common()

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

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

			check_hidden_states_output(__lowercase		,   __lowercase		,   __lowercase	)





	def      SCREAMING_SNAKE_CASE__						(	self	):
		lowercase					  =   self.model_tester.prepare_config_and_inputs()
		self.model_tester.create_and_check_for_image_classification(*__lowercase	)





	@unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.'	)
	def      SCREAMING_SNAKE_CASE__						(	self	):
		pass





	@slow
	def      SCREAMING_SNAKE_CASE__						(	self	):






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





	@is_pipeline_test
	@require_vision
	@slow
	def      SCREAMING_SNAKE_CASE__						(	self	):
		super().test_pipeline_image_classification()






def 							UpperCAmelCase_		(							):
	lowercase					  =   Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'							)
	return image







@require_torch
@require_vision
class 	A_       (      unittest.TestCase       ):




	'''simple docstring'''


	@cached_property
	def      SCREAMING_SNAKE_CASE__						(	self	):
		return AutoImageProcessor.from_pretrained('google/efficientnet-b7'	) if is_vision_available() else None





	@slow
	def      SCREAMING_SNAKE_CASE__						(	self	):
		lowercase					  =   EfficientNetForImageClassification.from_pretrained('google/efficientnet-b7'	).to(__lowercase	)

		lowercase					  =   self.default_image_processor
		lowercase					  =   prepare_img()
		lowercase					  =   image_processor(images=__lowercase		,   return_tensors='pt'	).to(__lowercase	)

		# forward pass
		with torch.no_grad():
			lowercase					  =   model(**__lowercase	)

		# verify the logits
		lowercase					  =   torch.Size((1, 1000)	)
		self.assertEqual(outputs.logits.shape		,   __lowercase	)

		lowercase					  =   torch.tensor([0.0_001, 0.0_002, 0.0_002]	).to(__lowercase	)
		self.assertTrue(torch.allclose(outputs.logits[0, :3]		,   __lowercase		,   atol=1E-4	)	)



# This test is meant to be run in on an instance with TPUs like this:
#
#   python examples/pytorch/xla_spawn.py --num_cores=8 tests/test_trainer_tpu.py
#
# Replace 8 with the number of TPU cores you have.
#

import sys
from typing import Dict

from transformers import EvalPrediction, HfArgumentParser, TrainingArguments, is_torch_available
from transformers.utils import logging


UpperCAmelCase     				=			logging.get_logger(__name__)


if is_torch_available():
	import torch
	from torch import nn
	from torch.utils.data import Dataset

	from transformers import Trainer







	class 	A_       (      __lowerCamelCase       ):




		'''simple docstring'''


		def __init__(	self		,   snake_case = 101	):
			lowercase					  =   length





		def __len__(	self	):
			return self.length





		def __getitem__(	self		,   snake_case	):
			return i







	class 	A_       :




		'''simple docstring'''


		def __call__(	self		,   snake_case	):
			return {"input_ids": torch.tensor(snake_case	), "labels": torch.tensor(snake_case	)}







	class 	A_       (      nn.Module       ):




		'''simple docstring'''


		def __init__(	self	):
			super().__init__()
			# Add some (unused) params otherwise DDP will complain.
			lowercase					  =   nn.Linear(120		,   80	)





		def      SCREAMING_SNAKE_CASE__						(	self		,   snake_case		,   snake_case=None	):
			if labels is not None:
				return torch.tensor(0.0		,   device=input_ids.device	), input_ids
			else:
				return input_ids






def 							UpperCAmelCase_		(							):
	lowercase					  =   HfArgumentParser((TrainingArguments,)							)
	sys.argv += ["--output_dir", "./examples"]
	lowercase					  =   parser.parse_args_into_dataclasses()[0]

	logger.warning(
	    F'''Process rank: {training_args.local_rank}, device: {training_args.device}, '''
	    F'''tpu_num_cores: {training_args.tpu_num_cores}'''			,							)

	# Essentially, what we want to verify in the distributed case is
	# that we get all samples back, in the right order.
	# (this is crucial for prediction for instance)
	for dataset_length in [1001, 256, 15]:
		lowercase					  =   DummyDataset(__SCREAMING_SNAKE_CASE							)

		def compute_metrics(__SCREAMING_SNAKE_CASE							) -> Dict:
			lowercase					  =   list(range(len(__SCREAMING_SNAKE_CASE							)							)							)
			lowercase					  =   p.predictions.tolist() == sequential and p.label_ids.tolist() == sequential
			return {"success": success}

		lowercase					  =   Trainer(
		    model=DummyModel()			,							args=__SCREAMING_SNAKE_CASE			,							data_collator=DummyDataCollator()			,							eval_dataset=__SCREAMING_SNAKE_CASE			,							compute_metrics=__SCREAMING_SNAKE_CASE			,							)
		lowercase					  =   trainer.evaluate()
		logger.info(__SCREAMING_SNAKE_CASE							)
		if metrics["eval_success"] is not True:
			logger.error(__SCREAMING_SNAKE_CASE							)
			exit(1							)

		lowercase					  =   trainer.predict(__SCREAMING_SNAKE_CASE							)
		logger.info(p.metrics							)
		if p.metrics["test_success"] is not True:
			logger.error(p.metrics							)
			exit(1							)

		lowercase					  =   2

		lowercase					  =   trainer.evaluate()
		logger.info(__SCREAMING_SNAKE_CASE							)
		if metrics["eval_success"] is not True:
			logger.error(__SCREAMING_SNAKE_CASE							)
			exit(1							)

		lowercase					  =   trainer.predict(__SCREAMING_SNAKE_CASE							)
		logger.info(p.metrics							)
		if p.metrics["test_success"] is not True:
			logger.error(p.metrics							)
			exit(1							)

		lowercase					  =   None

	logger.info('🔥 All distributed tests successful'							)






def 							UpperCAmelCase_		(							__SCREAMING_SNAKE_CASE							):
	# For xla_spawn (TPUs)
	main()


if __name__ == "__main__":
	main()

