




import inspect
import unittest

from transformers import MobileNetVaConfig
from transformers.testing_utils import 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 MobileNetVaForImageClassification, MobileNetVaModel
			from transformers.models.mobilenet_va.modeling_mobilenet_va import MOBILENET_V1_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
			from PIL import Image

			from transformers import MobileNetVaImageProcessor






class  __magic_name__						(  __UpperCAmelCase):
				'''simple docstring'''







				def     _A							(							self:   Union[str, Any]		):
											SCREAMING_SNAKE_CASE_   	=    self.config_class(**self.inputs_dict		)
											self.parent.assertTrue(hasattr(_lowerCamelCase		,					'''tf_padding'''		)		)
											self.parent.assertTrue(hasattr(_lowerCamelCase		,					'''depth_multiplier'''		)		)






class  __magic_name__						:
				'''simple docstring'''







				def __init__(							self:   Optional[int]		,					_lowerCamelCase:   Union[str, Any]		,					_lowerCamelCase:   List[Any]=13		,					_lowerCamelCase:   Dict=3		,					_lowerCamelCase:   List[str]=32		,					_lowerCamelCase:   Any=0.25		,					_lowerCamelCase:   int=8		,					_lowerCamelCase:   Union[str, Any]=True		,					_lowerCamelCase:   Tuple=10_24		,					_lowerCamelCase:   Optional[int]=32		,					_lowerCamelCase:   List[Any]="relu6"		,					_lowerCamelCase:   Dict=0.1		,					_lowerCamelCase:   Union[str, Any]=0.02		,					_lowerCamelCase:   Tuple=True		,					_lowerCamelCase:   str=True		,					_lowerCamelCase:   List[Any]=10		,					_lowerCamelCase:   Optional[int]=None		,					):
											SCREAMING_SNAKE_CASE_   	=    parent
											SCREAMING_SNAKE_CASE_   	=    batch_size
											SCREAMING_SNAKE_CASE_   	=    num_channels
											SCREAMING_SNAKE_CASE_   	=    image_size
											SCREAMING_SNAKE_CASE_   	=    depth_multiplier
											SCREAMING_SNAKE_CASE_   	=    min_depth
											SCREAMING_SNAKE_CASE_   	=    tf_padding
											SCREAMING_SNAKE_CASE_   	=    int(last_hidden_size * depth_multiplier		)
											SCREAMING_SNAKE_CASE_   	=    output_stride
											SCREAMING_SNAKE_CASE_   	=    hidden_act
											SCREAMING_SNAKE_CASE_   	=    classifier_dropout_prob
											SCREAMING_SNAKE_CASE_   	=    use_labels
											SCREAMING_SNAKE_CASE_   	=    is_training
											SCREAMING_SNAKE_CASE_   	=    num_labels
											SCREAMING_SNAKE_CASE_   	=    initializer_range
											SCREAMING_SNAKE_CASE_   	=    scope


				def     _A							(							self:   Dict		):
											SCREAMING_SNAKE_CASE_   	=    floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]		)

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

											SCREAMING_SNAKE_CASE_   	=    self.get_config()

											return config, pixel_values, labels, pixel_labels


				def     _A							(							self:   str		):
											return MobileNetVaConfig(
											    num_channels=self.num_channels		,					image_size=self.image_size		,					depth_multiplier=self.depth_multiplier		,					min_depth=self.min_depth		,					tf_padding=self.tf_padding		,					hidden_act=self.hidden_act		,					classifier_dropout_prob=self.classifier_dropout_prob		,					initializer_range=self.initializer_range		,					)


				def     _A							(							self:   List[Any]		,					_lowerCamelCase:   List[str]		,					_lowerCamelCase:   List[Any]		,					_lowerCamelCase:   List[str]		,					_lowerCamelCase:   str		):
											SCREAMING_SNAKE_CASE_   	=    MobileNetVaModel(config=_lowerCamelCase		)
											model.to(_lowerCamelCase		)
											model.eval()
											SCREAMING_SNAKE_CASE_   	=    model(_lowerCamelCase		)
											self.parent.assertEqual(
											    result.last_hidden_state.shape		,					(
											        self.batch_size,
											        self.last_hidden_size,
											        self.image_size // self.output_stride,
											        self.image_size // self.output_stride,
											    )		,					)


				def     _A							(							self:   Dict		,					_lowerCamelCase:   int		,					_lowerCamelCase:   List[str]		,					_lowerCamelCase:   Optional[Any]		,					_lowerCamelCase:   Tuple		):
											SCREAMING_SNAKE_CASE_   	=    self.num_labels
											SCREAMING_SNAKE_CASE_   	=    MobileNetVaForImageClassification(_lowerCamelCase		)
											model.to(_lowerCamelCase		)
											model.eval()
											SCREAMING_SNAKE_CASE_   	=    model(_lowerCamelCase		,					labels=_lowerCamelCase		)
											self.parent.assertEqual(result.logits.shape		,					(self.batch_size, self.num_labels)		)





				def     _A							(							self:   Tuple		):
											SCREAMING_SNAKE_CASE_   	=    self.prepare_config_and_inputs()
											SCREAMING_SNAKE_CASE_	,	SCREAMING_SNAKE_CASE_	,	SCREAMING_SNAKE_CASE_	,	SCREAMING_SNAKE_CASE_   	=    config_and_inputs
											SCREAMING_SNAKE_CASE_   	=    {'''pixel_values''': pixel_values}
											return config, inputs_dict






