



"""simple docstring"""

import gc
import unittest

import numpy as np
import torch

from diffusers import AutoencoderKL, DDIMScheduler, DiTPipeline, DPMSolverMultistepScheduler, TransformeraDModel
from diffusers.utils import is_xformers_available, load_numpy, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu

from ..pipeline_params import (
    CLASS_CONDITIONED_IMAGE_GENERATION_BATCH_PARAMS,
    CLASS_CONDITIONED_IMAGE_GENERATION_PARAMS,
)
from ..test_pipelines_common import PipelineTesterMixin


enable_full_determinism()







class    __lowercase     (					_UpperCAmelCase					,    unittest.TestCase):







						"""simple docstring"""







						_A		:							str							       =		DiTPipeline
						_A		:							List[str]							       =		CLASS_CONDITIONED_IMAGE_GENERATION_PARAMS
						_A		:							Any							       =		PipelineTesterMixin.required_optional_params - {
						    """latents""",
						    """num_images_per_prompt""",
						    """callback""",
						    """callback_steps""",
						}
						_A		:							Dict							       =		CLASS_CONDITIONED_IMAGE_GENERATION_BATCH_PARAMS
						_A		:							Tuple							       =		False







						def 						__UpperCamelCase							(self       ):
											torch.manual_seed(0       )
											snake_case_					:		List[str] 					=					TransformeraDModel(
											    sample_size=16   ,		num_layers=2   ,		patch_size=4   ,		attention_head_dim=8   ,		num_attention_heads=2   ,		in_channels=4   ,		out_channels=8   ,		attention_bias=lowercase__   ,		activation_fn="""gelu-approximate"""   ,		num_embeds_ada_norm=10_00   ,		norm_type="""ada_norm_zero"""   ,		norm_elementwise_affine=lowercase__   ,		)
											snake_case_					:		Optional[int] 					=					AutoencoderKL()
											snake_case_					:		Dict 					=					DDIMScheduler()
											snake_case_					:		int 					=					{"""transformer""": transformer.eval(), """vae""": vae.eval(), """scheduler""": scheduler}
											return components







						def 						__UpperCamelCase							(self   ,		lowercase__   ,		lowercase__=0       ):
											if str(lowercase__       ).startswith("""mps"""       ):
																snake_case_					:		Optional[Any] 					=					torch.manual_seed(lowercase__       )
											else:
																snake_case_					:		Any 					=					torch.Generator(device=lowercase__       ).manual_seed(lowercase__       )
											snake_case_					:		List[Any] 					=					{
											    """class_labels""": [1],
											    """generator""": generator,
											    """num_inference_steps""": 2,
											    """output_type""": """numpy""",
											}
											return inputs







						def 						__UpperCamelCase							(self       ):
											snake_case_					:		Tuple 					=					"""cpu"""

											snake_case_					:		Optional[int] 					=					self.get_dummy_components()
											snake_case_					:		Optional[int] 					=					self.pipeline_class(**lowercase__       )
											pipe.to(lowercase__       )
											pipe.set_progress_bar_config(disable=lowercase__       )

											snake_case_					:		Optional[Any] 					=					self.get_dummy_inputs(lowercase__       )
											snake_case_					:		Union[str, Any] 					=					pipe(**lowercase__       ).images
											snake_case_					:		Dict 					=					image[0, -3:, -3:, -1]

											self.assertEqual(image.shape   ,		(1, 16, 16, 3)       )
											snake_case_					:		int 					=					np.array([0.2946, 0.6601, 0.4329, 0.3296, 0.4144, 0.5319, 0.7273, 0.5013, 0.4457]       )
											snake_case_					:		Any 					=					np.abs(image_slice.flatten() - expected_slice       ).max()
											self.assertLessEqual(lowercase__   ,		1e-3       )







						def 						__UpperCamelCase							(self       ):
											self._test_inference_batch_single_identical(relax_max_difference=lowercase__   ,		expected_max_diff=1e-3       )







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







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







						"""simple docstring"""







						def 						__UpperCamelCase							(self       ):
											super().tearDown()
											gc.collect()
											torch.cuda.empty_cache()







						def 						__UpperCamelCase							(self       ):
											snake_case_					:		str 					=					torch.manual_seed(0       )

											snake_case_					:		Tuple 					=					DiTPipeline.from_pretrained("""facebook/DiT-XL-2-256"""       )
											pipe.to("""cuda"""       )

											snake_case_					:		Union[str, Any] 					=					["""vase""", """umbrella""", """white shark""", """white wolf"""]
											snake_case_					:		Tuple 					=					pipe.get_label_ids(lowercase__       )

											snake_case_					:		Optional[Any] 					=					pipe(lowercase__   ,		generator=lowercase__   ,		num_inference_steps=40   ,		output_type="""np"""       ).images

											for word, image in zip(lowercase__   ,		lowercase__       ):
																snake_case_					:		Any 					=					load_numpy(
																    f'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/dit/{word}.npy'       )
																assert np.abs((expected_image - image).max()       ) < 1e-2







						def 						__UpperCamelCase							(self       ):
											snake_case_					:		Tuple 					=					DiTPipeline.from_pretrained("""facebook/DiT-XL-2-512"""       )
											snake_case_					:		Union[str, Any] 					=					DPMSolverMultistepScheduler.from_config(pipe.scheduler.config       )
											pipe.to("""cuda"""       )

											snake_case_					:		Any 					=					["""vase""", """umbrella"""]
											snake_case_					:		Union[str, Any] 					=					pipe.get_label_ids(lowercase__       )

											snake_case_					:		Tuple 					=					torch.manual_seed(0       )
											snake_case_					:		Union[str, Any] 					=					pipe(lowercase__   ,		generator=lowercase__   ,		num_inference_steps=25   ,		output_type="""np"""       ).images

											for word, image in zip(lowercase__   ,		lowercase__       ):
																snake_case_					:		Optional[int] 					=					load_numpy(
																    """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"""
																    f'/dit/{word}_512.npy'       )

																assert np.abs((expected_image - image).max()       ) < 1e-1









