
"""simple docstring"""




from typing import List, Optional, Tuple, Union

from . import logging
from .import_utils import is_torch_available, is_torch_version


if is_torch_available():
			import torch

_A      :	List[str]       		=	logging.get_logger(__name__)  # pylint: disable=invalid-name

try:
			from torch._dynamo import allow_in_graph as maybe_allow_in_graph
except (ImportError, ModuleNotFoundError):


			def   __magic_name__     (				cls    :	int  )			->    Optional[int]:
										return cls


def   __magic_name__     (				__snake_case    :	Union[Tuple, List]					,			__snake_case    :	Optional[Union[List["torch.Generator"], "torch.Generator"]] = None					,			__snake_case    :	Optional["torch.device"] = None					,			__snake_case    :	Optional["torch.dtype"] = None					,			__snake_case    :	Optional["torch.layout"] = None					,			)			->    Dict:
							lowercase   :    List[Any]			=							device
							lowercase   :    Any			=							shape[0]

							lowercase   :    str			=							layout or torch.strided
							lowercase   :    Optional[int]			=							device or torch.device("cpu"  )

							if generator is not None:
														lowercase   :    Tuple			=							generator.device.type if not isinstance(__snake_case					,			__snake_case  ) else generator[0].device.type
														if gen_device_type != device.type and gen_device_type == "cpu":
																					lowercase   :    Dict			=							"cpu"
																					if device != "mps":
																												logger.info(
																												    f"""The passed generator was created on 'cpu' even though a tensor on {device} was expected."""
																												    f""" Tensors will be created on 'cpu' and then moved to {device}. Note that one can probably"""
																												    f""" slighly speed up this function by passing a generator that was created on the {device} device."""  )
														elif gen_device_type != device.type and gen_device_type == "cuda":
																					raise ValueError(f"""Cannot generate a {device} tensor from a generator of type {gen_device_type}."""  )

							if isinstance(__snake_case					,			__snake_case  ):
														lowercase   :    List[Any]			=							(1,) + shape[1:]
														lowercase   :    List[str]			=							[
														    torch.randn(__snake_case					,			generator=generator[i]					,			device=__snake_case					,			dtype=__snake_case					,			layout=__snake_case  )
														    for i in range(__snake_case  )
														]
														lowercase   :    Any			=							torch.cat(__snake_case					,			dim=0  ).to(__snake_case  )
							else:
														lowercase   :    Optional[Any]			=							torch.randn(__snake_case					,			generator=__snake_case					,			device=__snake_case					,			dtype=__snake_case					,			layout=__snake_case  ).to(__snake_case  )

							return latents


def   __magic_name__     (				__snake_case    :	Dict  )			->    Tuple:
							if is_torch_version("<"					,			"2.0.0"  ) or not hasattr(__snake_case					,			"_dynamo"  ):
														return False
							return isinstance(__snake_case					,			torch._dynamo.eval_frame.OptimizedModule  )




