






'''simple docstring'''





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__	( __a):




					def 						A	(   self   :						List[Any]	)  ->				Optional[Any]:
								UpperCAmelCase_	:    str	  =    self.config_class(**self.inputs_dict	)
								self.parent.assertTrue(hasattr(lowerCAmelCase__							,      '''embed_dim'''	)	)
								self.parent.assertTrue(hasattr(lowerCAmelCase__							,      '''num_heads'''	)	)






class       snake_case__	:




					def __init__(   self   :						Tuple							,      _A   :						Optional[Any]							,      _A   :						List[str]=13							,      _A   :						Tuple=64							,      _A   :						Union[str, Any]=3							,      _A   :						Union[str, Any]=[16, 48, 96]							,      _A   :						Optional[Any]=[1, 3, 6]							,      _A   :						Optional[int]=[1, 2, 10]							,      _A   :						List[str]=[7, 3, 3]							,      _A   :						Tuple=[4, 2, 2]							,      _A   :						List[Any]=[2, 1, 1]							,      _A   :						Union[str, Any]=[2, 2, 2]							,      _A   :						Dict=[False, False, True]							,      _A   :						str=[0.0, 0.0, 0.0]							,      _A   :						Any=0.02							,      _A   :						int=1e-12							,      _A   :						List[str]=True							,      _A   :						Tuple=True							,      _A   :						str=2							,      )  ->				Union[str, Any]:
								UpperCAmelCase_	:    str	  =    parent
								UpperCAmelCase_	:    Dict	  =    batch_size
								UpperCAmelCase_	:    Any	  =    image_size
								UpperCAmelCase_	:    Any	  =    patch_sizes
								UpperCAmelCase_	:    Union[str, Any]	  =    patch_stride
								UpperCAmelCase_	:    Dict	  =    patch_padding
								UpperCAmelCase_	:    Union[str, Any]	  =    is_training
								UpperCAmelCase_	:    List[Any]	  =    use_labels
								UpperCAmelCase_	:    Optional[int]	  =    num_labels
								UpperCAmelCase_	:    Tuple	  =    num_channels
								UpperCAmelCase_	:    List[Any]	  =    embed_dim
								UpperCAmelCase_	:    Tuple	  =    num_heads
								UpperCAmelCase_	:    int	  =    stride_kv
								UpperCAmelCase_	:    List[Any]	  =    depth
								UpperCAmelCase_	:    Optional[Any]	  =    cls_token
								UpperCAmelCase_	:    List[str]	  =    attention_drop_rate
								UpperCAmelCase_	:    Union[str, Any]	  =    initializer_range
								UpperCAmelCase_	:    List[Any]	  =    layer_norm_eps




					def 						A	(   self   :						List[Any]	)  ->				List[Any]:
								UpperCAmelCase_	:    str	  =    floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]	)

								UpperCAmelCase_	:    Dict	  =    None
								if self.use_labels:
											# create a random int32 tensor of given shape
											UpperCAmelCase_	:    List[str]	  =    ids_tensor([self.batch_size]							,      self.num_labels	)

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




					def 						A	(   self   :						Tuple	)  ->				List[str]:
								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 						A	(   self   :						List[Any]							,      _A   :						int							,      _A   :						Any							,      _A   :						List[Any]	)  ->				Any:
								UpperCAmelCase_	:    List[Any]	  =    TFCvtModel(config=lowerCAmelCase__	)
								UpperCAmelCase_	:    Optional[int]	  =    model(lowerCAmelCase__							,      training=lowerCAmelCase__	)
								UpperCAmelCase_	:    Dict	  =    (self.image_size, self.image_size)
								UpperCAmelCase_  ,	UpperCAmelCase_	:    str	  =    image_size[0], image_size[1]
								for i in range(len(self.depth	)	):
											UpperCAmelCase_	:    str	  =    floor(((height + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1	)
											UpperCAmelCase_	:    int	  =    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 						A	(   self   :						List[str]							,      _A   :						Tuple							,      _A   :						Tuple							,      _A   :						List[Any]	)  ->				Dict:
								UpperCAmelCase_	:    Union[str, Any]	  =    self.num_labels
								UpperCAmelCase_	:    List[str]	  =    TFCvtForImageClassification(lowerCAmelCase__	)
								UpperCAmelCase_	:    Dict	  =    model(lowerCAmelCase__							,      labels=lowerCAmelCase__							,      training=lowerCAmelCase__	)
								self.parent.assertEqual(result.logits.shape							,      (self.batch_size, self.num_labels)	)





					def 						A	(   self   :						List[str]	)  ->				Any:
								UpperCAmelCase_	:    Union[str, Any]	  =    self.prepare_config_and_inputs()
								UpperCAmelCase_  ,	UpperCAmelCase_  ,	UpperCAmelCase_	:    str	  =    config_and_inputs
								UpperCAmelCase_	:    Optional[int]	  =    {'''pixel_values''': pixel_values}
								return config, inputs_dict






@require_tf
class       snake_case__	( __a			,							__a			,							unittest.TestCase):
					a_								= (TFCvtModel, TFCvtForImageClassification) if is_tf_available() else ()
					a_								= (
					    {'''feature-extraction''': TFCvtModel, '''image-classification''': TFCvtForImageClassification}
					    if is_tf_available()
					    else {}
					)
					a_								= False
					a_								= False
					a_								= False
					a_								= False
					a_								= False




					def 						A	(   self   :						str	)  ->				List[str]:
								UpperCAmelCase_	:    str	  =    TFCvtModelTester(self	)
								UpperCAmelCase_	:    int	  =    TFCvtConfigTester(self							,      config_class=lowerCAmelCase__							,      has_text_modality=lowerCAmelCase__							,      hidden_size=37	)




					def 						A	(   self   :						Tuple	)  ->				Optional[int]:
								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 						A	(   self   :						Any	)  ->				str:
								pass




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




					@unittest.skip(reason='''Cvt does not support input and output embeddings'''	)
					def 						A	(   self   :						List[Any]	)  ->				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.'''							,      )
					def 						A	(   self   :						Dict	)  ->				List[Any]:
								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 						A	(   self   :						List[str]	)  ->				Optional[Any]:
								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 						A	(   self   :						Union[str, Any]	)  ->				Tuple:
								UpperCAmelCase_	:    str	  =    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 						A	(   self   :						Any	)  ->				int:
								UpperCAmelCase_  ,	UpperCAmelCase_	:    Tuple	  =    self.model_tester.prepare_config_and_inputs_for_common()

								for model_class in self.all_model_classes:
											UpperCAmelCase_	:    Dict	  =    model_class(lowerCAmelCase__	)
											UpperCAmelCase_	:    Union[str, Any]	  =    inspect.signature(model.call	)
											# signature.parameters is an OrderedDict => so arg_names order is deterministic
											UpperCAmelCase_	:    Dict	  =    [*signature.parameters.keys()]

											UpperCAmelCase_	:    int	  =    ['''pixel_values''']
											self.assertListEqual(arg_names[:1]							,      lowerCAmelCase__	)




					def 						A	(   self   :						Optional[int]	)  ->				List[str]:
								def check_hidden_states_output(_A   :						Optional[int]							,      _A   :						str							,      _A   :						Any	):
											UpperCAmelCase_	:    Union[str, Any]	  =    model_class(lowerCAmelCase__	)

											UpperCAmelCase_	:    Dict	  =    model(**self._prepare_for_class(lowerCAmelCase__							,      lowerCAmelCase__	)	)
											UpperCAmelCase_	:    List[Any]	  =    outputs.hidden_states

											UpperCAmelCase_	:    str	  =    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,
											    ]							,      )

								UpperCAmelCase_  ,	UpperCAmelCase_	:    Tuple	  =    self.model_tester.prepare_config_and_inputs_for_common()

								for model_class in self.all_model_classes:
											UpperCAmelCase_	:    List[str]	  =    True
											check_hidden_states_output(lowerCAmelCase__							,      lowerCAmelCase__							,      lowerCAmelCase__	)

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

											check_hidden_states_output(lowerCAmelCase__							,      lowerCAmelCase__							,      lowerCAmelCase__	)




					def 						A	(   self   :						Optional[int]	)  ->				Optional[Any]:
								UpperCAmelCase_	:    int	  =    self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_model(*lowerCAmelCase__	)




					def 						A	(   self   :						int	)  ->				Tuple:
								UpperCAmelCase_	:    int	  =    self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_image_classification(*lowerCAmelCase__	)





					@slow
					def 						A	(   self   :						List[Any]	)  ->				int:
								for model_name in TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
											UpperCAmelCase_	:    List[Any]	  =    TFCvtModel.from_pretrained(lowerCAmelCase__	)
											self.assertIsNotNone(lowerCAmelCase__	)






def __UpperCAmelCase					( )  ->					Union[str, Any]:
			UpperCAmelCase_	:    Union[str, Any]	  =    Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''						)
			return image







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




					@cached_property
					def 						A	(   self   :						int	)  ->				Any:
								return AutoImageProcessor.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]	)





					@slow
					def 						A	(   self   :						Optional[int]	)  ->				Optional[int]:
								UpperCAmelCase_	:    List[Any]	  =    TFCvtForImageClassification.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]	)

								UpperCAmelCase_	:    Any	  =    self.default_image_processor
								UpperCAmelCase_	:    str	  =    prepare_img()
								UpperCAmelCase_	:    Optional[Any]	  =    image_processor(images=lowerCAmelCase__							,      return_tensors='''tf'''	)

								# forward pass
								UpperCAmelCase_	:    List[str]	  =    model(**lowerCAmelCase__	)

								# verify the logits
								UpperCAmelCase_	:    List[str]	  =    tf.TensorShape((1, 10_00)	)
								self.assertEqual(outputs.logits.shape							,      lowerCAmelCase__	)

								UpperCAmelCase_	:    Optional[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	)	)




"""simple docstring"""





import gc
import random
import unittest

import numpy as np
import torch
from PIL import Image

from diffusers import (
    DDIMScheduler,
    KandinskyVaaImgaImgPipeline,
    KandinskyVaaPriorPipeline,
    UNetaDConditionModel,
    VQModel,
)
from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu

from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference


enable_full_determinism()
class 						SCREAMING_SNAKE_CASE_ (						__a     ,				unittest.TestCase ):




		"""simple docstring"""





		__lowercase							:  Optional[Any]						   =		KandinskyVaaImgaImgPipeline
		__lowercase							:  str						   =		['''image_embeds''', '''negative_image_embeds''', '''image''']
		__lowercase							:  Dict						   =		[
		    '''image_embeds''',
		    '''negative_image_embeds''',
		    '''image''',
		]
		__lowercase							:  Tuple						   =		[
		    '''generator''',
		    '''height''',
		    '''width''',
		    '''strength''',
		    '''guidance_scale''',
		    '''num_inference_steps''',
		    '''return_dict''',
		    '''guidance_scale''',
		    '''num_images_per_prompt''',
		    '''output_type''',
		    '''return_dict''',
		]
		__lowercase							:  Tuple						   =		False




		@property
		def 	snake_case_     (     self):
				return 3_2




		@property
		def 	snake_case_     (     self):
				return 3_2




		@property
		def 	snake_case_     (     self):
				return self.time_input_dim




		@property
		def 	snake_case_     (     self):
				return self.time_input_dim * 4




		@property
		def 	snake_case_     (     self):
				return 1_0_0




		@property
		def 	snake_case_     (     self):
				torch.manual_seed(0)

				__SCREAMING_SNAKE_CASE            = {
				    """in_channels""": 4,
				    # Out channels is double in channels because predicts mean and variance
				    """out_channels""": 8,
				    """addition_embed_type""": """image""",
				    """down_block_types""": ("""ResnetDownsampleBlock2D""", """SimpleCrossAttnDownBlock2D"""),
				    """up_block_types""": ("""SimpleCrossAttnUpBlock2D""", """ResnetUpsampleBlock2D"""),
				    """mid_block_type""": """UNetMidBlock2DSimpleCrossAttn""",
				    """block_out_channels""": (self.block_out_channels_a, self.block_out_channels_a * 2),
				    """layers_per_block""": 1,
				    """encoder_hid_dim""": self.text_embedder_hidden_size,
				    """encoder_hid_dim_type""": """image_proj""",
				    """cross_attention_dim""": self.cross_attention_dim,
				    """attention_head_dim""": 4,
				    """resnet_time_scale_shift""": """scale_shift""",
				    """class_embed_type""": None,
				}

				__SCREAMING_SNAKE_CASE            = UNetaDConditionModel(**lowerCAmelCase__)
				return model




		@property
		def 	snake_case_     (     self):
				return {
				    "block_out_channels": [3_2, 6_4],
				    "down_block_types": ["DownEncoderBlock2D", "AttnDownEncoderBlock2D"],
				    "in_channels": 3,
				    "latent_channels": 4,
				    "layers_per_block": 1,
				    "norm_num_groups": 8,
				    "norm_type": "spatial",
				    "num_vq_embeddings": 1_2,
				    "out_channels": 3,
				    "up_block_types": [
				        "AttnUpDecoderBlock2D",
				        "UpDecoderBlock2D",
				    ],
				    "vq_embed_dim": 4,
				}




		@property
		def 	snake_case_     (     self):
				torch.manual_seed(0)
				__SCREAMING_SNAKE_CASE            = VQModel(**self.dummy_movq_kwargs)
				return model




		def 	snake_case_     (     self):
				__SCREAMING_SNAKE_CASE            = self.dummy_unet
				__SCREAMING_SNAKE_CASE            = self.dummy_movq

				__SCREAMING_SNAKE_CASE            = {
				    """num_train_timesteps""": 1_0_0_0,
				    """beta_schedule""": """linear""",
				    """beta_start""": 0.0_00_85,
				    """beta_end""": 0.0_12,
				    """clip_sample""": False,
				    """set_alpha_to_one""": False,
				    """steps_offset""": 0,
				    """prediction_type""": """epsilon""",
				    """thresholding""": False,
				}

				__SCREAMING_SNAKE_CASE            = DDIMScheduler(**lowerCAmelCase__)

				__SCREAMING_SNAKE_CASE            = {
				    """unet""": unet,
				    """scheduler""": scheduler,
				    """movq""": movq,
				}

				return components




		def 	snake_case_     (     self							,  lowerCAmelCase__							,  lowerCAmelCase__=0):
				__SCREAMING_SNAKE_CASE            = floats_tensor((1, self.text_embedder_hidden_size)							,  rng=random.Random(lowerCAmelCase__)).to(lowerCAmelCase__)
				__SCREAMING_SNAKE_CASE            = floats_tensor((1, self.text_embedder_hidden_size)							,  rng=random.Random(seed + 1)).to(
				    lowerCAmelCase__)
				# create init_image
				__SCREAMING_SNAKE_CASE            = floats_tensor((1, 3, 6_4, 6_4)							,  rng=random.Random(lowerCAmelCase__)).to(lowerCAmelCase__)
				__SCREAMING_SNAKE_CASE            = image.cpu().permute(0							,  2							,  3							,  1)[0]
				__SCREAMING_SNAKE_CASE            = Image.fromarray(np.uinta(lowerCAmelCase__)).convert("""RGB""").resize((2_5_6, 2_5_6))

				if str(lowerCAmelCase__).startswith("""mps"""):
						__SCREAMING_SNAKE_CASE            = torch.manual_seed(lowerCAmelCase__)
				else:
						__SCREAMING_SNAKE_CASE            = torch.Generator(device=lowerCAmelCase__).manual_seed(lowerCAmelCase__)
				__SCREAMING_SNAKE_CASE            = {
				    """image""": init_image,
				    """image_embeds""": image_embeds,
				    """negative_image_embeds""": negative_image_embeds,
				    """generator""": generator,
				    """height""": 6_4,
				    """width""": 6_4,
				    """num_inference_steps""": 1_0,
				    """guidance_scale""": 7.0,
				    """strength""": 0.2,
				    """output_type""": """np""",
				}
				return inputs




		def 	snake_case_     (     self):
				__SCREAMING_SNAKE_CASE            = """cpu"""

				__SCREAMING_SNAKE_CASE            = self.get_dummy_components()

				__SCREAMING_SNAKE_CASE            = self.pipeline_class(**lowerCAmelCase__)
				__SCREAMING_SNAKE_CASE            = pipe.to(lowerCAmelCase__)

				pipe.set_progress_bar_config(disable=lowerCAmelCase__)

				__SCREAMING_SNAKE_CASE            = pipe(**self.get_dummy_inputs(lowerCAmelCase__))
				__SCREAMING_SNAKE_CASE            = output.images

				__SCREAMING_SNAKE_CASE            = pipe(
				    **self.get_dummy_inputs(lowerCAmelCase__)							,  return_dict=lowerCAmelCase__							,  )[0]

				__SCREAMING_SNAKE_CASE            = image[0, -3:, -3:, -1]
				__SCREAMING_SNAKE_CASE            = image_from_tuple[0, -3:, -3:, -1]

				assert image.shape == (1, 6_4, 6_4, 3)

				__SCREAMING_SNAKE_CASE            = np.array(
				    [0.6_19_97_78, 0.63_98_44_06, 0.46_14_57_85, 0.62_94_49_84, 0.5_62_22_15, 0.47_30_61_32, 0.47_44_14_56, 0.4_60_76_06, 0.48_71_92_63])
				assert (
				    np.abs(image_slice.flatten() - expected_slice).max() < 1E-2
				), f" expected_slice {expected_slice}, but got {image_slice.flatten()}"
				assert (
				    np.abs(image_from_tuple_slice.flatten() - expected_slice).max() < 1E-2
				), f" expected_slice {expected_slice}, but got {image_from_tuple_slice.flatten()}"



@slow
@require_torch_gpu
class 						SCREAMING_SNAKE_CASE_ (						unittest.TestCase ):




		"""simple docstring"""





		def 	snake_case_     (     self):
				# clean up the VRAM after each test
				super().tearDown()
				gc.collect()
				torch.cuda.empty_cache()




		def 	snake_case_     (     self):
				__SCREAMING_SNAKE_CASE            = load_numpy(
				    """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"""
				    """/kandinskyv22/kandinskyv22_img2img_frog.npy""")

				__SCREAMING_SNAKE_CASE            = load_image(
				    """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/kandinsky/cat.png""")
				__SCREAMING_SNAKE_CASE            = """A red cartoon frog, 4k"""

				__SCREAMING_SNAKE_CASE            = KandinskyVaaPriorPipeline.from_pretrained(
				    """kandinsky-community/kandinsky-2-2-prior"""							,  torch_dtype=torch.floataa)
				pipe_prior.to(lowerCAmelCase__)

				__SCREAMING_SNAKE_CASE            = KandinskyVaaImgaImgPipeline.from_pretrained(
				    """kandinsky-community/kandinsky-2-2-decoder"""							,  torch_dtype=torch.floataa)
				__SCREAMING_SNAKE_CASE            = pipeline.to(lowerCAmelCase__)

				pipeline.set_progress_bar_config(disable=lowerCAmelCase__)

				__SCREAMING_SNAKE_CASE            = torch.Generator(device="""cpu""").manual_seed(0)
				__SCREAMING_SNAKE_CASE       ,__SCREAMING_SNAKE_CASE            = pipe_prior(
				    lowerCAmelCase__							,  generator=lowerCAmelCase__							,  num_inference_steps=5							,  negative_prompt=""""""							,  ).to_tuple()

				__SCREAMING_SNAKE_CASE            = pipeline(
				    image=lowerCAmelCase__							,  image_embeds=lowerCAmelCase__							,  negative_image_embeds=lowerCAmelCase__							,  generator=lowerCAmelCase__							,  num_inference_steps=1_0_0							,  height=7_6_8							,  width=7_6_8							,  strength=0.2							,  output_type="""np"""							,  )

				__SCREAMING_SNAKE_CASE            = output.images[0]

				assert image.shape == (7_6_8, 7_6_8, 3)

				assert_mean_pixel_difference(lowerCAmelCase__							,  lowerCAmelCase__)




