





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 					lowercase__ (			__lowerCamelCase       ):

   '''simple docstring'''


   def    UpperCamelCase__						(					self							)				->   Dict:






       """simple docstring"""
       UpperCamelCase__							:       Tuple      =   self.config_class(**self.inputs_dict							)
       self.parent.assertTrue(hasattr(__magic_name__,	'''embed_dim'''							)							)
       self.parent.assertTrue(hasattr(__magic_name__,	'''num_heads'''							)							)






class 					lowercase__ :

   '''simple docstring'''


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






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




   def    UpperCamelCase__						(					self							)				->   str:






       """simple docstring"""
       UpperCamelCase__							:       str      =   floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]							)

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

       UpperCamelCase__							:       Optional[Any]      =   self.get_config()
       return config, pixel_values, labels




   def    UpperCamelCase__						(					self							)				->   Dict:






       """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,	__magic_name__,	__magic_name__,	__magic_name__							)				->   Optional[Any]:






       """simple docstring"""
       UpperCamelCase__							:       Dict      =   TFCvtModel(config=__magic_name__							)
       UpperCamelCase__							:       int      =   model(__magic_name__,	training=__magic_name__							)
       UpperCamelCase__							:       Tuple      =   (self.image_size, self.image_size)
       UpperCamelCase__     ,UpperCamelCase__							:       Optional[Any]      =   image_size[0], image_size[1]
       for i in range(len(self.depth							)							):
           UpperCamelCase__							:       Any      =   floor(((height + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1							)
           UpperCamelCase__							:       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,	__magic_name__,	__magic_name__,	__magic_name__							)				->   Optional[Any]:






       """simple docstring"""
       UpperCamelCase__							:       List[Any]      =   self.num_labels
       UpperCamelCase__							:       Dict      =   TFCvtForImageClassification(__magic_name__							)
       UpperCamelCase__							:       int      =   model(__magic_name__,	labels=__magic_name__,	training=__magic_name__							)
       self.parent.assertEqual(result.logits.shape,	(self.batch_size, self.num_labels)							)




   def    UpperCamelCase__						(					self							)				->   List[Any]:






       """simple docstring"""
       UpperCamelCase__							:       Union[str, Any]      =   self.prepare_config_and_inputs()
       UpperCamelCase__     ,UpperCamelCase__     ,UpperCamelCase__							:       Dict      =   config_and_inputs
       UpperCamelCase__							:       Optional[Any]      =   {'''pixel_values''': pixel_values}
       return config, inputs_dict






@require_tf
class 					lowercase__ (			__lowerCamelCase    ,       __lowerCamelCase    ,       unittest.TestCase       ):

   '''simple docstring'''


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




   def    UpperCamelCase__						(					self							)				->   int:






       """simple docstring"""
       UpperCamelCase__							:       Optional[Any]      =   TFCvtModelTester(self							)
       UpperCamelCase__							:       int      =   TFCvtConfigTester(self,	config_class=__magic_name__,	has_text_modality=__magic_name__,	hidden_size=37							)




   def    UpperCamelCase__						(					self							)				->   Any:






       """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							)				->   int:






       """simple docstring"""
       pass




   @unittest.skip(reason='''Cvt does not use inputs_embeds'''							)
   def    UpperCamelCase__						(					self							)				->   str:






       """simple docstring"""
       pass




   @unittest.skip(reason='''Cvt does not support input and output embeddings'''							)
   def    UpperCamelCase__						(					self							)				->   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.''',	)
   def    UpperCamelCase__						(					self							)				->   Any:






       """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							)				->   Optional[Any]:






       """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							)				->   List[str]:






       """simple docstring"""
       UpperCamelCase__							:       List[str]      =   tf.keras.mixed_precision.Policy('''mixed_float16'''							)
       tf.keras.mixed_precision.set_global_policy(__magic_name__							)
       super().test_keras_fit()
       tf.keras.mixed_precision.set_global_policy('''float32'''							)




   def    UpperCamelCase__						(					self							)				->   int:






       """simple docstring"""
       UpperCamelCase__     ,UpperCamelCase__							:       str      =   self.model_tester.prepare_config_and_inputs_for_common()

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

           UpperCamelCase__							:       str      =   ['''pixel_values''']
           self.assertListEqual(arg_names[:1],	__magic_name__							)




   def    UpperCamelCase__						(					self							)				->   str:






       """simple docstring"""
       def check_hidden_states_output(__magic_name__,	__magic_name__,	__magic_name__							):
           UpperCamelCase__							:       Union[str, Any]      =   model_class(__magic_name__							)

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

           UpperCamelCase__							:       Any      =   len(self.model_tester.depth							)
           self.assertEqual(len(__magic_name__							),	__magic_name__							)

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

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

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

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

           check_hidden_states_output(__magic_name__,	__magic_name__,	__magic_name__							)




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






       """simple docstring"""
       UpperCamelCase__							:       Tuple      =   self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*__magic_name__							)




   def    UpperCamelCase__						(					self							)				->   Dict:






       """simple docstring"""
       UpperCamelCase__							:       Tuple      =   self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_image_classification(*__magic_name__							)




   @slow
   def    UpperCamelCase__						(					self							)				->   str:






       """simple docstring"""
       for model_name in TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
           UpperCamelCase__							:       Tuple      =   TFCvtModel.from_pretrained(__magic_name__							)
           self.assertIsNotNone(__magic_name__							)




def 	lowerCAmelCase_					(						)   ->			Any:
    UpperCamelCase__							:       str      =   Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''   )
    return image






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

   '''simple docstring'''


   @cached_property
   def    UpperCamelCase__						(					self							)				->   Any:






       """simple docstring"""
       return AutoImageProcessor.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]							)




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






       """simple docstring"""
       UpperCamelCase__							:       str      =   TFCvtForImageClassification.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]							)

       UpperCamelCase__							:       int      =   self.default_image_processor
       UpperCamelCase__							:       Union[str, Any]      =   prepare_img()
       UpperCamelCase__							:       Optional[int]      =   image_processor(images=__magic_name__,	return_tensors='''tf'''							)

       # forward pass
       UpperCamelCase__							:       Any      =   model(**__magic_name__							)

       # verify the logits
       UpperCamelCase__							:       Any      =   tf.TensorShape((1, 1000)							)
       self.assertEqual(outputs.logits.shape,	__magic_name__							)

       UpperCamelCase__							:       Dict      =   tf.constant([0.9285, 0.9015, -0.3150]							)
       self.assertTrue(np.allclose(outputs.logits[0, :3].numpy(),	__magic_name__,	atol=1E-4							)							)








import gc
import tempfile
import unittest

import numpy as np
import torch

from diffusers import VersatileDiffusionTextToImagePipeline
from diffusers.utils.testing_utils import nightly, require_torch_gpu, torch_device


UpperCAmelCase_  							=				False






class 					lowercase__ (			unittest.TestCase       ):

   '''simple docstring'''


   pass






@nightly
@require_torch_gpu
class 					lowercase__ (			unittest.TestCase       ):

   '''simple docstring'''


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






       """simple docstring"""
       # clean up the VRAM after each test
       super().tearDown()
       gc.collect()
       torch.cuda.empty_cache()




   def    UpperCamelCase__						(					self							)				->   List[Any]:






       """simple docstring"""
       UpperCamelCase__							:       Dict      =   VersatileDiffusionTextToImagePipeline.from_pretrained('''shi-labs/versatile-diffusion'''							)
       # remove text_unet
       pipe.remove_unused_weights()
       pipe.to(__magic_name__							)
       pipe.set_progress_bar_config(disable=__magic_name__							)

       UpperCamelCase__							:       int      =   '''A painting of a squirrel eating a burger '''
       UpperCamelCase__							:       str      =   torch.manual_seed(0							)
       UpperCamelCase__							:       int      =   pipe(
           prompt=__magic_name__,	generator=__magic_name__,	guidance_scale=7.5,	num_inference_steps=2,	output_type='''numpy'''							).images

       with tempfile.TemporaryDirectory() as tmpdirname:
           pipe.save_pretrained(__magic_name__							)
           UpperCamelCase__							:       Union[str, Any]      =   VersatileDiffusionTextToImagePipeline.from_pretrained(__magic_name__							)
       pipe.to(__magic_name__							)
       pipe.set_progress_bar_config(disable=__magic_name__							)

       UpperCamelCase__							:       Optional[Any]      =   generator.manual_seed(0							)
       UpperCamelCase__							:       str      =   pipe(
           prompt=__magic_name__,	generator=__magic_name__,	guidance_scale=7.5,	num_inference_steps=2,	output_type='''numpy'''							).images

       assert np.abs(image - new_image							).sum() < 1E-5, "Models don't have the same forward pass"




   def    UpperCamelCase__						(					self							)				->   Any:






       """simple docstring"""
       UpperCamelCase__							:       str      =   VersatileDiffusionTextToImagePipeline.from_pretrained(
           '''shi-labs/versatile-diffusion''',	torch_dtype=torch.floataa							)
       pipe.to(__magic_name__							)
       pipe.set_progress_bar_config(disable=__magic_name__							)

       UpperCamelCase__							:       Optional[int]      =   '''A painting of a squirrel eating a burger '''
       UpperCamelCase__							:       str      =   torch.manual_seed(0							)
       UpperCamelCase__							:       Optional[int]      =   pipe(
           prompt=__magic_name__,	generator=__magic_name__,	guidance_scale=7.5,	num_inference_steps=50,	output_type='''numpy'''							).images

       UpperCamelCase__							:       int      =   image[0, 253:256, 253:256, -1]

       assert image.shape == (1, 512, 512, 3)
       UpperCamelCase__							:       int      =   np.array([0.3367, 0.3169, 0.2656, 0.3870, 0.4790, 0.3796, 0.4009, 0.4878, 0.4778]							)

       assert np.abs(image_slice.flatten() - expected_slice							).max() < 1E-2

