

"""simple docstring"""


from __future__ import annotations

import inspect
import unittest
from typing import List, Tuple

from transformers import RegNetConfig
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 TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST, TFRegNetForImageClassification, TFRegNetModel


if is_vision_available():
			from PIL import Image

			from transformers import AutoImageProcessor





class        snake_case      :

				def __init__(      self				:							Tuple	,    UpperCamelCase__				:							List[Any]	,    UpperCamelCase__				:							Optional[Any]=3	,    UpperCamelCase__				:							Optional[Any]=3_2	,    UpperCamelCase__				:							Union[str, Any]=3	,    UpperCamelCase__				:							List[Any]=1_0	,    UpperCamelCase__				:							int=[1_0, 2_0, 3_0, 4_0]	,    UpperCamelCase__				:							str=[1, 1, 2, 1]	,    UpperCamelCase__				:							Optional[int]=True	,    UpperCamelCase__				:							Any=True	,    UpperCamelCase__				:							List[str]="relu"	,    UpperCamelCase__				:							Optional[int]=3	,    UpperCamelCase__				:							Tuple=None	,    )->  List[Any]:



						'''simple docstring'''


						__lowerCAmelCase:			Optional[Any]        =     parent
						__lowerCAmelCase:			List[Any]        =     batch_size
						__lowerCAmelCase:			int        =     image_size
						__lowerCAmelCase:			Union[str, Any]        =     num_channels
						__lowerCAmelCase:			Any        =     embeddings_size
						__lowerCAmelCase:			List[Any]        =     hidden_sizes
						__lowerCAmelCase:			int        =     depths
						__lowerCAmelCase:			Tuple        =     is_training
						__lowerCAmelCase:			str        =     use_labels
						__lowerCAmelCase:			int        =     hidden_act
						__lowerCAmelCase:			str        =     num_labels
						__lowerCAmelCase:			Optional[int]        =     scope
						__lowerCAmelCase:			Union[str, Any]        =     len(UpperCAmelCase__)

				def 				lowercase_	(      self				:							Union[str, Any])->  Tuple:



						'''simple docstring'''


						__lowerCAmelCase:			Optional[int]        =     floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])

						__lowerCAmelCase:			Optional[int]        =     None
						if self.use_labels:
								__lowerCAmelCase:			Tuple        =     ids_tensor([self.batch_size]	,    self.num_labels)

						__lowerCAmelCase:			Any        =     self.get_config()
						return config, pixel_values, labels

				def 				lowercase_	(      self				:							str)->  Any:



						'''simple docstring'''


						return RegNetConfig(
						    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	,    )

				def 				lowercase_	(      self				:							Optional[Any]	,    UpperCamelCase__				:							Optional[Any]	,    UpperCamelCase__				:							Any	,    UpperCamelCase__				:							Union[str, Any])->  Tuple:



						'''simple docstring'''


						__lowerCAmelCase:			str        =     TFRegNetModel(config=UpperCAmelCase__)
						__lowerCAmelCase:			int        =     model(UpperCAmelCase__	,    training=UpperCAmelCase__)
						# 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 				lowercase_	(      self				:							Dict	,    UpperCamelCase__				:							List[str]	,    UpperCamelCase__				:							Optional[int]	,    UpperCamelCase__				:							Dict)->  Any:



						'''simple docstring'''


						__lowerCAmelCase:			str        =     self.num_labels
						__lowerCAmelCase:			Any        =     TFRegNetForImageClassification(UpperCAmelCase__)
						__lowerCAmelCase:			List[Any]        =     model(UpperCAmelCase__	,    labels=UpperCAmelCase__	,    training=UpperCAmelCase__)
						self.parent.assertEqual(result.logits.shape	,    (self.batch_size, self.num_labels))




				def 				lowercase_	(      self				:							Dict)->  Optional[int]:



						'''simple docstring'''


						__lowerCAmelCase:			Dict        =     self.prepare_config_and_inputs()
						__lowerCAmelCase ,					__lowerCAmelCase ,					__lowerCAmelCase:			Optional[int]        =     config_and_inputs
						__lowerCAmelCase:			int        =     {"pixel_values": pixel_values}
						return config, inputs_dict





