

"""simple docstring"""





from __future__ import annotations

import inspect
import unittest
from typing import List, Tuple

from transformers import ConvNextConfig
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 TFConvNextForImageClassification, TFConvNextModel


if is_vision_available():
				from PIL import Image

				from transformers import ConvNextImageProcessor

class     __a   :

			"""simple docstring"""

			def __init__(							self     :					str						,  lowercase_     :					Dict						,  lowercase_     :					Optional[Any]=13						,  lowercase_     :					str=32						,  lowercase_     :					str=3						,  lowercase_     :					Tuple=4						,  lowercase_     :					str=[10, 20, 30, 40]						,  lowercase_     :					int=[2, 2, 3, 2]						,  lowercase_     :					List[Any]=True						,  lowercase_     :					str=True						,  lowercase_     :					int=37						,  lowercase_     :					str="gelu"						,  lowercase_     :					List[Any]=10						,  lowercase_     :					Union[str, Any]=0.0_2						,  lowercase_     :					Any=3						,  lowercase_     :					Any=None						,  ):
								UpperCamelCase__		:    List[str]         =parent
								UpperCamelCase__		:    Tuple         =batch_size
								UpperCamelCase__		:    Union[str, Any]         =image_size
								UpperCamelCase__		:    Union[str, Any]         =num_channels
								UpperCamelCase__		:    int         =num_stages
								UpperCamelCase__		:    str         =hidden_sizes
								UpperCamelCase__		:    Dict         =depths
								UpperCamelCase__		:    Tuple         =is_training
								UpperCamelCase__		:    Optional[int]         =use_labels
								UpperCamelCase__		:    str         =intermediate_size
								UpperCamelCase__		:    Dict         =hidden_act
								UpperCamelCase__		:    List[str]         =type_sequence_label_size
								UpperCamelCase__		:    Any         =initializer_range
								UpperCamelCase__		:    Optional[int]         =scope






			def    _lowerCAmelCase			(							self     :					Optional[int]						):
								UpperCamelCase__		:    Tuple         =floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]						)

								UpperCamelCase__		:    Union[str, Any]         =None
								if self.use_labels:
													UpperCamelCase__		:    Any         =ids_tensor([self.batch_size]						,  self.type_sequence_label_size						)

								UpperCamelCase__		:    Optional[int]         =self.get_config()

								return config, pixel_values, labels






			def    _lowerCAmelCase			(							self     :					str						):
								return ConvNextConfig(
								    num_channels=self.num_channels						,  hidden_sizes=self.hidden_sizes						,  depths=self.depths						,  num_stages=self.num_stages						,  hidden_act=self.hidden_act						,  is_decoder=lowercase_						,  initializer_range=self.initializer_range						,  )






			def    _lowerCAmelCase			(							self     :					Dict						,  lowercase_     :					Optional[Any]						,  lowercase_     :					Optional[int]						,  lowercase_     :					Dict						):
								UpperCamelCase__		:    Dict         =TFConvNextModel(config=lowercase_						)
								UpperCamelCase__		:    Optional[Any]         =model(lowercase_						,  training=lowercase_						)
								# 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    _lowerCAmelCase			(							self     :					List[str]						,  lowercase_     :					Any						,  lowercase_     :					Dict						,  lowercase_     :					Optional[Any]						):
								UpperCamelCase__		:    int         =self.type_sequence_label_size
								UpperCamelCase__		:    int         =TFConvNextForImageClassification(lowercase_						)
								UpperCamelCase__		:    Dict         =model(lowercase_						,  labels=lowercase_						,  training=lowercase_						)
								self.parent.assertEqual(result.logits.shape						,  (self.batch_size, self.type_sequence_label_size)						)






			def    _lowerCAmelCase			(							self     :					Union[str, Any]						):
								UpperCamelCase__		:    Dict         =self.prepare_config_and_inputs()
								UpperCamelCase__  ,			UpperCamelCase__  ,			UpperCamelCase__		:    Any         =config_and_inputs
								UpperCamelCase__		:    List[Any]         ={'''pixel_values''': pixel_values}
								return config, inputs_dict



