



from __future__ import annotations

import inspect
import unittest
from math import floor

import numpy as np

from transformers import CvtConfig
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 TFCvtForImageClassification, TFCvtModel
  from transformers.models.cvt.modeling_tf_cvt import TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
  from PIL import Image

  from transformers import AutoImageProcessor







class 		snake_case						(	SCREAMING_SNAKE_CASE_  ):



   '''simple docstring'''






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

    """simple docstring"""







    _snake_case    :  List[Any]					=					self.config_class(**self.inputs_dict)
    self.parent.assertTrue(hasattr(lowerCAmelCase				,		"""embed_dim"""))
    self.parent.assertTrue(hasattr(lowerCAmelCase				,		"""num_heads"""))







class 		snake_case						:



   '''simple docstring'''






   def __init__(					self							:			Optional[Any]				,		lowerCAmelCase							:			List[Any]				,		lowerCAmelCase							:			Optional[Any]=13				,		lowerCAmelCase							:			int=64				,		lowerCAmelCase							:			int=3				,		lowerCAmelCase							:			List[str]=[16, 48, 96]				,		lowerCAmelCase							:			Optional[int]=[1, 3, 6]				,		lowerCAmelCase							:			Dict=[1, 2, 10]				,		lowerCAmelCase							:			Optional[int]=[7, 3, 3]				,		lowerCAmelCase							:			int=[4, 2, 2]				,		lowerCAmelCase							:			Dict=[2, 1, 1]				,		lowerCAmelCase							:			Optional[Any]=[2, 2, 2]				,		lowerCAmelCase							:			str=[False, False, True]				,		lowerCAmelCase							:			Dict=[0.0, 0.0, 0.0]				,		lowerCAmelCase							:			Union[str, Any]=0.02				,		lowerCAmelCase							:			Any=1E-12				,		lowerCAmelCase							:			List[Any]=True				,		lowerCAmelCase							:			Optional[int]=True				,		lowerCAmelCase							:			int=2				,		)				->				List[Any]:

    """simple docstring"""







    _snake_case    :  Union[str, Any]					=					parent
    _snake_case    :  Optional[int]					=					batch_size
    _snake_case    :  int					=					image_size
    _snake_case    :  int					=					patch_sizes
    _snake_case    :  Union[str, Any]					=					patch_stride
    _snake_case    :  Any					=					patch_padding
    _snake_case    :  int					=					is_training
    _snake_case    :  Dict					=					use_labels
    _snake_case    :  Any					=					num_labels
    _snake_case    :  Union[str, Any]					=					num_channels
    _snake_case    :  List[str]					=					embed_dim
    _snake_case    :  Optional[Any]					=					num_heads
    _snake_case    :  Optional[int]					=					stride_kv
    _snake_case    :  Any					=					depth
    _snake_case    :  Union[str, Any]					=					cls_token
    _snake_case    :  Union[str, Any]					=					attention_drop_rate
    _snake_case    :  int					=					initializer_range
    _snake_case    :  Optional[int]					=					layer_norm_eps

   def      UpperCamelCase_  (					self							:			Any)				->				int:

    """simple docstring"""







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

    _snake_case    :  Union[str, Any]					=					None
    if self.use_labels:
     # create a random int32 tensor of given shape
     _snake_case    :  Optional[Any]					=					ids_tensor([self.batch_size]				,		self.num_labels)

    _snake_case    :  List[str]					=					self.get_config()
    return config, pixel_values, labels

   def      UpperCamelCase_  (					self							:			int)				->				Tuple:

    """simple docstring"""







    return CvtConfig(
        image_size=self.image_size				,		num_labels=self.num_labels				,		num_channels=self.num_channels				,		embed_dim=self.embed_dim				,		num_heads=self.num_heads				,		patch_sizes=self.patch_sizes				,		patch_padding=self.patch_padding				,		patch_stride=self.patch_stride				,		stride_kv=self.stride_kv				,		depth=self.depth				,		cls_token=self.cls_token				,		attention_drop_rate=self.attention_drop_rate				,		initializer_range=self.initializer_range				,		)

   def      UpperCamelCase_  (					self							:			Optional[Any]				,		lowerCAmelCase							:			Tuple				,		lowerCAmelCase							:			Optional[int]				,		lowerCAmelCase							:			List[str])				->				str:

    """simple docstring"""







    _snake_case    :  Optional[int]					=					TFCvtModel(config=lowerCAmelCase)
    _snake_case    :  List[Any]					=					model(lowerCAmelCase				,		training=lowerCAmelCase)
    _snake_case    :  Any					=					(self.image_size, self.image_size)
    _snake_case	,    _snake_case    :  Any					=					image_size[0], image_size[1]
    for i in range(len(self.depth)):
     _snake_case    :  Optional[Any]					=					floor(((height + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1)
     _snake_case    :  List[str]					=					floor(((width + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1)
    self.parent.assertEqual(result.last_hidden_state.shape				,		(self.batch_size, self.embed_dim[-1], height, width))

   def      UpperCamelCase_  (					self							:			List[Any]				,		lowerCAmelCase							:			Any				,		lowerCAmelCase							:			Union[str, Any]				,		lowerCAmelCase							:			List[Any])				->				str:

    """simple docstring"""







    _snake_case    :  str					=					self.num_labels
    _snake_case    :  Tuple					=					TFCvtForImageClassification(lowerCAmelCase)
    _snake_case    :  Union[str, Any]					=					model(lowerCAmelCase				,		labels=lowerCAmelCase				,		training=lowerCAmelCase)
    self.parent.assertEqual(result.logits.shape				,		(self.batch_size, self.num_labels))


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

    """simple docstring"""







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







@require_tf
class 		snake_case						(	SCREAMING_SNAKE_CASE_					,SCREAMING_SNAKE_CASE_					,unittest.TestCase  ):



   '''simple docstring'''






   snake_case_					: Tuple          =		(TFCvtModel, TFCvtForImageClassification) if is_tf_available() else ()
   snake_case_					: int          =		(
       {"""feature-extraction""": TFCvtModel, """image-classification""": TFCvtForImageClassification}
       if is_tf_available()
       else {}
   )
   snake_case_					: Tuple          =		False
   snake_case_					: List[Any]          =		False
   snake_case_					: List[Any]          =		False
   snake_case_					: List[Any]          =		False
   snake_case_					: Optional[int]          =		False

   def      UpperCamelCase_  (					self							:			List[str])				->				Optional[Any]:

    """simple docstring"""







    _snake_case    :  int					=					TFCvtModelTester(self)
    _snake_case    :  Optional[Any]					=					TFCvtConfigTester(self				,		config_class=lowerCAmelCase				,		has_text_modality=lowerCAmelCase				,		hidden_size=37)

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

    """simple docstring"""







    self.config_tester.create_and_test_config_common_properties()
    self.config_tester.create_and_test_config_to_json_string()
    self.config_tester.create_and_test_config_to_json_file()
    self.config_tester.create_and_test_config_from_and_save_pretrained()
    self.config_tester.create_and_test_config_with_num_labels()
    self.config_tester.check_config_can_be_init_without_params()
    self.config_tester.check_config_arguments_init()

   @unittest.skip(reason="""Cvt does not output attentions""")
   def      UpperCamelCase_  (					self							:			str)				->				Any:

    """simple docstring"""







    pass

   @unittest.skip(reason="""Cvt does not use inputs_embeds""")
   def      UpperCamelCase_  (					self							:			Dict)				->				Union[str, Any]:

    """simple docstring"""







    pass

   @unittest.skip(reason="""Cvt does not support input and output embeddings""")
   def      UpperCamelCase_  (					self							:			Union[str, Any])				->				List[str]:

    """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."""				,		)
   def      UpperCamelCase_  (					self							:			str)				->				Tuple:

    """simple docstring"""







    super().test_dataset_conversion()

   @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      UpperCamelCase_  (					self							:			Union[str, Any])				->				int:

    """simple docstring"""







    super().test_keras_fit()

   @unittest.skip(reason="""Get `Failed to determine best cudnn convolution algo.` error after using TF 2.12+cuda 11.8""")
   def      UpperCamelCase_  (					self							:			Union[str, Any])				->				int:

    """simple docstring"""







    _snake_case    :  Union[str, Any]					=					tf.keras.mixed_precision.Policy("""mixed_float16""")
    tf.keras.mixed_precision.set_global_policy(lowerCAmelCase)
    super().test_keras_fit()
    tf.keras.mixed_precision.set_global_policy("""float32""")

   def      UpperCamelCase_  (					self							:			Optional[Any])				->				Optional[int]:

    """simple docstring"""







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

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

     _snake_case    :  Dict					=					["""pixel_values"""]
     self.assertListEqual(arg_names[:1]				,		lowerCAmelCase)

   def      UpperCamelCase_  (					self							:			Optional[int])				->				Any:

    """simple docstring"""







    def check_hidden_states_output(lowerCAmelCase							:			Dict				,		lowerCAmelCase							:			List[Any]				,		lowerCAmelCase							:			Optional[Any]):
     _snake_case    :  Union[str, Any]					=					model_class(lowerCAmelCase)

     _snake_case    :  Any					=					model(**self._prepare_for_class(lowerCAmelCase				,		lowerCAmelCase))
     _snake_case    :  Optional[Any]					=					outputs.hidden_states

     _snake_case    :  Dict					=					len(self.model_tester.depth)
     self.assertEqual(len(lowerCAmelCase)				,		lowerCAmelCase)

     # verify the first hidden states (first block)
     self.assertListEqual(
         list(hidden_states[0].shape[-3:])				,		[
             self.model_tester.embed_dim[0],
             self.model_tester.image_size // 4,
             self.model_tester.image_size // 4,
         ]				,		)

    _snake_case	,    _snake_case    :  List[str]					=					self.model_tester.prepare_config_and_inputs_for_common()

    for model_class in self.all_model_classes:
     _snake_case    :  Any					=					True
     check_hidden_states_output(lowerCAmelCase				,		lowerCAmelCase				,		lowerCAmelCase)

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

     check_hidden_states_output(lowerCAmelCase				,		lowerCAmelCase				,		lowerCAmelCase)

   def      UpperCamelCase_  (					self							:			Optional[Any])				->				Optional[int]:

    """simple docstring"""







    _snake_case    :  Optional[Any]					=					self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_model(*lowerCAmelCase)

   def      UpperCamelCase_  (					self							:			Dict)				->				str:

    """simple docstring"""







    _snake_case    :  str					=					self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_for_image_classification(*lowerCAmelCase)


   @slow
   def      UpperCamelCase_  (					self							:			Optional[int])				->				int:

    """simple docstring"""







    for model_name in TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
     _snake_case    :  str					=					TFCvtModel.from_pretrained(lowerCAmelCase)
     self.assertIsNotNone(lowerCAmelCase)



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







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



   '''simple docstring'''






   @cached_property
   def      UpperCamelCase_  (					self							:			Dict)				->				Union[str, Any]:

    """simple docstring"""







    return AutoImageProcessor.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0])


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

    """simple docstring"""







    _snake_case    :  Dict					=					TFCvtForImageClassification.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0])

    _snake_case    :  Union[str, Any]					=					self.default_image_processor
    _snake_case    :  Any					=					prepare_img()
    _snake_case    :  str					=					image_processor(images=lowerCAmelCase				,		return_tensors="""tf""")

    # forward pass
    _snake_case    :  Optional[int]					=					model(**lowerCAmelCase)

    # verify the logits
    _snake_case    :  Optional[Any]					=					tf.TensorShape((1, 1000))
    self.assertEqual(outputs.logits.shape				,		lowerCAmelCase)

    _snake_case    :  int					=					tf.constant([0.9_285, 0.9_015, -0.3_150])
    self.assertTrue(np.allclose(outputs.logits[0, :3].numpy()				,		lowerCAmelCase				,		atol=1E-4))





