




'''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       ,__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.02       ,__a=3       ,__a=None       ,)			->							str:
          snake_case :			str					   = parent
          snake_case :			Any					   = batch_size
          snake_case :			Tuple					   = image_size
          snake_case :			List[str]					   = num_channels
          snake_case :			Optional[int]					   = num_stages
          snake_case :			List[str]					   = hidden_sizes
          snake_case :			int					   = depths
          snake_case :			Optional[Any]					   = is_training
          snake_case :			Dict					   = use_labels
          snake_case :			Optional[Any]					   = intermediate_size
          snake_case :			Union[str, Any]					   = hidden_act
          snake_case :			List[Any]					   = type_sequence_label_size
          snake_case :			List[Any]					   = initializer_range
          snake_case :			List[Any]					   = scope







     def  snake_case_			(							self       )			->							List[str]:
          snake_case :			Tuple					   = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]       )

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

          snake_case :			List[str]					   = self.get_config()

          return config, pixel_values, labels







     def  snake_case_			(							self       )			->							Union[str, Any]:
          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  snake_case_			(							self       ,__a       ,__a       ,__a       )			->							Union[str, Any]:
          snake_case :			Optional[Any]					   = TFConvNextModel(config=__a       )
          snake_case :			Optional[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  snake_case_			(							self       ,__a       ,__a       ,__a       )			->							Dict:
          snake_case :			Any					   = self.type_sequence_label_size
          snake_case :			Any					   = TFConvNextForImageClassification(__a       )
          snake_case :			Tuple					   = model(__a       ,labels=__a       ,training=__a       )
          self.parent.assertEqual(result.logits.shape       ,(self.batch_size, self.type_sequence_label_size)       )







     def  snake_case_			(							self       )			->							Optional[int]:
          snake_case :			Dict					   = self.prepare_config_and_inputs()
          snake_case   ,		snake_case   ,		snake_case :			Union[str, Any]					   = config_and_inputs
          snake_case :			List[str]					   = {"""pixel_values""": pixel_values}
          return config, inputs_dict







@require_tf
class 				_a   (a__,		a__,		unittest.TestCase  ):





     '''simple docstring'''



     lowerCAmelCase_     :    List[Any]									=				(TFConvNextModel, TFConvNextForImageClassification) if is_tf_available() else ()
     lowerCAmelCase_     :    Tuple									=				(
         {"""feature-extraction""": TFConvNextModel, """image-classification""": TFConvNextForImageClassification}
         if is_tf_available()
         else {}
     )

     lowerCAmelCase_     :    int									=				False
     lowerCAmelCase_     :    str									=				False
     lowerCAmelCase_     :    List[Any]									=				False
     lowerCAmelCase_     :    Optional[Any]									=				False
     lowerCAmelCase_     :    int									=				False







     def  snake_case_			(							self       )			->							Union[str, Any]:
          snake_case :			Any					   = TFConvNextModelTester(self       )
          snake_case :			Optional[int]					   = ConfigTester(
              self       ,config_class=__a       ,has_text_modality=__a       ,hidden_size=37       ,)







     @unittest.skip(reason="""ConvNext does not use inputs_embeds"""       )
     def  snake_case_			(							self       )			->							List[Any]:
          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  snake_case_			(							self       )			->							Optional[int]:
          super().test_keras_fit()







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







     def  snake_case_			(							self       )			->							Any:
          snake_case   ,		snake_case :			int					   = self.model_tester.prepare_config_and_inputs_for_common()

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

               snake_case :			Tuple					   = ["""pixel_values"""]
               self.assertListEqual(arg_names[:1]       ,__a       )







     def  snake_case_			(							self       )			->							Optional[int]:
          snake_case :			Dict					   = 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  snake_case_			(							self       )			->							List[str]:
          super().test_dataset_conversion()







     def  snake_case_			(							self       )			->							Tuple:
          def check_hidden_states_output(__a       ,__a       ,__a       ):
               snake_case :			List[Any]					   = model_class(__a       )

               snake_case :			int					   = model(**self._prepare_for_class(__a       ,__a       )       )
               snake_case :			Dict					   = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

               snake_case :			int					   = 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]       ,)

          snake_case   ,		snake_case :			Dict					   = self.model_tester.prepare_config_and_inputs_for_common()

          for model_class in self.all_model_classes:
               snake_case :			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"]
               snake_case :			Dict					   = True

               check_hidden_states_output(__a       ,__a       ,__a       )







     def  snake_case_			(							self       )			->							str:
          snake_case   ,		snake_case :			Optional[int]					   = self.model_tester.prepare_config_and_inputs_for_common()

          def check_equivalence(__a       ,__a       ,__a       ,__a={}       ):
               snake_case :			Dict					   = model(__a       ,return_dict=__a       ,**__a       )
               snake_case :			str					   = 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:
               snake_case :			str					   = model_class(__a       )

               snake_case :			Tuple					   = self._prepare_for_class(__a       ,__a       )
               snake_case :			Optional[Any]					   = self._prepare_for_class(__a       ,__a       )
               check_equivalence(__a       ,__a       ,__a       )

               snake_case :			Optional[Any]					   = self._prepare_for_class(__a       ,__a       ,return_labels=__a       )
               snake_case :			Tuple					   = self._prepare_for_class(__a       ,__a       ,return_labels=__a       )
               check_equivalence(__a       ,__a       ,__a       )

               snake_case :			Tuple					   = self._prepare_for_class(__a       ,__a       )
               snake_case :			Union[str, Any]					   = self._prepare_for_class(__a       ,__a       )
               check_equivalence(__a       ,__a       ,__a       ,{"""output_hidden_states""": True}       )

               snake_case :			int					   = self._prepare_for_class(__a       ,__a       ,return_labels=__a       )
               snake_case :			Optional[Any]					   = self._prepare_for_class(__a       ,__a       ,return_labels=__a       )
               check_equivalence(__a       ,__a       ,__a       ,{"""output_hidden_states""": True}       )







     def  snake_case_			(							self       )			->							Optional[Any]:
          snake_case :			Union[str, Any]					   = self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_for_image_classification(*__a       )







     @slow
     def  snake_case_			(							self       )			->							Any:
          snake_case :			Any					   = TFConvNextModel.from_pretrained("""facebook/convnext-tiny-224"""       )
          self.assertIsNotNone(__a       )



def 					lowerCamelCase__							(			):
     snake_case :			Optional[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  snake_case_			(							self       )			->							int:
          return ConvNextImageProcessor.from_pretrained("""facebook/convnext-tiny-224"""       ) if is_vision_available() else None







     @slow
     def  snake_case_			(							self       )			->							Optional[int]:
          snake_case :			Optional[Any]					   = TFConvNextForImageClassification.from_pretrained("""facebook/convnext-tiny-224"""       )

          snake_case :			List[Any]					   = self.default_image_processor
          snake_case :			Optional[Any]					   = prepare_img()
          snake_case :			List[str]					   = image_processor(images=__a       ,return_tensors="""tf"""       )

          # forward pass
          snake_case :			Any					   = model(**__a       )

          # verify the logits
          snake_case :			int					   = tf.TensorShape((1, 1_000)       )
          self.assertEqual(outputs.logits.shape       ,__a       )

          snake_case :			Any					   = tf.constant([-0.0_260, -0.4_739, 0.1_911]       )

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









'''simple docstring'''







from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_torch_available


lowercase			:      Tuple			=					{"""configuration_bert_generation""": ["""BertGenerationConfig"""]}

try:
      if not is_sentencepiece_available():
            raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
      pass
else:
      lowercase			:      Tuple			=					["""BertGenerationTokenizer"""]

try:
      if not is_torch_available():
            raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
      pass
else:
      lowercase			:      List[Any]			=					[
          """BertGenerationDecoder""",
          """BertGenerationEncoder""",
          """BertGenerationPreTrainedModel""",
          """load_tf_weights_in_bert_generation""",
      ]


if TYPE_CHECKING:
      from .configuration_bert_generation import BertGenerationConfig

      try:
            if not is_sentencepiece_available():
                  raise OptionalDependencyNotAvailable()
      except OptionalDependencyNotAvailable:
            pass
      else:
            from .tokenization_bert_generation import BertGenerationTokenizer

      try:
            if not is_torch_available():
                  raise OptionalDependencyNotAvailable()
      except OptionalDependencyNotAvailable:
            pass
      else:
            from .modeling_bert_generation import (
                BertGenerationDecoder,
                BertGenerationEncoder,
                BertGenerationPreTrainedModel,
                load_tf_weights_in_bert_generation,
            )

else:
      import sys

      lowercase			:      Optional[Any]			=					_LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)