@require_tf
class     __a   (      snake_case__,    snake_case__,    unittest.TestCase    ):

			"""simple docstring"""

			SCREAMING_SNAKE_CASE_						     =						(TFConvNextModel, TFConvNextForImageClassification) if is_tf_available() else ()
			SCREAMING_SNAKE_CASE_						     =						(
			    {'feature-extraction': TFConvNextModel, 'image-classification': TFConvNextForImageClassification}
			    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    _lowerCAmelCase			(							self     :					Tuple						):
								UpperCamelCase__		:    Any         =TFConvNextModelTester(self						)
								UpperCamelCase__		:    Optional[int]         =ConfigTester(
								    self						,  config_class=lowercase_						,  has_text_modality=lowercase_						,  hidden_size=37						,  )






			@unittest.skip(reason='''ConvNext does not use inputs_embeds'''						)
			def    _lowerCAmelCase			(							self     :					List[str]						):
								pass






			@unittest.skipIf(
			    not is_tf_available() or len(tf.config.list_physical_devices('''GPU'''						)						) == 0						,  reason='''TF does not support backprop for grouped convolutions on CPU.'''						,  )
			@slow
			def    _lowerCAmelCase			(							self     :					int						):
								super().test_keras_fit()






			@unittest.skip(reason='''ConvNext does not support input and output embeddings'''						)
			def    _lowerCAmelCase			(							self     :					Union[str, Any]						):
								pass






			def    _lowerCAmelCase			(							self     :					Optional[Any]						):
								UpperCamelCase__  ,			UpperCamelCase__		:    Dict         =self.model_tester.prepare_config_and_inputs_for_common()

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

													UpperCamelCase__		:    int         =['''pixel_values''']
													self.assertListEqual(arg_names[:1]						,  lowercase_						)






			def    _lowerCAmelCase			(							self     :					Any						):
								UpperCamelCase__		:    Tuple         =self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_model(*lowercase_						)






			@unittest.skipIf(
			    not is_tf_available() or len(tf.config.list_physical_devices('''GPU'''						)						) == 0						,  reason='''TF does not support backprop for grouped convolutions on CPU.'''						,  )
			def    _lowerCAmelCase			(							self     :					int						):
								super().test_dataset_conversion()






			def    _lowerCAmelCase			(							self     :					Union[str, Any]						):
								def check_hidden_states_output(lowercase_     :					Tuple						,  lowercase_     :					List[Any]						,  lowercase_     :					Optional[Any]						):
													UpperCamelCase__		:    str         =model_class(lowercase_						)

													UpperCamelCase__		:    Any         =model(**self._prepare_for_class(lowercase_						,  lowercase_						)						)
													UpperCamelCase__		:    int         =outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

													UpperCamelCase__		:    Union[str, Any]         =self.model_tester.num_stages
													self.assertEqual(len(lowercase_						)						,  expected_num_stages + 1						)

													# ConvNext'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__		:    Optional[int]         =self.model_tester.prepare_config_and_inputs_for_common()

								for model_class in self.all_model_classes:
													UpperCamelCase__		:    Dict         =True
													check_hidden_states_output(lowercase_						,  lowercase_						,  lowercase_						)

													# check that output_hidden_states also work using config
													del inputs_dict["output_hidden_states"]
													UpperCamelCase__		:    Optional[Any]         =True

													check_hidden_states_output(lowercase_						,  lowercase_						,  lowercase_						)






			def    _lowerCAmelCase			(							self     :					Optional[int]						):
								UpperCamelCase__  ,			UpperCamelCase__		:    Dict         =self.model_tester.prepare_config_and_inputs_for_common()

								def check_equivalence(lowercase_     :					Optional[Any]						,  lowercase_     :					List[str]						,  lowercase_     :					Tuple						,  lowercase_     :					int={}						):
													UpperCamelCase__		:    Optional[int]         =model(lowercase_						,  return_dict=lowercase_						,  **lowercase_						)
													UpperCamelCase__		:    int         =model(lowercase_						,  return_dict=lowercase_						,  **lowercase_						).to_tuple()

													def recursive_check(lowercase_     :					int						,  lowercase_     :					Any						):
																		if isinstance(lowercase_						,  (List, Tuple)						):
																							for tuple_iterable_value, dict_iterable_value in zip(lowercase_						,  lowercase_						):
																												recursive_check(lowercase_						,  lowercase_						)
																		elif tuple_object is None:
																							return
																		else:
																							self.assertTrue(
																							    all(tf.equal(lowercase_						,  lowercase_						)						)						,  msg=(
																							        '''Tuple and dict output are not equal. Difference:'''
																							        f''' {tf.math.reduce_max(tf.abs(tuple_object - dict_object						)						)}'''
																							    )						,  )

																		recursive_check(lowercase_						,  lowercase_						)

								for model_class in self.all_model_classes:
													UpperCamelCase__		:    str         =model_class(lowercase_						)

													UpperCamelCase__		:    List[str]         =self._prepare_for_class(lowercase_						,  lowercase_						)
													UpperCamelCase__		:    Union[str, Any]         =self._prepare_for_class(lowercase_						,  lowercase_						)
													check_equivalence(lowercase_						,  lowercase_						,  lowercase_						)

													UpperCamelCase__		:    int         =self._prepare_for_class(lowercase_						,  lowercase_						,  return_labels=lowercase_						)
													UpperCamelCase__		:    Optional[int]         =self._prepare_for_class(lowercase_						,  lowercase_						,  return_labels=lowercase_						)
													check_equivalence(lowercase_						,  lowercase_						,  lowercase_						)

													UpperCamelCase__		:    List[str]         =self._prepare_for_class(lowercase_						,  lowercase_						)
													UpperCamelCase__		:    Any         =self._prepare_for_class(lowercase_						,  lowercase_						)
													check_equivalence(lowercase_						,  lowercase_						,  lowercase_						,  {'''output_hidden_states''': True}						)

													UpperCamelCase__		:    Optional[Any]         =self._prepare_for_class(lowercase_						,  lowercase_						,  return_labels=lowercase_						)
													UpperCamelCase__		:    Tuple         =self._prepare_for_class(lowercase_						,  lowercase_						,  return_labels=lowercase_						)
													check_equivalence(lowercase_						,  lowercase_						,  lowercase_						,  {'''output_hidden_states''': True}						)






			def    _lowerCAmelCase			(							self     :					Optional[int]						):
								UpperCamelCase__		:    Any         =self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_image_classification(*lowercase_						)






			@slow
			def    _lowerCAmelCase			(							self     :					List[Any]						):
								UpperCamelCase__		:    List[Any]         =TFConvNextModel.from_pretrained('''facebook/convnext-tiny-224'''						)
								self.assertIsNotNone(lowercase_						)



def        _lowerCAmelCase      (						):


					'''simple docstring'''






					UpperCamelCase__		:    Any         =Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''				)
					return image







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

			"""simple docstring"""

			@cached_property
			def    _lowerCAmelCase			(							self     :					Optional[Any]						):
								return ConvNextImageProcessor.from_pretrained('''facebook/convnext-tiny-224'''						) if is_vision_available() else None






			@slow
			def    _lowerCAmelCase			(							self     :					Optional[Any]						):
								UpperCamelCase__		:    List[Any]         =TFConvNextForImageClassification.from_pretrained('''facebook/convnext-tiny-224'''						)

								UpperCamelCase__		:    Optional[Any]         =self.default_image_processor
								UpperCamelCase__		:    int         =prepare_img()
								UpperCamelCase__		:    Optional[Any]         =image_processor(images=lowercase_						,  return_tensors='''tf'''						)

								# forward pass
								UpperCamelCase__		:    Tuple         =model(**lowercase_						)

								# verify the logits
								UpperCamelCase__		:    Union[str, Any]         =tf.TensorShape((1, 1000)						)
								self.assertEqual(outputs.logits.shape						,  lowercase_						)

								UpperCamelCase__		:    Union[str, Any]         =tf.constant([-0.0_2_6_0, -0.4_7_3_9, 0.1_9_1_1]						)

								tf.debugging.assert_near(outputs.logits[0, :3]						,  lowercase_						,  atol=1e-4						)