@require_tf
class        snake_case      (							UpperCAmelCase__,				UpperCAmelCase__,				unittest.TestCase    ):
				SCREAMING_SNAKE_CASE_  : str   =    (TFRegNetModel, TFRegNetForImageClassification) if is_tf_available() else ()
				SCREAMING_SNAKE_CASE_  : Optional[Any]   =    (
				    {"""feature-extraction""": TFRegNetModel, """image-classification""": TFRegNetForImageClassification}
				    if is_tf_available()
				    else {}
				)

				SCREAMING_SNAKE_CASE_  : List[str]   =    False
				SCREAMING_SNAKE_CASE_  : Dict   =    False
				SCREAMING_SNAKE_CASE_  : Union[str, Any]   =    False
				SCREAMING_SNAKE_CASE_  : Tuple   =    False
				SCREAMING_SNAKE_CASE_  : int   =    False

				def 				lowercase_	(      self				:							List[str])->  Tuple:



						'''simple docstring'''


						__lowerCAmelCase:			int        =     TFRegNetModelTester(self)
						__lowerCAmelCase:			Dict        =     ConfigTester(self	,    config_class=UpperCAmelCase__	,    has_text_modality=UpperCAmelCase__)

				def 				lowercase_	(      self				:							List[str])->  Tuple:



						'''simple docstring'''


						return

				@unittest.skip(reason="RegNet does not use inputs_embeds")
				def 				lowercase_	(      self				:							Tuple)->  int:



						'''simple docstring'''


						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 				lowercase_	(      self				:							str)->  str:



						'''simple docstring'''


						super().test_keras_fit()

				@unittest.skip(reason="RegNet does not support input and output embeddings")
				def 				lowercase_	(      self				:							Dict)->  int:



						'''simple docstring'''


						pass

				def 				lowercase_	(      self				:							str)->  List[str]:



						'''simple docstring'''


						__lowerCAmelCase ,					__lowerCAmelCase:			Optional[Any]        =     self.model_tester.prepare_config_and_inputs_for_common()

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

								__lowerCAmelCase:			Optional[Any]        =     ["pixel_values"]
								self.assertListEqual(arg_names[:1]	,    UpperCAmelCase__)

				def 				lowercase_	(      self				:							int)->  Tuple:



						'''simple docstring'''


						__lowerCAmelCase:			Union[str, Any]        =     self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_model(*UpperCAmelCase__)

				def 				lowercase_	(      self				:							Optional[Any])->  Dict:



						'''simple docstring'''


						def check_hidden_states_output(UpperCamelCase__				:							Dict	,    UpperCamelCase__				:							Optional[int]	,    UpperCamelCase__				:							Optional[Any]):
								__lowerCAmelCase:			str        =     model_class(UpperCAmelCase__)
								__lowerCAmelCase:			Tuple        =     model(**self._prepare_for_class(UpperCAmelCase__	,    UpperCAmelCase__)	,    training=UpperCAmelCase__)

								__lowerCAmelCase:			int        =     outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

								__lowerCAmelCase:			Any        =     self.model_tester.num_stages
								self.assertEqual(len(UpperCAmelCase__)	,    expected_num_stages + 1)

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

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

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

										check_hidden_states_output(UpperCAmelCase__	,    UpperCAmelCase__	,    UpperCAmelCase__)

				def 				lowercase_	(      self				:							Dict)->  int:



						'''simple docstring'''


						__lowerCAmelCase ,					__lowerCAmelCase:			Union[str, Any]        =     self.model_tester.prepare_config_and_inputs_for_common()

						def check_equivalence(UpperCamelCase__				:							Union[str, Any]	,    UpperCamelCase__				:							str	,    UpperCamelCase__				:							Any	,    UpperCamelCase__				:							Dict={}):
								__lowerCAmelCase:			Union[str, Any]        =     model(UpperCAmelCase__	,    return_dict=UpperCAmelCase__	,    **UpperCAmelCase__)
								__lowerCAmelCase:			int        =     model(UpperCAmelCase__	,    return_dict=UpperCAmelCase__	,    **UpperCAmelCase__).to_tuple()

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

										recursive_check(UpperCAmelCase__	,    UpperCAmelCase__)

						for model_class in self.all_model_classes:
								__lowerCAmelCase:			Optional[int]        =     model_class(UpperCAmelCase__)

								__lowerCAmelCase:			str        =     self._prepare_for_class(UpperCAmelCase__	,    UpperCAmelCase__)
								__lowerCAmelCase:			Optional[Any]        =     self._prepare_for_class(UpperCAmelCase__	,    UpperCAmelCase__)
								check_equivalence(UpperCAmelCase__	,    UpperCAmelCase__	,    UpperCAmelCase__)

								__lowerCAmelCase:			Optional[int]        =     self._prepare_for_class(UpperCAmelCase__	,    UpperCAmelCase__	,    return_labels=UpperCAmelCase__)
								__lowerCAmelCase:			int        =     self._prepare_for_class(UpperCAmelCase__	,    UpperCAmelCase__	,    return_labels=UpperCAmelCase__)
								check_equivalence(UpperCAmelCase__	,    UpperCAmelCase__	,    UpperCAmelCase__)

								__lowerCAmelCase:			Dict        =     self._prepare_for_class(UpperCAmelCase__	,    UpperCAmelCase__)
								__lowerCAmelCase:			Optional[int]        =     self._prepare_for_class(UpperCAmelCase__	,    UpperCAmelCase__)
								check_equivalence(UpperCAmelCase__	,    UpperCAmelCase__	,    UpperCAmelCase__	,    {"output_hidden_states": True})

								__lowerCAmelCase:			str        =     self._prepare_for_class(UpperCAmelCase__	,    UpperCAmelCase__	,    return_labels=UpperCAmelCase__)
								__lowerCAmelCase:			Optional[Any]        =     self._prepare_for_class(UpperCAmelCase__	,    UpperCAmelCase__	,    return_labels=UpperCAmelCase__)
								check_equivalence(UpperCAmelCase__	,    UpperCAmelCase__	,    UpperCAmelCase__	,    {"output_hidden_states": True})

				def 				lowercase_	(      self				:							Optional[int])->  int:



						'''simple docstring'''


						__lowerCAmelCase:			List[str]        =     self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_for_image_classification(*UpperCAmelCase__)




				@slow
				def 				lowercase_	(      self				:							List[Any])->  List[str]:



						'''simple docstring'''


						for model_name in TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
								__lowerCAmelCase:			Dict        =     TFRegNetModel.from_pretrained(UpperCAmelCase__)
								self.assertIsNotNone(UpperCAmelCase__)