"""simple docstring"""

import warnings

from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding







class    __lowercase     (					_UpperCAmelCase):







						"""simple docstring"""







						_A		:							Union[str, Any]							       =		["""image_processor""", """tokenizer"""]
						_A		:							str							       =		"""ChineseCLIPImageProcessor"""
						_A		:							Tuple							       =		("""BertTokenizer""", """BertTokenizerFast""")







						def __init__(self   ,		lowercase__=None   ,		lowercase__=None   ,		**lowercase__       ):
											snake_case_					:		Any 					=					None
											if "feature_extractor" in kwargs:
																warnings.warn(
																    """The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`"""
																    """ instead."""   ,		lowercase__   ,		)
																snake_case_					:		Optional[Any] 					=					kwargs.pop("""feature_extractor"""       )

											snake_case_					:		str 					=					image_processor if image_processor is not None else feature_extractor
											if image_processor is None:
																raise ValueError("""You need to specify an `image_processor`."""       )
											if tokenizer is None:
																raise ValueError("""You need to specify a `tokenizer`."""       )

											super().__init__(lowercase__   ,		lowercase__       )
											snake_case_					:		Union[str, Any] 					=					self.image_processor







						def __call__(self   ,		lowercase__=None   ,		lowercase__=None   ,		lowercase__=None   ,		**lowercase__       ):

											if text is None and images is None:
																raise ValueError("""You have to specify either text or images. Both cannot be none."""       )

											if text is not None:
																snake_case_					:		Any 					=					self.tokenizer(lowercase__   ,		return_tensors=lowercase__   ,		**lowercase__       )

											if images is not None:
																snake_case_					:		Tuple 					=					self.image_processor(lowercase__   ,		return_tensors=lowercase__   ,		**lowercase__       )

											if text is not None and images is not None:
																snake_case_					:		List[Any] 					=					image_features.pixel_values
																return encoding
											elif text is not None:
																return encoding
											else:
																return BatchEncoding(data=dict(**lowercase__       )   ,		tensor_type=lowercase__       )







						def 						__UpperCamelCase							(self   ,		*lowercase__   ,		**lowercase__       ):
											return self.tokenizer.batch_decode(*lowercase__   ,		**lowercase__       )







						def 						__UpperCamelCase							(self   ,		*lowercase__   ,		**lowercase__       ):
											return self.tokenizer.decode(*lowercase__   ,		**lowercase__       )







						@property
						def 						__UpperCamelCase							(self       ):
											snake_case_					:		Optional[int] 					=					self.tokenizer.model_input_names
											snake_case_					:		Union[str, Any] 					=					self.image_processor.model_input_names
											return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names       )       )







						@property
						def 						__UpperCamelCase							(self       ):
											warnings.warn(
											    """`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead."""   ,		lowercase__   ,		)
											return self.image_processor_class