"""simple docstring"""





from typing import TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_flax_available,
    is_sentencepiece_available,
    is_tf_available,
    is_tokenizers_available,
    is_torch_available,
)


_SCREAMING_SNAKE_CASE       :  List[Any]        = {"""configuration_t5""": ["""T5_PRETRAINED_CONFIG_ARCHIVE_MAP""", """T5Config""", """T5OnnxConfig"""]}

try:
				if not is_sentencepiece_available():
								raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
				pass
else:
				_SCREAMING_SNAKE_CASE       :  Optional[Any]        = ["""T5Tokenizer"""]

try:
				if not is_tokenizers_available():
								raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
				pass
else:
				_SCREAMING_SNAKE_CASE       :  str        = ["""T5TokenizerFast"""]

try:
				if not is_torch_available():
								raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
				pass
else:
				_SCREAMING_SNAKE_CASE       :  Dict        = [
				    """T5_PRETRAINED_MODEL_ARCHIVE_LIST""",
				    """T5EncoderModel""",
				    """T5ForConditionalGeneration""",
				    """T5Model""",
				    """T5PreTrainedModel""",
				    """load_tf_weights_in_t5""",
				    """T5ForQuestionAnswering""",
				]

try:
				if not is_tf_available():
								raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
				pass
