

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 					_a		(__magic_name__       ):


					'''simple docstring'''






					def 						__A    (				self    ):
						A__							:					Any       =	self.config_class(**self.inputs_dict    )
						self.parent.assertTrue(hasattr(A__					, """embed_dim"""    )    )
						self.parent.assertTrue(hasattr(A__					, """num_heads"""    )    )



class 					_a		:


					'''simple docstring'''






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






					def 						__A    (				self    ):
						A__							:					Tuple       =	floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]    )

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

						A__							:					Tuple       =	self.get_config()
						return config, pixel_values, labels






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






					def 						__A    (				self    ):
						A__							:					Union[str, Any]       =	self.prepare_config_and_inputs()
						A__     ,     A__     ,     A__							:					Optional[int]       =	config_and_inputs
						A__							:					Union[str, Any]       =	{"""pixel_values""": pixel_values}
						return config, inputs_dict



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


					'''simple docstring'''






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






					def 						__A    (				self    ):
						A__							:					List[str]       =	TFCvtModelTester(self    )
						A__							:					Any       =	TFCvtConfigTester(self					, config_class=A__					, has_text_modality=A__					, hidden_size=37    )






					def 						__A    (				self    ):
						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    ):
						pass






					@unittest.skip(reason="""Cvt does not use inputs_embeds"""    )
					def 						__A    (				self    ):
						pass






					@unittest.skip(reason="""Cvt does not support input and output embeddings"""    )
					def 						__A    (				self    ):
						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    ):
						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    ):
						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    ):
						A__							:					Any       =	tf.keras.mixed_precision.Policy("""mixed_float16"""    )
						tf.keras.mixed_precision.set_global_policy(A__    )
						super().test_keras_fit()
						tf.keras.mixed_precision.set_global_policy("""float32"""    )






					def 						__A    (				self    ):
						A__     ,     A__							:					str       =	self.model_tester.prepare_config_and_inputs_for_common()

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

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






					def 						__A    (				self    ):
						def check_hidden_states_output(A__					, A__					, A__    ):
							A__							:					Optional[int]       =	model_class(A__    )

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

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

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

						A__     ,     A__							:					Optional[Any]       =	self.model_tester.prepare_config_and_inputs_for_common()

						for model_class in self.all_model_classes:
							A__							:					Optional[Any]       =	True
							check_hidden_states_output(A__					, A__					, A__    )

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

							check_hidden_states_output(A__					, A__					, A__    )






					def 						__A    (				self    ):
						A__							:					Tuple       =	self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_model(*A__    )






					def 						__A    (				self    ):
						A__							:					Optional[Any]       =	self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_for_image_classification(*A__    )






					@slow
					def 						__A    (				self    ):
						for model_name in TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
							A__							:					List[Any]       =	TFCvtModel.from_pretrained(A__    )
							self.assertIsNotNone(A__    )



def 		UpperCamelCase      ()  ->   Union[str, Any]:
	A__							:					Dict       =	Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""      )
	return image



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


					'''simple docstring'''






					@cached_property
					def 						__A    (				self    ):
						return AutoImageProcessor.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]    )






					@slow
					def 						__A    (				self    ):
						A__							:					Any       =	TFCvtForImageClassification.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]    )

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

						# forward pass
						A__							:					Tuple       =	model(**A__    )

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

						A__							:					Any       =	tf.constant([0.9_2_8_5, 0.9_0_1_5, -0.3_1_5_0]    )
						self.assertTrue(np.allclose(outputs.logits[0, :3].numpy()					, A__					, atol=1e-4    )    )






import unittest

import numpy as np
import torch
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer

from diffusers import (
    AutoencoderKL,
    DDIMScheduler,
    DPMSolverMultistepScheduler,
    TextToVideoSDPipeline,
    UNetaDConditionModel,
)
from diffusers.utils import is_xformers_available, load_numpy, skip_mps, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism

from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_PARAMS
from ..test_pipelines_common import PipelineTesterMixin


enable_full_determinism()



