



"""simple docstring"""







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        _SCREAMING_SNAKE_CASE						:





							"""simple docstring"""





							def __init__(   self:     Optional[Any]				,		__A:     Optional[int]				,		__A:     str=3				,		__A:     str=32				,		__A:     Tuple=3				,		__A:     Union[str, Any]=10				,		__A:     Tuple=[10, 20, 30, 40]				,		__A:     Optional[Any]=[1, 1, 2, 1]				,		__A:     Dict=True				,		__A:     Optional[int]=True				,		__A:     str="relu"				,		__A:     int=3				,		__A:     Any=None				,		):

												'''simple docstring'''

												a__          =  parent
												a__          =  batch_size
												a__          =  image_size
												a__          =  num_channels
												a__          =  embeddings_size
												a__          =  hidden_sizes
												a__          =  depths
												a__          =  is_training
												a__          =  use_labels
												a__          =  hidden_act
												a__          =  num_labels
												a__          =  scope
												a__          =  len(__A    )




							def  lowercase		(   self:     str    ):

												'''simple docstring'''

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

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

												a__          =  self.get_config()

												return config, pixel_values, labels




							def  lowercase		(   self:     Optional[Any]    ):

												'''simple docstring'''

												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  lowercase		(   self:     List[str]				,		__A:     List[Any]				,		__A:     List[Any]				,		__A:     Dict    ):

												'''simple docstring'''

												a__          =  TFResNetModel(config=__A    )
												a__          =  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 // 32, self.image_size // 32)				,		)




							def  lowercase		(   self:     List[Any]				,		__A:     Dict				,		__A:     Dict				,		__A:     Union[str, Any]    ):

												'''simple docstring'''

												a__          =  self.num_labels
												a__          =  TFResNetForImageClassification(__A    )
												a__          =  model(__A				,		labels=__A    )
												self.parent.assertEqual(result.logits.shape				,		(self.batch_size, self.num_labels)    )





							def  lowercase		(   self:     Any    ):

												'''simple docstring'''

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







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





							"""simple docstring"""





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

							_SCREAMING_SNAKE_CASE    =False
							_SCREAMING_SNAKE_CASE    =False
							_SCREAMING_SNAKE_CASE    =False
							_SCREAMING_SNAKE_CASE    =False
							_SCREAMING_SNAKE_CASE    =False




							def  lowercase		(   self:     List[str]    ):

												'''simple docstring'''

												a__          =  TFResNetModelTester(self    )
												a__          =  ConfigTester(self				,		config_class=__A				,		has_text_modality=__A    )




							def  lowercase		(   self:     List[Any]    ):

												'''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  lowercase		(   self:     Optional[int]    ):

												'''simple docstring'''

												return




							@unittest.skip(reason='''ResNet does not use inputs_embeds'''    )
							def  lowercase		(   self:     Union[str, Any]    ):

												'''simple docstring'''

												pass




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

												'''simple docstring'''

												pass




							def  lowercase		(   self:     List[Any]    ):

												'''simple docstring'''

												a__          =  self.model_tester.prepare_config_and_inputs_for_common()

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

																	a__          =  ["pixel_values"]
																	self.assertListEqual(arg_names[:1]				,		__A    )




							def  lowercase		(   self:     Any    ):

												'''simple docstring'''

												a__          =  self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_model(*__A    )




							def  lowercase		(   self:     int    ):

												'''simple docstring'''

												def check_hidden_states_output(__A:     List[Any]				,		__A:     List[Any]				,		__A:     int    ):
																	a__          =  model_class(__A    )
																	a__          =  model(**self._prepare_for_class(__A				,		__A    )    )

																	a__          =  outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

																	a__          =  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]				,		)

												a__          =  self.model_tester.prepare_config_and_inputs_for_common()
												a__          =  ["basic", "bottleneck"]
												for model_class in self.all_model_classes:
																	for layer_type in layers_type:
																						a__          =  layer_type
																						a__          =  True
																						check_hidden_states_output(__A				,		__A				,		__A    )

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

																						check_hidden_states_output(__A				,		__A				,		__A    )




							def  lowercase		(   self:     List[str]    ):

												'''simple docstring'''

												a__          =  self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_for_image_classification(*__A    )





							@slow
							def  lowercase		(   self:     List[Any]    ):

												'''simple docstring'''

												for model_name in TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																	a__          =  TFResNetModel.from_pretrained(__A    )
																	self.assertIsNotNone(__A    )





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







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





							"""simple docstring"""





							@cached_property
							def  lowercase		(   self:     Tuple    ):

												'''simple docstring'''

												return (
												    AutoImageProcessor.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]    )
												    if is_vision_available()
												    else None
												)





							@slow
							def  lowercase		(   self:     List[str]    ):

												'''simple docstring'''

												a__          =  TFResNetForImageClassification.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]    )

												a__          =  self.default_image_processor
												a__          =  prepare_img()
												a__          =  image_processor(images=__A				,		return_tensors='''tf'''    )

												# forward pass
												a__          =  model(**__A    )

												# verify the logits
												a__          =  tf.TensorShape((1, 1000)    )
												self.assertEqual(outputs.logits.shape				,		__A    )

												a__          =  tf.constant([-1_1.1_0_6_9, -9.7_8_7_7, -8.3_7_7_7]    )

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










"""simple docstring"""







import copy
import os
from typing import TYPE_CHECKING, List, Union


if TYPE_CHECKING:
	pass

from ...configuration_utils import PretrainedConfig
from ...utils import logging


__a       :	List[Any]             = logging.get_logger(__name__)

__a       :	Tuple             = {
    'kakaobrain/align-base': 'https://huggingface.co/kakaobrain/align-base/resolve/main/config.json',
}







class        _SCREAMING_SNAKE_CASE						(  __snake_case							):





							"""simple docstring"""





							_SCREAMING_SNAKE_CASE    ='align_text_model'




							def __init__(   self:     Tuple				,		__A:     Optional[int]=30522				,		__A:     Tuple=768				,		__A:     Any=12				,		__A:     Any=12				,		__A:     Dict=3072				,		__A:     Tuple="gelu"				,		__A:     Union[str, Any]=0.1				,		__A:     List[str]=0.1				,		__A:     Optional[int]=512				,		__A:     Tuple=2				,		__A:     str=0.0_2				,		__A:     int=1e-12				,		__A:     Optional[int]=0				,		__A:     Optional[int]="absolute"				,		__A:     List[Any]=True				,		**__A:     Tuple				,		):

												'''simple docstring'''

												super().__init__(**__A    )

												a__          =  vocab_size
												a__          =  hidden_size
												a__          =  num_hidden_layers
												a__          =  num_attention_heads
												a__          =  hidden_act
												a__          =  intermediate_size
												a__          =  hidden_dropout_prob
												a__          =  attention_probs_dropout_prob
												a__          =  max_position_embeddings
												a__          =  type_vocab_size
												a__          =  initializer_range
												a__          =  layer_norm_eps
												a__          =  position_embedding_type
												a__          =  use_cache
												a__          =  pad_token_id





							@classmethod
							def  lowercase		(   cls:     Any				,		__A:     Union[str, os.PathLike]				,		**__A:     Tuple    ):

												'''simple docstring'''

												cls._set_token_in_kwargs(__A    )

												a__       ,a__          =  cls.get_config_dict(__A				,		**__A    )

												# get the text config dict if we are loading from AlignConfig
												if config_dict.get('''model_type'''    ) == "align":
																	a__          =  config_dict['''text_config''']

												if "model_type" in config_dict and hasattr(cls				,		'''model_type'''    ) and config_dict["model_type"] != cls.model_type:
																	logger.warning(
																	    F'You are using a model of type {config_dict["model_type"]} to instantiate a model of type '
																	    F'{cls.model_type}. This is not supported for all configurations of models and can yield errors.'    )

												return cls.from_dict(__A				,		**__A    )







class        _SCREAMING_SNAKE_CASE						(  __snake_case							):





							"""simple docstring"""





							_SCREAMING_SNAKE_CASE    ='align_vision_model'




							def __init__(   self:     Dict				,		__A:     int = 3				,		__A:     int = 600				,		__A:     float = 2.0				,		__A:     float = 3.1				,		__A:     int = 8				,		__A:     List[int] = [3, 3, 5, 3, 5, 5, 3]				,		__A:     List[int] = [32, 16, 24, 40, 80, 112, 192]				,		__A:     List[int] = [16, 24, 40, 80, 112, 192, 320]				,		__A:     List[int] = []				,		__A:     List[int] = [1, 2, 2, 2, 1, 2, 1]				,		__A:     List[int] = [1, 2, 2, 3, 3, 4, 1]				,		__A:     List[int] = [1, 6, 6, 6, 6, 6, 6]				,		__A:     float = 0.2_5				,		__A:     str = "swish"				,		__A:     int = 2560				,		__A:     str = "mean"				,		__A:     float = 0.0_2				,		__A:     float = 0.0_0_1				,		__A:     float = 0.9_9				,		__A:     float = 0.2				,		**__A:     List[Any]				,		):

												'''simple docstring'''

												super().__init__(**__A    )

												a__          =  num_channels
												a__          =  image_size
												a__          =  width_coefficient
												a__          =  depth_coefficient
												a__          =  depth_divisor
												a__          =  kernel_sizes
												a__          =  in_channels
												a__          =  out_channels
												a__          =  depthwise_padding
												a__          =  strides
												a__          =  num_block_repeats
												a__          =  expand_ratios
												a__          =  squeeze_expansion_ratio
												a__          =  hidden_act
												a__          =  hidden_dim
												a__          =  pooling_type
												a__          =  initializer_range
												a__          =  batch_norm_eps
												a__          =  batch_norm_momentum
												a__          =  drop_connect_rate
												a__          =  sum(__A    ) * 4





							@classmethod
							def  lowercase		(   cls:     Dict				,		__A:     Union[str, os.PathLike]				,		**__A:     List[Any]    ):

												'''simple docstring'''

												cls._set_token_in_kwargs(__A    )

												a__       ,a__          =  cls.get_config_dict(__A				,		**__A    )

												# get the vision config dict if we are loading from AlignConfig
												if config_dict.get('''model_type'''    ) == "align":
																	a__          =  config_dict['''vision_config''']

												if "model_type" in config_dict and hasattr(cls				,		'''model_type'''    ) and config_dict["model_type"] != cls.model_type:
																	logger.warning(
																	    F'You are using a model of type {config_dict["model_type"]} to instantiate a model of type '
																	    F'{cls.model_type}. This is not supported for all configurations of models and can yield errors.'    )

												return cls.from_dict(__A				,		**__A    )







class        _SCREAMING_SNAKE_CASE						(  __snake_case							):





							"""simple docstring"""





							_SCREAMING_SNAKE_CASE    ='align'
							_SCREAMING_SNAKE_CASE    =True




							def __init__(   self:     Optional[int]				,		__A:     Optional[int]=None				,		__A:     Dict=None				,		__A:     List[str]=640				,		__A:     Optional[int]=1.0				,		__A:     str=0.0_2				,		**__A:     List[str]				,		):

												'''simple docstring'''

												super().__init__(**__A    )

												if text_config is None:
																	a__          =  {}
																	logger.info('''text_config is None. Initializing the AlignTextConfig with default values.'''    )

												if vision_config is None:
																	a__          =  {}
																	logger.info('''vision_config is None. Initializing the AlignVisionConfig with default values.'''    )

												a__          =  AlignTextConfig(**__A    )
												a__          =  AlignVisionConfig(**__A    )

												a__          =  projection_dim
												a__          =  temperature_init_value
												a__          =  initializer_range




							@classmethod
							def  lowercase		(   cls:     Dict				,		__A:     AlignTextConfig				,		__A:     AlignVisionConfig				,		**__A:     str    ):

												'''simple docstring'''

												return cls(text_config=text_config.to_dict()				,		vision_config=vision_config.to_dict()				,		**__A    )





							def  lowercase		(   self:     Any    ):

												'''simple docstring'''

												a__          =  copy.deepcopy(self.__dict__    )
												a__          =  self.text_config.to_dict()
												a__          =  self.vision_config.to_dict()
												a__          =  self.__class__.model_type
												return output