else:
				_SCREAMING_SNAKE_CASE       :  Dict        = [
				    """TF_T5_PRETRAINED_MODEL_ARCHIVE_LIST""",
				    """TFT5EncoderModel""",
				    """TFT5ForConditionalGeneration""",
				    """TFT5Model""",
				    """TFT5PreTrainedModel""",
				]

try:
				if not is_flax_available():
								raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
				pass
else:
				_SCREAMING_SNAKE_CASE       :  Any        = [
				    """FlaxT5EncoderModel""",
				    """FlaxT5ForConditionalGeneration""",
				    """FlaxT5Model""",
				    """FlaxT5PreTrainedModel""",
				]


if TYPE_CHECKING:
				from .configuration_ta import T5_PRETRAINED_CONFIG_ARCHIVE_MAP, TaConfig, TaOnnxConfig

				try:
								if not is_sentencepiece_available():
												raise OptionalDependencyNotAvailable()
				except OptionalDependencyNotAvailable:
								pass
				else:
								from .tokenization_ta import TaTokenizer

				try:
								if not is_tokenizers_available():
												raise OptionalDependencyNotAvailable()
				except OptionalDependencyNotAvailable:
								pass
				else:
								from .tokenization_ta_fast import TaTokenizerFast

				try:
								if not is_torch_available():
												raise OptionalDependencyNotAvailable()
				except OptionalDependencyNotAvailable:
								pass
				else:
								from .modeling_ta import (
								    T5_PRETRAINED_MODEL_ARCHIVE_LIST,
								    TaEncoderModel,
								    TaForConditionalGeneration,
								    TaForQuestionAnswering,
								    TaModel,
								    TaPreTrainedModel,
								    load_tf_weights_in_ta,
								)

				try:
								if not is_tf_available():
												raise OptionalDependencyNotAvailable()
				except OptionalDependencyNotAvailable:
								pass
				else:
								from .modeling_tf_ta import (
								    TF_T5_PRETRAINED_MODEL_ARCHIVE_LIST,
								    TFTaEncoderModel,
								    TFTaForConditionalGeneration,
								    TFTaModel,
								    TFTaPreTrainedModel,
								)

				try:
								if not is_flax_available():
												raise OptionalDependencyNotAvailable()
				except OptionalDependencyNotAvailable:
								pass
				else:
								from .modeling_flax_ta import (
								    FlaxTaEncoderModel,
								    FlaxTaForConditionalGeneration,
								    FlaxTaModel,
								    FlaxTaPreTrainedModel,
								)


else:
				import sys

				_SCREAMING_SNAKE_CASE       :  str        = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)


