



"""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    SCREAMING_SNAKE_CASE__						:

   def __init__(     self   ,  _SCREAMING_SNAKE_CASE   ,  _SCREAMING_SNAKE_CASE=3   ,  _SCREAMING_SNAKE_CASE=32   ,  _SCREAMING_SNAKE_CASE=3   ,  _SCREAMING_SNAKE_CASE=10   ,  _SCREAMING_SNAKE_CASE=[10, 20, 30, 40]   ,  _SCREAMING_SNAKE_CASE=[1, 1, 2, 1]   ,  _SCREAMING_SNAKE_CASE=True   ,  _SCREAMING_SNAKE_CASE=True   ,  _SCREAMING_SNAKE_CASE="relu"   ,  _SCREAMING_SNAKE_CASE=3   ,  _SCREAMING_SNAKE_CASE=None   ,  )						->   Optional[int]:





    '''simple docstring'''




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

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





    '''simple docstring'''




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

    UpperCAmelCase			:      Any			=			None
    if self.use_labels:
     UpperCAmelCase			:      Dict			=			ids_tensor([self.batch_size]   ,  self.num_labels		)

    UpperCAmelCase			:      List[Any]			=			self.get_config()
    return config, pixel_values, labels

   def 			SCREAMING_SNAKE_CASE  (     self		)						->   Dict:





    '''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 			SCREAMING_SNAKE_CASE  (     self   ,  _SCREAMING_SNAKE_CASE   ,  _SCREAMING_SNAKE_CASE   ,  _SCREAMING_SNAKE_CASE		)						->   str:





    '''simple docstring'''




    UpperCAmelCase			:      Any			=			TFRegNetModel(config=__lowercase		)
    UpperCAmelCase			:      List[str]			=			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 			SCREAMING_SNAKE_CASE  (     self   ,  _SCREAMING_SNAKE_CASE   ,  _SCREAMING_SNAKE_CASE   ,  _SCREAMING_SNAKE_CASE		)						->   Union[str, Any]:





    '''simple docstring'''




    UpperCAmelCase			:      Union[str, Any]			=			self.num_labels
    UpperCAmelCase			:      Tuple			=			TFRegNetForImageClassification(__lowercase		)
    UpperCAmelCase			:      Union[str, Any]			=			model(__lowercase   ,  labels=__lowercase   ,  training=__lowercase		)
    self.parent.assertEqual(result.logits.shape   ,  (self.batch_size, self.num_labels)		)




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





    '''simple docstring'''




    UpperCAmelCase			:      Optional[Any]			=			self.prepare_config_and_inputs()
    UpperCAmelCase			,	UpperCAmelCase			,	UpperCAmelCase			:      List[str]			=			config_and_inputs
    UpperCAmelCase			:      List[str]			=			{"""pixel_values""": pixel_values}
    return config, inputs_dict



@require_tf
class    SCREAMING_SNAKE_CASE__						(      lowercase__   ,    lowercase__   ,    unittest.TestCase				):
   __lowerCAmelCase						:     Optional[int]		=		(TFRegNetModel, TFRegNetForImageClassification) if is_tf_available() else ()
   __lowerCAmelCase						:     List[str]		=		(
       {"""feature-extraction""": TFRegNetModel, """image-classification""": TFRegNetForImageClassification}
       if is_tf_available()
       else {}
   )

   __lowerCAmelCase						:     int		=		False
   __lowerCAmelCase						:     str		=		False
   __lowerCAmelCase						:     int		=		False
   __lowerCAmelCase						:     Optional[int]		=		False
   __lowerCAmelCase						:     Optional[int]		=		False

   def 			SCREAMING_SNAKE_CASE  (     self		)						->   Tuple:





    '''simple docstring'''




    UpperCAmelCase			:      List[str]			=			TFRegNetModelTester(self		)
    UpperCAmelCase			:      Union[str, Any]			=			ConfigTester(self   ,  config_class=__lowercase   ,  has_text_modality=__lowercase		)

   def 			SCREAMING_SNAKE_CASE  (     self		)						->   Optional[Any]:





    '''simple docstring'''




    return

   @unittest.skip(reason="""RegNet does not use inputs_embeds"""		)
   def 			SCREAMING_SNAKE_CASE  (     self		)						->   Optional[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 			SCREAMING_SNAKE_CASE  (     self		)						->   int:





    '''simple docstring'''




    super().test_keras_fit()

   @unittest.skip(reason="""RegNet does not support input and output embeddings"""		)
   def 			SCREAMING_SNAKE_CASE  (     self		)						->   Optional[Any]:





    '''simple docstring'''




    pass

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





    '''simple docstring'''




    UpperCAmelCase			,	UpperCAmelCase			:      Optional[int]			=			self.model_tester.prepare_config_and_inputs_for_common()

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

     UpperCAmelCase			:      Optional[int]			=			["""pixel_values"""]
     self.assertListEqual(arg_names[:1]   ,  __lowercase		)

   def 			SCREAMING_SNAKE_CASE  (     self		)						->   Dict:





    '''simple docstring'''




    UpperCAmelCase			:      List[Any]			=			self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_model(*__lowercase		)

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





    '''simple docstring'''




    def check_hidden_states_output(_SCREAMING_SNAKE_CASE   ,  _SCREAMING_SNAKE_CASE   ,  _SCREAMING_SNAKE_CASE		):
     UpperCAmelCase			:      Tuple			=			model_class(__lowercase		)
     UpperCAmelCase			:      List[Any]			=			model(**self._prepare_for_class(__lowercase   ,  __lowercase		)   ,  training=__lowercase		)

     UpperCAmelCase			:      List[str]			=			outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

     UpperCAmelCase			:      List[Any]			=			self.model_tester.num_stages
     self.assertEqual(len(__lowercase		)   ,  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]   ,  )

    UpperCAmelCase			,	UpperCAmelCase			:      List[Any]			=			self.model_tester.prepare_config_and_inputs_for_common()
    UpperCAmelCase			:      Tuple			=			["""basic""", """bottleneck"""]
    for model_class in self.all_model_classes:
     for layer_type in layers_type:
      UpperCAmelCase			:      Optional[int]			=			layer_type
      UpperCAmelCase			:      Tuple			=			True
      check_hidden_states_output(__lowercase   ,  __lowercase   ,  __lowercase		)

      # check that output_hidden_states also work using config
      del inputs_dict["output_hidden_states"]
      UpperCAmelCase			:      List[str]			=			True

      check_hidden_states_output(__lowercase   ,  __lowercase   ,  __lowercase		)

   def 			SCREAMING_SNAKE_CASE  (     self		)						->   int:





    '''simple docstring'''




    UpperCAmelCase			,	UpperCAmelCase			:      List[Any]			=			self.model_tester.prepare_config_and_inputs_for_common()

    def check_equivalence(_SCREAMING_SNAKE_CASE   ,  _SCREAMING_SNAKE_CASE   ,  _SCREAMING_SNAKE_CASE   ,  _SCREAMING_SNAKE_CASE={}		):
     UpperCAmelCase			:      Dict			=			model(__lowercase   ,  return_dict=__lowercase   ,  **__lowercase		)
     UpperCAmelCase			:      Dict			=			model(__lowercase   ,  return_dict=__lowercase   ,  **__lowercase		).to_tuple()

     def recursive_check(_SCREAMING_SNAKE_CASE   ,  _SCREAMING_SNAKE_CASE		):
      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			:      List[Any]			=			model_class(__lowercase		)

     UpperCAmelCase			:      int			=			self._prepare_for_class(__lowercase   ,  __lowercase		)
     UpperCAmelCase			:      Tuple			=			self._prepare_for_class(__lowercase   ,  __lowercase		)
     check_equivalence(__lowercase   ,  __lowercase   ,  __lowercase		)

     UpperCAmelCase			:      Union[str, Any]			=			self._prepare_for_class(__lowercase   ,  __lowercase   ,  return_labels=__lowercase		)
     UpperCAmelCase			:      str			=			self._prepare_for_class(__lowercase   ,  __lowercase   ,  return_labels=__lowercase		)
     check_equivalence(__lowercase   ,  __lowercase   ,  __lowercase		)

     UpperCAmelCase			:      str			=			self._prepare_for_class(__lowercase   ,  __lowercase		)
     UpperCAmelCase			:      str			=			self._prepare_for_class(__lowercase   ,  __lowercase		)
     check_equivalence(__lowercase   ,  __lowercase   ,  __lowercase   ,  {"""output_hidden_states""": True}		)

     UpperCAmelCase			:      Tuple			=			self._prepare_for_class(__lowercase   ,  __lowercase   ,  return_labels=__lowercase		)
     UpperCAmelCase			:      str			=			self._prepare_for_class(__lowercase   ,  __lowercase   ,  return_labels=__lowercase		)
     check_equivalence(__lowercase   ,  __lowercase   ,  __lowercase   ,  {"""output_hidden_states""": True}		)

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





    '''simple docstring'''




    UpperCAmelCase			:      Union[str, Any]			=			self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_for_image_classification(*__lowercase		)




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





    '''simple docstring'''




    for model_name in TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
     UpperCAmelCase			:      Union[str, Any]			=			TFRegNetModel.from_pretrained(__lowercase		)
     self.assertIsNotNone(__lowercase		)

def    _snake_case		(		):
 UpperCAmelCase			:      List[str]			=			Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""		)
 return image



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

   @cached_property
   def 			SCREAMING_SNAKE_CASE  (     self		)						->   Optional[int]:





    '''simple docstring'''




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




   @slow
   def 			SCREAMING_SNAKE_CASE  (     self		)						->   str:





    '''simple docstring'''




    UpperCAmelCase			:      Any			=			TFRegNetForImageClassification.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]		)

    UpperCAmelCase			:      int			=			self.default_image_processor
    UpperCAmelCase			:      List[str]			=			prepare_img()
    UpperCAmelCase			:      Dict			=			image_processor(images=__lowercase   ,  return_tensors="""tf"""		)

    # forward pass
    UpperCAmelCase			:      Union[str, Any]			=			model(**__lowercase   ,  training=__lowercase		)

    # verify the logits
    UpperCAmelCase			:      int			=			tf.TensorShape((1, 1000)		)
    self.assertEqual(outputs.logits.shape   ,  __lowercase		)

    UpperCAmelCase			:      Dict			=			tf.constant([-0.4180, -1.5051, -3.4836]		)

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







"""simple docstring"""
import os
import unittest

from transformers.models.transfo_xl.tokenization_transfo_xl import VOCAB_FILES_NAMES, TransfoXLTokenizer

from ...test_tokenization_common import TokenizerTesterMixin



class    SCREAMING_SNAKE_CASE__						(      UpperCAmelCase__   ,    unittest.TestCase				):
   __lowerCAmelCase						:     List[Any]		=		TransfoXLTokenizer
   __lowerCAmelCase						:     Optional[int]		=		False
   __lowerCAmelCase						:     Optional[Any]		=		False

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





    '''simple docstring'''




    super().setUp()

    UpperCAmelCase			:      Optional[Any]			=			[
        """<unk>""",
        """[CLS]""",
        """[SEP]""",
        """want""",
        """unwanted""",
        """wa""",
        """un""",
        """running""",
        """,""",
        """low""",
        """l""",
    ]
    UpperCAmelCase			:      int			=			os.path.join(self.tmpdirname   ,  VOCAB_FILES_NAMES["""vocab_file"""]		)
    with open(self.vocab_file   ,  """w"""   ,  encoding="""utf-8"""		) as vocab_writer:
     vocab_writer.write("""""".join([x + """\n""" for x in vocab_tokens]		)		)

   def 			SCREAMING_SNAKE_CASE  (     self   ,  **_SCREAMING_SNAKE_CASE		)						->   List[Any]:





    '''simple docstring'''




    UpperCAmelCase			:      Optional[Any]			=			True
    return TransfoXLTokenizer.from_pretrained(self.tmpdirname   ,  **_SCREAMING_SNAKE_CASE		)

   def 			SCREAMING_SNAKE_CASE  (     self   ,  _SCREAMING_SNAKE_CASE		)						->   List[Any]:





    '''simple docstring'''




    UpperCAmelCase			:      int			=			"""<unk> UNwanted , running"""
    UpperCAmelCase			:      Dict			=			"""<unk> unwanted, running"""
    return input_text, output_text

   def 			SCREAMING_SNAKE_CASE  (     self		)						->   Any:





    '''simple docstring'''




    UpperCAmelCase			:      List[str]			=			TransfoXLTokenizer(vocab_file=self.vocab_file   ,  lower_case=_SCREAMING_SNAKE_CASE		)

    UpperCAmelCase			:      Dict			=			tokenizer.tokenize("""<unk> UNwanted , running"""		)
    self.assertListEqual(_SCREAMING_SNAKE_CASE   ,  ["""<unk>""", """unwanted""", """,""", """running"""]		)

    self.assertListEqual(tokenizer.convert_tokens_to_ids(_SCREAMING_SNAKE_CASE		)   ,  [0, 4, 8, 7]		)

   def 			SCREAMING_SNAKE_CASE  (     self		)						->   Tuple:





    '''simple docstring'''




    UpperCAmelCase			:      Tuple			=			TransfoXLTokenizer(lower_case=_SCREAMING_SNAKE_CASE		)

    self.assertListEqual(
        tokenizer.tokenize(""" \tHeLLo ! how  \n Are yoU ?  """		)   ,  ["""hello""", """!""", """how""", """are""", """you""", """?"""]		)

   def 			SCREAMING_SNAKE_CASE  (     self		)						->   Optional[Any]:





    '''simple docstring'''




    UpperCAmelCase			:      Optional[Any]			=			TransfoXLTokenizer(lower_case=_SCREAMING_SNAKE_CASE		)

    self.assertListEqual(
        tokenizer.tokenize(""" \tHeLLo ! how  \n Are yoU ?  """		)   ,  ["""HeLLo""", """!""", """how""", """Are""", """yoU""", """?"""]		)

   def 			SCREAMING_SNAKE_CASE  (     self		)						->   int:





    '''simple docstring'''




    UpperCAmelCase			:      List[Any]			=			TransfoXLTokenizer(lower_case=_SCREAMING_SNAKE_CASE		)
    UpperCAmelCase			:      Dict			=			"""Hello (bracket) and side-scrolled [and] Henry's $5,000 with 3.34 m. What's up!?"""
    UpperCAmelCase			:      Optional[Any]			=			[
        """Hello""",
        """(""",
        """bracket""",
        """)""",
        """and""",
        """side""",
        """@-@""",
        """scrolled""",
        """[""",
        """and""",
        """]""",
        """Henry""",
        """'s""",
        """$""",
        """5""",
        """@,@""",
        """000""",
        """with""",
        """3""",
        """@.@""",
        """34""",
        """m""",
        """.""",
        """What""",
        """'s""",
        """up""",
        """!""",
        """?""",
    ]

    self.assertListEqual(tokenizer.tokenize(_SCREAMING_SNAKE_CASE		)   ,  _SCREAMING_SNAKE_CASE		)

    self.assertEqual(tokenizer.convert_tokens_to_string(_SCREAMING_SNAKE_CASE		)   ,  _SCREAMING_SNAKE_CASE		)




   def 			SCREAMING_SNAKE_CASE  (     self		)						->   Dict:





    '''simple docstring'''




    UpperCAmelCase			:      List[str]			=			self.get_tokenizer()
    UpperCAmelCase			:      Tuple			=			len(_SCREAMING_SNAKE_CASE		)

    tokenizer.add_tokens(["""new1""", """new2"""]		)
    tokenizer.move_added_token("""new1"""   ,  1		)

    # Check that moved token is not copied (duplicate)
    self.assertEqual(len(_SCREAMING_SNAKE_CASE		)   ,  original_len + 2		)
    # Check that token is moved to specified id
    self.assertEqual(tokenizer.encode("""new1"""		)   ,  [1]		)
    self.assertEqual(tokenizer.decode([1]		)   ,  """new1"""		)