"""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__						:
   def __init__(      self     ,   _a     ,   _a=13     ,   _a=32     ,   _a=3     ,   _a=4     ,   _a=[10, 20, 30, 40]     ,   _a=[2, 2, 3, 2]     ,   _a=True     ,   _a=True     ,   _a=37     ,   _a="gelu"     ,   _a=10     ,   _a=0.0_2     ,   _a=3     ,   _a=None     ,   ):
          lowercase   :    Any			=							parent
          lowercase   :    Optional[int]			=							batch_size
          lowercase   :    Optional[Any]			=							image_size
          lowercase   :    Any			=							num_channels
          lowercase   :    str			=							num_stages
          lowercase   :    Union[str, Any]			=							hidden_sizes
          lowercase   :    Optional[Any]			=							depths
          lowercase   :    str			=							is_training
          lowercase   :    int			=							use_labels
          lowercase   :    str			=							intermediate_size
          lowercase   :    Dict			=							hidden_act
          lowercase   :    int			=							type_sequence_label_size
          lowercase   :    Optional[int]			=							initializer_range
          lowercase   :    Dict			=							scope
   def       __magic_name__      (      self    ):
          lowercase   :    Optional[Any]			=							floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]    )

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

          lowercase   :    str			=							self.get_config()

          return config, pixel_values, labels
   def       __magic_name__      (      self    ):
          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=_a     ,   initializer_range=self.initializer_range     ,   )
   def       __magic_name__      (      self     ,   _a     ,   _a     ,   _a    ):
          lowercase   :    Any			=							TFConvNextModel(config=_a    )
          lowercase   :    int			=							model(_a     ,   training=_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       __magic_name__      (      self     ,   _a     ,   _a     ,   _a    ):
          lowercase   :    List[Any]			=							self.type_sequence_label_size
          lowercase   :    List[str]			=							TFConvNextForImageClassification(_a    )
          lowercase   :    int			=							model(_a     ,   labels=_a     ,   training=_a    )
          self.parent.assertEqual(result.logits.shape     ,   (self.batch_size, self.type_sequence_label_size)    )

   def       __magic_name__      (      self    ):
          lowercase   :    Union[str, Any]			=							self.prepare_config_and_inputs()
          lowercase		,   lowercase		,   lowercase   :    str			=							config_and_inputs
          lowercase   :    List[Any]			=							{"pixel_values": pixel_values}
          return config, inputs_dict


@require_tf
class 		a__						(				a_,      a_,      unittest.TestCase						):
   __lowerCAmelCase						=    (TFConvNextModel, TFConvNextForImageClassification) if is_tf_available() else ()
   __lowerCAmelCase						=    (
       {"""feature-extraction""": TFConvNextModel, """image-classification""": TFConvNextForImageClassification}
       if is_tf_available()
       else {}
   )

   __lowerCAmelCase						=    False
   __lowerCAmelCase						=    False
   __lowerCAmelCase						=    False
   __lowerCAmelCase						=    False
   __lowerCAmelCase						=    False
   def       __magic_name__      (      self    ):
          lowercase   :    Tuple			=							TFConvNextModelTester(self    )
          lowercase   :    int			=							ConfigTester(
              self     ,   config_class=_a     ,   has_text_modality=_a     ,   hidden_size=37     ,   )
   @unittest.skip(reason="ConvNext does not use inputs_embeds"    )
   def       __magic_name__      (      self    ):
          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       __magic_name__      (      self    ):
          super().test_keras_fit()
   @unittest.skip(reason="ConvNext does not support input and output embeddings"    )
   def       __magic_name__      (      self    ):
          pass
   def       __magic_name__      (      self    ):
          lowercase		,   lowercase   :    List[str]			=							self.model_tester.prepare_config_and_inputs_for_common()

          for model_class in self.all_model_classes:
                 lowercase   :    Dict			=							model_class(_a    )
                 lowercase   :    str			=							inspect.signature(model.call    )
                 # signature.parameters is an OrderedDict => so arg_names order is deterministic
                 lowercase   :    Optional[int]			=							[*signature.parameters.keys()]

                 lowercase   :    Optional[Any]			=							["pixel_values"]
                 self.assertListEqual(arg_names[:1]     ,   _a    )
   def       __magic_name__      (      self    ):
          lowercase   :    Union[str, Any]			=							self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_model(*_a    )
   @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       __magic_name__      (      self    ):
          super().test_dataset_conversion()
   def       __magic_name__      (      self    ):
          def check_hidden_states_output(_a     ,   _a     ,   _a    ):
                 lowercase   :    str			=							model_class(_a    )

                 lowercase   :    Any			=							model(**self._prepare_for_class(_a     ,   _a    )    )
                 lowercase   :    Optional[Any]			=							outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

                 lowercase   :    str			=							self.model_tester.num_stages
                 self.assertEqual(len(_a    )     ,   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]     ,   )

          lowercase		,   lowercase   :    Any			=							self.model_tester.prepare_config_and_inputs_for_common()

          for model_class in self.all_model_classes:
                 lowercase   :    Union[str, Any]			=							True
                 check_hidden_states_output(_a     ,   _a     ,   _a    )

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

                 check_hidden_states_output(_a     ,   _a     ,   _a    )
   def       __magic_name__      (      self    ):
          lowercase		,   lowercase   :    List[str]			=							self.model_tester.prepare_config_and_inputs_for_common()

          def check_equivalence(_a     ,   _a     ,   _a     ,   _a={}    ):
                 lowercase   :    Union[str, Any]			=							model(_a     ,   return_dict=_a     ,   **_a    )
                 lowercase   :    Dict			=							model(_a     ,   return_dict=_a     ,   **_a    ).to_tuple()

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

                        recursive_check(_a     ,   _a    )

          for model_class in self.all_model_classes:
                 lowercase   :    str			=							model_class(_a    )

                 lowercase   :    int			=							self._prepare_for_class(_a     ,   _a    )
                 lowercase   :    Dict			=							self._prepare_for_class(_a     ,   _a    )
                 check_equivalence(_a     ,   _a     ,   _a    )

                 lowercase   :    Tuple			=							self._prepare_for_class(_a     ,   _a     ,   return_labels=_a    )
                 lowercase   :    Union[str, Any]			=							self._prepare_for_class(_a     ,   _a     ,   return_labels=_a    )
                 check_equivalence(_a     ,   _a     ,   _a    )

                 lowercase   :    Any			=							self._prepare_for_class(_a     ,   _a    )
                 lowercase   :    List[str]			=							self._prepare_for_class(_a     ,   _a    )
                 check_equivalence(_a     ,   _a     ,   _a     ,   {"output_hidden_states": True}    )

                 lowercase   :    Union[str, Any]			=							self._prepare_for_class(_a     ,   _a     ,   return_labels=_a    )
                 lowercase   :    Optional[Any]			=							self._prepare_for_class(_a     ,   _a     ,   return_labels=_a    )
                 check_equivalence(_a     ,   _a     ,   _a     ,   {"output_hidden_states": True}    )
   def       __magic_name__      (      self    ):
          lowercase   :    int			=							self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_for_image_classification(*_a    )

   @slow
   def       __magic_name__      (      self    ):
          lowercase   :    Tuple			=							TFConvNextModel.from_pretrained("facebook/convnext-tiny-224"    )
          self.assertIsNotNone(_a    )


def   __magic_name__     (				)			->    Any:
       lowercase   :    List[str]			=							Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"  )
       return image

@require_tf
@require_vision
class 		a__						(				unittest.TestCase						):
   @cached_property
   def       __magic_name__      (      self    ):
          return ConvNextImageProcessor.from_pretrained("facebook/convnext-tiny-224"    ) if is_vision_available() else None

   @slow
   def       __magic_name__      (      self    ):
          lowercase   :    Dict			=							TFConvNextForImageClassification.from_pretrained("facebook/convnext-tiny-224"    )

          lowercase   :    List[str]			=							self.default_image_processor
          lowercase   :    List[str]			=							prepare_img()
          lowercase   :    Union[str, Any]			=							image_processor(images=_a     ,   return_tensors="tf"    )

          # forward pass
          lowercase   :    str			=							model(**_a    )

          # verify the logits
          lowercase   :    List[str]			=							tf.TensorShape((1, 1_000)    )
          self.assertEqual(outputs.logits.shape     ,   _a    )

          lowercase   :    int			=							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]     ,   _a     ,   atol=1E-4    )