@require_torch
class  __magic_name__						(  __UpperCAmelCase    ,  __UpperCAmelCase    ,  unittest.TestCase):
				'''simple docstring'''







				SCREAMING_SNAKE_CASE__					:							int	      =					(MobileNetVaModel, MobileNetVaForImageClassification) if is_torch_available() else ()
				SCREAMING_SNAKE_CASE__					:							int	      =					(
				    {"feature-extraction": MobileNetVaModel, "image-classification": MobileNetVaForImageClassification}
				    if is_torch_available()
				    else {}
				)

				SCREAMING_SNAKE_CASE__					:							str	      =					False
				SCREAMING_SNAKE_CASE__					:							int	      =					False
				SCREAMING_SNAKE_CASE__					:							str	      =					False
				SCREAMING_SNAKE_CASE__					:							Optional[Any]	      =					False


				def     _A							(							self:   Optional[Any]		):
											SCREAMING_SNAKE_CASE_   	=    MobileNetVaModelTester(self		)
											SCREAMING_SNAKE_CASE_   	=    MobileNetVaConfigTester(self		,					config_class=_lowerCamelCase		,					has_text_modality=_lowerCamelCase		)


				def     _A							(							self:   List[Any]		):
											self.config_tester.run_common_tests()


				@unittest.skip(reason='''MobileNetV1 does not use inputs_embeds'''		)
				def     _A							(							self:   Optional[int]		):
											pass


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


				@unittest.skip(reason='''MobileNetV1 does not output attentions'''		)
				def     _A							(							self:   str		):
											pass


				def     _A							(							self:   int		):
											SCREAMING_SNAKE_CASE_	,	SCREAMING_SNAKE_CASE_   	=    self.model_tester.prepare_config_and_inputs_for_common()

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

																		SCREAMING_SNAKE_CASE_   	=    ['''pixel_values''']
																		self.assertListEqual(arg_names[:1]		,					_lowerCamelCase		)


				def     _A							(							self:   Dict		):
											SCREAMING_SNAKE_CASE_   	=    self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_model(*_lowerCamelCase		)


				def     _A							(							self:   Tuple		):
											def check_hidden_states_output(_lowerCamelCase:   str		,					_lowerCamelCase:   Union[str, Any]		,					_lowerCamelCase:   int		):
																		SCREAMING_SNAKE_CASE_   	=    model_class(_lowerCamelCase		)
																		model.to(_lowerCamelCase		)
																		model.eval()

																		with torch.no_grad():
																									SCREAMING_SNAKE_CASE_   	=    model(**self._prepare_for_class(_lowerCamelCase		,					_lowerCamelCase		)		)

																		SCREAMING_SNAKE_CASE_   	=    outputs.hidden_states

																		SCREAMING_SNAKE_CASE_   	=    26
																		self.assertEqual(len(_lowerCamelCase		)		,					_lowerCamelCase		)

											SCREAMING_SNAKE_CASE_	,	SCREAMING_SNAKE_CASE_   	=    self.model_tester.prepare_config_and_inputs_for_common()

											for model_class in self.all_model_classes:
																		SCREAMING_SNAKE_CASE_   	=    True
																		check_hidden_states_output(_lowerCamelCase		,					_lowerCamelCase		,					_lowerCamelCase		)

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

																		check_hidden_states_output(_lowerCamelCase		,					_lowerCamelCase		,					_lowerCamelCase		)


				def     _A							(							self:   List[str]		):
											SCREAMING_SNAKE_CASE_   	=    self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_for_image_classification(*_lowerCamelCase		)





				@slow
				def     _A							(							self:   Dict		):
											for model_name in MOBILENET_V1_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																		SCREAMING_SNAKE_CASE_   	=    MobileNetVaModel.from_pretrained(_lowerCamelCase		)
																		self.assertIsNotNone(_lowerCamelCase		)






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