def        a__       (       )      ->      Union[str, Any]:
		__lowerCAmelCase:			Optional[Any]        =     Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"					)
		return image





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

				@cached_property
				def 				lowercase_	(      self				:							Dict)->  List[Any]:



						'''simple docstring'''


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




				@slow
				def 				lowercase_	(      self				:							Union[str, Any])->  int:



						'''simple docstring'''


						__lowerCAmelCase:			int        =     TFRegNetForImageClassification.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0])

						__lowerCAmelCase:			Dict        =     self.default_image_processor
						__lowerCAmelCase:			List[Any]        =     prepare_img()
						__lowerCAmelCase:			str        =     image_processor(images=UpperCAmelCase__	,    return_tensors="tf")

						# forward pass
						__lowerCAmelCase:			List[Any]        =     model(**UpperCAmelCase__	,    training=UpperCAmelCase__)

						# verify the logits
						__lowerCAmelCase:			str        =     tf.TensorShape((1, 1_0_0_0))
						self.assertEqual(outputs.logits.shape	,    UpperCAmelCase__)

						__lowerCAmelCase:			List[Any]        =     tf.constant([-0.4180, -1.5051, -3.4836])

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








from typing import TYPE_CHECKING

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


_lowerCamelCase      :						Any							=  {"""configuration_xlnet""": ["""XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP""", """XLNetConfig"""]}

