
from __future__ import annotations

import inspect
import unittest

import numpy as np

from transformers import ResNetConfig
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 TFResNetForImageClassification, TFResNetModel
		from transformers.models.resnet.modeling_tf_resnet import TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
		from PIL import Image

		from transformers import AutoImageProcessor




class 				lowerCamelCase__							:




	'''simple docstring'''




	def __init__(      self	:List[Any]  ,     a	:int  ,     a	:Dict=3  ,     a	:List[str]=3_2  ,     a	:Any=3  ,     a	:List[str]=1_0  ,     a	:Union[str, Any]=[1_0, 2_0, 3_0, 4_0]  ,     a	:Optional[int]=[1, 1, 2, 1]  ,     a	:Union[str, Any]=True  ,     a	:Any=True  ,     a	:Optional[Any]="relu"  ,     a	:Dict=3  ,     a	:List[str]=None  ,     )	->				Union[str, Any]:
								__UpperCamelCase			:     Optional[Any]         =      parent
								__UpperCamelCase			:     Tuple         =      batch_size
								__UpperCamelCase			:     str         =      image_size
								__UpperCamelCase			:     Dict         =      num_channels
								__UpperCamelCase			:     Optional[Any]         =      embeddings_size
								__UpperCamelCase			:     Any         =      hidden_sizes
								__UpperCamelCase			:     Union[str, Any]         =      depths
								__UpperCamelCase			:     int         =      is_training
								__UpperCamelCase			:     Tuple         =      use_labels
								__UpperCamelCase			:     Dict         =      hidden_act
								__UpperCamelCase			:     Optional[int]         =      num_labels
								__UpperCamelCase			:     Dict         =      scope
								__UpperCamelCase			:     Dict         =      len(a		)







	def      _lowerCamelCase       (      self	:str		)	->				Optional[Any]:
								__UpperCamelCase			:     Optional[Any]         =      floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]		)

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

								__UpperCamelCase			:     Optional[Any]         =      self.get_config()

								return config, pixel_values, labels







	def      _lowerCamelCase       (      self	:List[Any]		)	->				Dict:
								return ResNetConfig(
								    num_channels=self.num_channels  ,     embeddings_size=self.embeddings_size  ,     hidden_sizes=self.hidden_sizes  ,     depths=self.depths  ,     hidden_act=self.hidden_act  ,     num_labels=self.num_labels  ,     image_size=self.image_size  ,     )







	def      _lowerCamelCase       (      self	:Dict  ,     a	:Any  ,     a	:Optional[Any]  ,     a	:Optional[Any]		)	->				Any:
								__UpperCamelCase			:     List[str]         =      TFResNetModel(config=a		)
								__UpperCamelCase			:     Any         =      model(a		)
								# expected last hidden states: B, C, H // 32, W // 32
								self.parent.assertEqual(
								    result.last_hidden_state.shape  ,     (self.batch_size, self.hidden_sizes[-1], self.image_size // 3_2, self.image_size // 3_2)  ,     )







	def      _lowerCamelCase       (      self	:List[str]  ,     a	:Optional[Any]  ,     a	:Dict  ,     a	:Union[str, Any]		)	->				List[Any]:
								__UpperCamelCase			:     Dict         =      self.num_labels
								__UpperCamelCase			:     List[Any]         =      TFResNetForImageClassification(a		)
								__UpperCamelCase			:     Dict         =      model(a  ,     labels=a		)
								self.parent.assertEqual(result.logits.shape  ,     (self.batch_size, self.num_labels)		)







	def      _lowerCamelCase       (      self	:Tuple		)	->				Union[str, Any]:
								__UpperCamelCase			:     Union[str, Any]         =      self.prepare_config_and_inputs()
								__UpperCamelCase     ,		__UpperCamelCase     ,		__UpperCamelCase			:     Tuple         =      config_and_inputs
								__UpperCamelCase			:     int         =      {"pixel_values": pixel_values}
								return config, inputs_dict




@require_tf
class 				lowerCamelCase__							(       __lowercase  ,		__lowercase  ,		unittest.TestCase):




	'''simple docstring'''




	_A			=  (TFResNetModel, TFResNetForImageClassification) if is_tf_available() else ()
	_A			=  (
	    {'feature-extraction': TFResNetModel, 'image-classification': TFResNetForImageClassification}
	    if is_tf_available()
	    else {}
	)

	_A			=  False
	_A			=  False
	_A			=  False
	_A			=  False
	_A			=  False







	def      _lowerCamelCase       (      self	:Tuple		)	->				Union[str, Any]:
								__UpperCamelCase			:     List[str]         =      TFResNetModelTester(self		)
								__UpperCamelCase			:     str         =      ConfigTester(self  ,     config_class=a  ,     has_text_modality=a		)







	def      _lowerCamelCase       (      self	:Tuple		)	->				Any:
								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	:Tuple		)	->				List[str]:
								return







	@unittest.skip(reason="ResNet does not use inputs_embeds"		)
	def      _lowerCamelCase       (      self	:Union[str, Any]		)	->				Optional[Any]:
								pass







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







	def      _lowerCamelCase       (      self	:List[Any]		)	->				Optional[int]:
								__UpperCamelCase     ,		__UpperCamelCase			:     Union[str, Any]         =      self.model_tester.prepare_config_and_inputs_for_common()

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

															__UpperCamelCase			:     Any         =      ["pixel_values"]
															self.assertListEqual(arg_names[:1]  ,     a		)







	def      _lowerCamelCase       (      self	:Optional[Any]		)	->				Tuple:
								__UpperCamelCase			:     Optional[int]         =      self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_model(*a		)







	def      _lowerCamelCase       (      self	:Optional[Any]		)	->				Any:
								def check_hidden_states_output(a	:Union[str, Any]  ,     a	:Optional[Any]  ,     a	:Optional[Any]		):
															__UpperCamelCase			:     Dict         =      model_class(a		)
															__UpperCamelCase			:     Optional[Any]         =      model(**self._prepare_for_class(a  ,     a		)		)

															__UpperCamelCase			:     str         =      outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

															__UpperCamelCase			:     List[Any]         =      self.model_tester.num_stages
															self.assertEqual(len(a		)  ,     expected_num_stages + 1		)

															# ResNet'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 // 4, self.model_tester.image_size // 4]  ,     )

								__UpperCamelCase     ,		__UpperCamelCase			:     Any         =      self.model_tester.prepare_config_and_inputs_for_common()
								__UpperCamelCase			:     Union[str, Any]         =      ["basic", "bottleneck"]
								for model_class in self.all_model_classes:
															for layer_type in layers_type:
																						__UpperCamelCase			:     int         =      layer_type
																						__UpperCamelCase			:     Optional[int]         =      True
																						check_hidden_states_output(a  ,     a  ,     a		)

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

																						check_hidden_states_output(a  ,     a  ,     a		)







	def      _lowerCamelCase       (      self	:Union[str, Any]		)	->				Any:
								__UpperCamelCase			:     List[Any]         =      self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_image_classification(*a		)







	@slow
	def      _lowerCamelCase       (      self	:Union[str, Any]		)	->				Tuple:
								for model_name in TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
															__UpperCamelCase			:     Optional[int]         =      TFResNetModel.from_pretrained(a		)
															self.assertIsNotNone(a		)




def 			_SCREAMING_SNAKE_CASE      (	)      ->					Optional[int]:






							'''simple docstring'''





							__UpperCamelCase			:     Dict         =      Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png")
							return image




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




	'''simple docstring'''




	@cached_property
	def      _lowerCamelCase       (      self	:Any		)	->				str:
								return (
								    AutoImageProcessor.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]		)
								    if is_vision_available()
								    else None
								)







	@slow
	def      _lowerCamelCase       (      self	:Optional[int]		)	->				List[str]:
								__UpperCamelCase			:     Dict         =      TFResNetForImageClassification.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]		)

								__UpperCamelCase			:     Dict         =      self.default_image_processor
								__UpperCamelCase			:     Any         =      prepare_img()
								__UpperCamelCase			:     Optional[Any]         =      image_processor(images=a  ,     return_tensors="tf"		)

								# forward pass
								__UpperCamelCase			:     Union[str, Any]         =      model(**a		)

								# verify the logits
								__UpperCamelCase			:     Optional[Any]         =      tf.TensorShape((1, 1_0_0_0)		)
								self.assertEqual(outputs.logits.shape  ,     a		)

								__UpperCamelCase			:     Dict         =      tf.constant([-11.1069, -9.7877, -8.3777]		)

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