import json
import os
import unittest

from transformers.models.ctrl.tokenization_ctrl import VOCAB_FILES_NAMES, CTRLTokenizer

from ...test_tokenization_common import TokenizerTesterMixin







class 		snake_case						(	SCREAMING_SNAKE_CASE_					,unittest.TestCase  ):



   '''simple docstring'''






   snake_case_					: Optional[Any]          =		CTRLTokenizer
   snake_case_					: Optional[Any]          =		False
   snake_case_					: List[Any]          =		False

   def      UpperCamelCase_  (					self							:			int)				->				Dict:

    """simple docstring"""







    super().setUp()

    # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt
    _snake_case    :  Dict					=					["""adapt""", """re@@""", """a@@""", """apt""", """c@@""", """t""", """<unk>"""]
    _snake_case    :  Optional[int]					=					dict(zip(lowerCAmelCase				,		range(len(lowerCAmelCase))))
    _snake_case    :  int					=					["""#version: 0.2""", """a p""", """ap t</w>""", """r e""", """a d""", """ad apt</w>""", """"""]
    _snake_case    :  List[Any]					=					{"""unk_token""": """<unk>"""}

    _snake_case    :  Dict					=					os.path.join(self.tmpdirname				,		VOCAB_FILES_NAMES["""vocab_file"""])
    _snake_case    :  Any					=					os.path.join(self.tmpdirname				,		VOCAB_FILES_NAMES["""merges_file"""])
    with open(self.vocab_file				,		"""w"""				,		encoding="""utf-8""") as fp:
     fp.write(json.dumps(lowerCAmelCase) + """\n""")
    with open(self.merges_file				,		"""w"""				,		encoding="""utf-8""") as fp:
     fp.write("""\n""".join(lowerCAmelCase))

   def      UpperCamelCase_  (					self							:			Dict				,		**lowerCAmelCase							:			int)				->				Optional[Any]:

    """simple docstring"""







    kwargs.update(self.special_tokens_map)
    return CTRLTokenizer.from_pretrained(self.tmpdirname				,		**lowerCAmelCase)

   def      UpperCamelCase_  (					self							:			Any				,		lowerCAmelCase							:			Optional[int])				->				Optional[int]:

    """simple docstring"""







    _snake_case    :  Tuple					=					"""adapt react readapt apt"""
    _snake_case    :  Tuple					=					"""adapt react readapt apt"""
    return input_text, output_text


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

    """simple docstring"""







    _snake_case    :  str					=					CTRLTokenizer(self.vocab_file				,		self.merges_file				,		**self.special_tokens_map)
    _snake_case    :  Dict					=					"""adapt react readapt apt"""
    _snake_case    :  int					=					"""adapt re@@ a@@ c@@ t re@@ adapt apt""".split()
    _snake_case    :  Tuple					=					tokenizer.tokenize(lowerCAmelCase)
    self.assertListEqual(lowerCAmelCase				,		lowerCAmelCase)

    _snake_case    :  str					=					tokens + [tokenizer.unk_token]

    _snake_case    :  Union[str, Any]					=					[0, 1, 2, 4, 5, 1, 0, 3, 6]
    self.assertListEqual(tokenizer.convert_tokens_to_ids(lowerCAmelCase)				,		lowerCAmelCase)