try:
  if not is_sentencepiece_available():
    raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
  pass
else:
  _lowerCamelCase      :						int							=  ["""XLNetTokenizer"""]

try:
  if not is_tokenizers_available():
    raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
  pass
else:
  _lowerCamelCase      :						int							=  ["""XLNetTokenizerFast"""]

try:
  if not is_torch_available():
    raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
  pass
else:
  _lowerCamelCase      :						Union[str, Any]							=  [
      """XLNET_PRETRAINED_MODEL_ARCHIVE_LIST""",
      """XLNetForMultipleChoice""",
      """XLNetForQuestionAnswering""",
      """XLNetForQuestionAnsweringSimple""",
      """XLNetForSequenceClassification""",
      """XLNetForTokenClassification""",
      """XLNetLMHeadModel""",
      """XLNetModel""",
      """XLNetPreTrainedModel""",
      """load_tf_weights_in_xlnet""",
  ]

try:
  if not is_tf_available():
    raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
  pass
else:
  _lowerCamelCase      :						Dict							=  [
      """TF_XLNET_PRETRAINED_MODEL_ARCHIVE_LIST""",
      """TFXLNetForMultipleChoice""",
      """TFXLNetForQuestionAnsweringSimple""",
      """TFXLNetForSequenceClassification""",
      """TFXLNetForTokenClassification""",
      """TFXLNetLMHeadModel""",
      """TFXLNetMainLayer""",
      """TFXLNetModel""",
      """TFXLNetPreTrainedModel""",
  ]


if TYPE_CHECKING:
  from .configuration_xlnet import XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP, XLNetConfig

  try:
    if not is_sentencepiece_available():
      raise OptionalDependencyNotAvailable()
  except OptionalDependencyNotAvailable:
    pass
  else:
    from .tokenization_xlnet import XLNetTokenizer

  try:
    if not is_tokenizers_available():
      raise OptionalDependencyNotAvailable()
  except OptionalDependencyNotAvailable:
    pass
  else:
    from .tokenization_xlnet_fast import XLNetTokenizerFast

  try:
    if not is_torch_available():
      raise OptionalDependencyNotAvailable()
  except OptionalDependencyNotAvailable:
    pass
  else:
    from .modeling_xlnet import (
        XLNET_PRETRAINED_MODEL_ARCHIVE_LIST,
        XLNetForMultipleChoice,
        XLNetForQuestionAnswering,
        XLNetForQuestionAnsweringSimple,
        XLNetForSequenceClassification,
        XLNetForTokenClassification,
        XLNetLMHeadModel,
        XLNetModel,
        XLNetPreTrainedModel,
        load_tf_weights_in_xlnet,
    )

  try:
    if not is_tf_available():
      raise OptionalDependencyNotAvailable()
  except OptionalDependencyNotAvailable:
    pass
  else:
    from .modeling_tf_xlnet import (
        TF_XLNET_PRETRAINED_MODEL_ARCHIVE_LIST,
        TFXLNetForMultipleChoice,
        TFXLNetForQuestionAnsweringSimple,
        TFXLNetForSequenceClassification,
        TFXLNetForTokenClassification,
        TFXLNetLMHeadModel,
        TFXLNetMainLayer,
        TFXLNetModel,
        TFXLNetPreTrainedModel,
    )

else:
  import sys

  _lowerCamelCase      :						int							=  _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)