import unittest
from dataclasses import dataclass

import pytest

from accelerate.commands.config.config_args import SageMakerConfig
from accelerate.utils import ComputeEnvironment
from accelerate.utils.launch import _convert_nargs_to_dict




@dataclass
class 				lowerCamelCase__							(       __lowercase):




	'''simple docstring'''




	_A			=  ComputeEnvironment.AMAZON_SAGEMAKER
	_A			=  True
	_A			=  'ml.p3.2xlarge'
	_A			=  'accelerate_sagemaker_execution_role'
	_A			=  'hf-sm'
	_A			=  'us-east-1'
	_A			=  1
	_A			=  'accelerate-sagemaker-1'
	_A			=  '1.6'
	_A			=  '4.4'
	_A			=  'train.py'
	_A			=  [
	    '--model_name_or_path',
	    'bert',
	    '--do_train',
	    'False',
	    '--epochs',
	    '3',
	    '--learning_rate',
	    '5e-5',
	    '--max_steps',
	    '50.5',
	]
	_A			=  [
	    '--model_name_or_path',
	    'bert',
	    '--do_train',
	    '--do_test',
	    'False',
	    '--do_predict',
	    '--epochs',
	    '3',
	    '--learning_rate',
	    '5e-5',
	    '--max_steps',
	    '50.5',
	]




class 				lowerCamelCase__							(       unittest.TestCase):




	'''simple docstring'''




	def      _lowerCamelCase       (      self	:Tuple		)	->				str:
								# If no defaults are changed, `to_kwargs` returns an empty dict.
								__UpperCamelCase			:     str         =      _convert_nargs_to_dict(MockLaunchConfig.success_training_script_args		)
								assert isinstance(converted_args["model_name_or_path"]  ,     a		)
								assert isinstance(converted_args["do_train"]  ,     a		)
								assert isinstance(converted_args["epochs"]  ,     a		)
								assert isinstance(converted_args["learning_rate"]  ,     a		)
								assert isinstance(converted_args["max_steps"]  ,     a		)

								with pytest.raises(a		):
															_convert_nargs_to_dict(MockLaunchConfig.fail_training_script_args		)