@require_torch
@require_vision
class  __magic_name__						(  unittest.TestCase):
				'''simple docstring'''







				@cached_property
				def     _A							(							self:   int		):
											return (
											    MobileNetVaImageProcessor.from_pretrained('''google/mobilenet_v1_1.0_224'''		) if is_vision_available() else None
											)





				@slow
				def     _A							(							self:   str		):
											SCREAMING_SNAKE_CASE_   	=    MobileNetVaForImageClassification.from_pretrained('''google/mobilenet_v1_1.0_224'''		).to(_lowerCamelCase		)

											SCREAMING_SNAKE_CASE_   	=    self.default_image_processor
											SCREAMING_SNAKE_CASE_   	=    prepare_img()
											SCREAMING_SNAKE_CASE_   	=    image_processor(images=_lowerCamelCase		,					return_tensors='''pt'''		).to(_lowerCamelCase		)

											# forward pass
											with torch.no_grad():
																		SCREAMING_SNAKE_CASE_   	=    model(**_lowerCamelCase		)

											# verify the logits
											SCREAMING_SNAKE_CASE_   	=    torch.Size((1, 10_01)		)
											self.assertEqual(outputs.logits.shape		,					_lowerCamelCase		)

											SCREAMING_SNAKE_CASE_   	=    torch.tensor([-4.17_39, -1.12_33, 3.12_05]		).to(_lowerCamelCase		)

											self.assertTrue(torch.allclose(outputs.logits[0, :3]		,					_lowerCamelCase		,					atol=1E-4		)		)








import math
import time
from typing import Dict, List, Optional

from torch.utils.data import Dataset

from transformers import SeqaSeqTrainer, is_torch_tpu_available
from transformers.trainer_utils import PredictionOutput, speed_metrics


if is_torch_tpu_available(check_device=False):
			import torch_xla.core.xla_model as xm
			import torch_xla.debug.metrics as met