@skip_mps
class 					_a		(__magic_name__	,     unittest.TestCase       ):


					'''simple docstring'''






					UpperCAmelCase__:     Any													= TextToVideoSDPipeline
					UpperCAmelCase__:     Any													= TEXT_TO_IMAGE_PARAMS
					UpperCAmelCase__:     Optional[Any]													= TEXT_TO_IMAGE_BATCH_PARAMS
					# No `output_type`.
					UpperCAmelCase__:     Optional[int]													= frozenset(
					    [
					        '''num_inference_steps''',
					        '''generator''',
					        '''latents''',
					        '''return_dict''',
					        '''callback''',
					        '''callback_steps''',
					    ]       )






					def 						__A    (				self    ):
						torch.manual_seed(0    )
						A__							:					Optional[int]       =	UNetaDConditionModel(
						    block_out_channels=(32, 64, 64, 64)					, layers_per_block=2					, sample_size=32					, in_channels=4					, out_channels=4					, down_block_types=("""CrossAttnDownBlock3D""", """CrossAttnDownBlock3D""", """CrossAttnDownBlock3D""", """DownBlock3D""")					, up_block_types=("""UpBlock3D""", """CrossAttnUpBlock3D""", """CrossAttnUpBlock3D""", """CrossAttnUpBlock3D""")					, cross_attention_dim=32					, attention_head_dim=4					, )
						A__							:					Optional[int]       =	DDIMScheduler(
						    beta_start=0.0_0_0_8_5					, beta_end=0.0_1_2					, beta_schedule="""scaled_linear"""					, clip_sample=A__					, set_alpha_to_one=A__					, )
						torch.manual_seed(0    )
						A__							:					Union[str, Any]       =	AutoencoderKL(
						    block_out_channels=[32, 64]					, in_channels=3					, out_channels=3					, down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""]					, up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""]					, latent_channels=4					, sample_size=128					, )
						torch.manual_seed(0    )
						A__							:					Union[str, Any]       =	CLIPTextConfig(
						    bos_token_id=0					, eos_token_id=2					, hidden_size=32					, intermediate_size=37					, layer_norm_eps=1e-05					, num_attention_heads=4					, num_hidden_layers=5					, pad_token_id=1					, vocab_size=1000					, hidden_act="""gelu"""					, projection_dim=512					, )
						A__							:					Union[str, Any]       =	CLIPTextModel(A__    )
						A__							:					Tuple       =	CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip"""    )

						A__							:					Dict       =	{
						    """unet""": unet,
						    """scheduler""": scheduler,
						    """vae""": vae,
						    """text_encoder""": text_encoder,
						    """tokenizer""": tokenizer,
						}
						return components






					def 						__A    (				self					, A__					, A__=0    ):
						if str(A__    ).startswith("""mps"""    ):
							A__							:					Tuple       =	torch.manual_seed(A__    )
						else:
							A__							:					List[str]       =	torch.Generator(device=A__    ).manual_seed(A__    )
						A__							:					List[str]       =	{
						    """prompt""": """A painting of a squirrel eating a burger""",
						    """generator""": generator,
						    """num_inference_steps""": 2,
						    """guidance_scale""": 6.0,
						    """output_type""": """pt""",
						}
						return inputs






					def 						__A    (				self    ):
						A__							:					List[str]       =	"""cpu"""  # ensure determinism for the device-dependent torch.Generator
						A__							:					Union[str, Any]       =	self.get_dummy_components()
						A__							:					Union[str, Any]       =	TextToVideoSDPipeline(**A__    )
						A__							:					int       =	sd_pipe.to(A__    )
						sd_pipe.set_progress_bar_config(disable=A__    )

						A__							:					int       =	self.get_dummy_inputs(A__    )
						A__							:					int       =	"""np"""
						A__							:					Any       =	sd_pipe(**A__    ).frames
						A__							:					Dict       =	frames[0][-3:, -3:, -1]

						assert frames[0].shape == (64, 64, 3)
						A__							:					Optional[Any]       =	np.array([1_5_8.0, 1_6_0.0, 1_5_3.0, 1_2_5.0, 1_0_0.0, 1_2_1.0, 1_1_1.0, 9_3.0, 1_1_3.0]    )

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






					def 						__A    (				self    ):
						self._test_attention_slicing_forward_pass(test_mean_pixel_difference=A__					, expected_max_diff=3e-3    )






					@unittest.skipIf(
					    torch_device != """cuda""" or not is_xformers_available()					, reason="""XFormers attention is only available with CUDA and `xformers` installed"""					, )
					def 						__A    (				self    ):
						self._test_xformers_attention_forwardGenerator_pass(test_mean_pixel_difference=A__					, expected_max_diff=1e-2    )






					@unittest.skip(reason="""Batching needs to be properly figured out first for this pipeline."""    )
					def 						__A    (				self    ):
						pass






					@unittest.skip(reason="""Batching needs to be properly figured out first for this pipeline."""    )
					def 						__A    (				self    ):
						pass






					@unittest.skip(reason="""`num_images_per_prompt` argument is not supported for this pipeline."""    )
					def 						__A    (				self    ):
						pass






					def 						__A    (				self    ):
						return super().test_progress_bar()



@slow
@skip_mps
class 					_a		(unittest.TestCase       ):


					'''simple docstring'''






					def 						__A    (				self    ):
						A__							:					Union[str, Any]       =	load_numpy(
						    """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/text_to_video/video.npy"""    )

						A__							:					Tuple       =	TextToVideoSDPipeline.from_pretrained("""damo-vilab/text-to-video-ms-1.7b"""    )
						A__							:					Any       =	DPMSolverMultistepScheduler.from_config(pipe.scheduler.config    )
						A__							:					int       =	pipe.to("""cuda"""    )

						A__							:					Optional[Any]       =	"""Spiderman is surfing"""
						A__							:					List[str]       =	torch.Generator(device="""cpu"""    ).manual_seed(0    )

						A__							:					Optional[Any]       =	pipe(A__					, generator=A__					, num_inference_steps=25					, output_type="""pt"""    ).frames
						A__							:					Dict       =	video_frames.cpu().numpy()

						assert np.abs(expected_video - video    ).mean() < 5e-2






					def 						__A    (				self    ):
						A__							:					List[Any]       =	load_numpy(
						    """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/text_to_video/video_2step.npy"""    )

						A__							:					Optional[int]       =	TextToVideoSDPipeline.from_pretrained("""damo-vilab/text-to-video-ms-1.7b"""    )
						A__							:					List[str]       =	pipe.to("""cuda"""    )

						A__							:					Dict       =	"""Spiderman is surfing"""
						A__							:					Union[str, Any]       =	torch.Generator(device="""cpu"""    ).manual_seed(0    )

						A__							:					Optional[int]       =	pipe(A__					, generator=A__					, num_inference_steps=2					, output_type="""pt"""    ).frames
						A__							:					Optional[int]       =	video_frames.cpu().numpy()

						assert np.abs(expected_video - video    ).mean() < 5e-2