class  __magic_name__						(  __UpperCAmelCase):
				'''simple docstring'''







				def __init__(							self:   List[Any]		,					*_lowerCamelCase:   Tuple		,					_lowerCamelCase:   Optional[Any]=None		,					_lowerCamelCase:   Dict=None		,					**_lowerCamelCase:   Dict		):
											super().__init__(*_lowerCamelCase		,					**_lowerCamelCase		)
											SCREAMING_SNAKE_CASE_   	=    eval_examples
											SCREAMING_SNAKE_CASE_   	=    post_process_function


				def     _A							(							self:   Tuple		,					_lowerCamelCase:   Optional[Dataset] = None		,					_lowerCamelCase:   List[str]=None		,					_lowerCamelCase:   Optional[List[str]] = None		,					_lowerCamelCase:   str = "eval"		,					**_lowerCamelCase:   Union[str, Any]		,					):
											SCREAMING_SNAKE_CASE_   	=    gen_kwargs.copy()
											SCREAMING_SNAKE_CASE_   	=    (
											    gen_kwargs['''max_length'''] if gen_kwargs.get('''max_length'''		) is not None else self.args.generation_max_length
											)
											SCREAMING_SNAKE_CASE_   	=    (
											    gen_kwargs['''num_beams'''] if gen_kwargs.get('''num_beams'''		) is not None else self.args.generation_num_beams
											)
											SCREAMING_SNAKE_CASE_   	=    gen_kwargs

											SCREAMING_SNAKE_CASE_   	=    self.eval_dataset if eval_dataset is None else eval_dataset
											SCREAMING_SNAKE_CASE_   	=    self.get_eval_dataloader(_lowerCamelCase		)
											SCREAMING_SNAKE_CASE_   	=    self.eval_examples if eval_examples is None else eval_examples

											# Temporarily disable metric computation, we will do it in the loop here.
											SCREAMING_SNAKE_CASE_   	=    self.compute_metrics
											SCREAMING_SNAKE_CASE_   	=    None
											SCREAMING_SNAKE_CASE_   	=    time.time()
											SCREAMING_SNAKE_CASE_   	=    self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop
											try:
																		SCREAMING_SNAKE_CASE_   	=    eval_loop(
																		    _lowerCamelCase		,					description='''Evaluation'''		,					prediction_loss_only=True if compute_metrics is None else None		,					ignore_keys=_lowerCamelCase		,					metric_key_prefix=_lowerCamelCase		,					)
											finally:
																		SCREAMING_SNAKE_CASE_   	=    compute_metrics
											SCREAMING_SNAKE_CASE_   	=    self.args.eval_batch_size * self.args.world_size
											if f"{metric_key_prefix}_jit_compilation_time" in output.metrics:
																		start_time += output.metrics[f"{metric_key_prefix}_jit_compilation_time"]
											output.metrics.update(
											    speed_metrics(
											        _lowerCamelCase		,					_lowerCamelCase		,					num_samples=output.num_samples		,					num_steps=math.ceil(output.num_samples / total_batch_size		)		,					)		)

											if self.post_process_function is not None and self.compute_metrics is not None and self.args.should_save:
																		# Only the main node write the results by default
																		SCREAMING_SNAKE_CASE_   	=    self.post_process_function(_lowerCamelCase		,					_lowerCamelCase		,					_lowerCamelCase		)
																		SCREAMING_SNAKE_CASE_   	=    self.compute_metrics(_lowerCamelCase		)

																		# Prefix all keys with metric_key_prefix + '_'
																		for key in list(metrics.keys()		):
																									if not key.startswith(f"{metric_key_prefix}_"		):
																																SCREAMING_SNAKE_CASE_   	=    metrics.pop(_lowerCamelCase		)

																		metrics.update(output.metrics		)
											else:
																		SCREAMING_SNAKE_CASE_   	=    output.metrics

											if self.args.should_log:
																		# Only the main node log the results by default
																		self.log(_lowerCamelCase		)

											if self.args.tpu_metrics_debug or self.args.debug:
																		# tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.)
																		xm.master_print(met.metrics_report()		)

											SCREAMING_SNAKE_CASE_   	=    self.callback_handler.on_evaluate(self.args		,					self.state		,					self.control		,					_lowerCamelCase		)
											return metrics





				def     _A							(							self:   List[str]		,					_lowerCamelCase:   int		,					_lowerCamelCase:   List[str]		,					_lowerCamelCase:   Optional[int]=None		,					_lowerCamelCase:   str = "test"		,					**_lowerCamelCase:   str		):
											SCREAMING_SNAKE_CASE_   	=    gen_kwargs.copy()

											SCREAMING_SNAKE_CASE_   	=    self.get_test_dataloader(_lowerCamelCase		)

											# Temporarily disable metric computation, we will do it in the loop here.
											SCREAMING_SNAKE_CASE_   	=    self.compute_metrics
											SCREAMING_SNAKE_CASE_   	=    None
											SCREAMING_SNAKE_CASE_   	=    time.time()
											SCREAMING_SNAKE_CASE_   	=    self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop
											try:
																		SCREAMING_SNAKE_CASE_   	=    eval_loop(
																		    _lowerCamelCase		,					description='''Prediction'''		,					prediction_loss_only=True if compute_metrics is None else None		,					ignore_keys=_lowerCamelCase		,					metric_key_prefix=_lowerCamelCase		,					)
											finally:
																		SCREAMING_SNAKE_CASE_   	=    compute_metrics

											SCREAMING_SNAKE_CASE_   	=    self.args.eval_batch_size * self.args.world_size
											if f"{metric_key_prefix}_jit_compilation_time" in output.metrics:
																		start_time += output.metrics[f"{metric_key_prefix}_jit_compilation_time"]
											output.metrics.update(
											    speed_metrics(
											        _lowerCamelCase		,					_lowerCamelCase		,					num_samples=output.num_samples		,					num_steps=math.ceil(output.num_samples / total_batch_size		)		,					)		)
											if self.post_process_function is None or self.compute_metrics is None:
																		return output

											SCREAMING_SNAKE_CASE_   	=    self.post_process_function(_lowerCamelCase		,					_lowerCamelCase		,					_lowerCamelCase		,					'''predict'''		)
											SCREAMING_SNAKE_CASE_   	=    self.compute_metrics(_lowerCamelCase		)

											# Prefix all keys with metric_key_prefix + '_'
											for key in list(metrics.keys()		):
																		if not key.startswith(f"{metric_key_prefix}_"		):
																									SCREAMING_SNAKE_CASE_   	=    metrics.pop(_lowerCamelCase		)
											metrics.update(output.metrics		)
											return PredictionOutput(predictions=predictions.predictions		,					label_ids=predictions.label_ids		,					metrics=_lowerCamelCase		)


