




'''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      lowerCAmelCase (			__lowerCAmelCase					, unittest.TestCase):
       __lowercase	:   Dict										=      DiTPipeline
       __lowercase	:   List[str]										=      CLASS_CONDITIONED_IMAGE_GENERATION_PARAMS
       __lowercase	:   Optional[int]										=      PipelineTesterMixin.required_optional_params - {
           '''latents''',
           '''num_images_per_prompt''',
           '''callback''',
           '''callback_steps''',
       }
       __lowercase	:   str										=      CLASS_CONDITIONED_IMAGE_GENERATION_BATCH_PARAMS
       __lowercase	:   Any										=      False


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



            '''simple docstring'''




            torch.manual_seed(0	)
            __snake_case            =	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=__SCREAMING_SNAKE_CASE     ,	activation_fn='''gelu-approximate'''     ,	num_embeds_ada_norm=1000     ,	norm_type='''ada_norm_zero'''     ,	norm_elementwise_affine=__SCREAMING_SNAKE_CASE     ,	)
            __snake_case            =	AutoencoderKL()
            __snake_case            =	DDIMScheduler()
            __snake_case            =	{'''transformer''': transformer.eval(), '''vae''': vae.eval(), '''scheduler''': scheduler}
            return components


       def    lowerCAmelCase   ( self     ,	__SCREAMING_SNAKE_CASE     ,	__SCREAMING_SNAKE_CASE=0	)   ->	List[Any]:



            '''simple docstring'''




            if str(__SCREAMING_SNAKE_CASE	).startswith('''mps'''	):
                 __snake_case            =	torch.manual_seed(__SCREAMING_SNAKE_CASE	)
            else:
                 __snake_case            =	torch.Generator(device=__SCREAMING_SNAKE_CASE	).manual_seed(__SCREAMING_SNAKE_CASE	)
            __snake_case            =	{
                '''class_labels''': [1],
                '''generator''': generator,
                '''num_inference_steps''': 2,
                '''output_type''': '''numpy''',
            }
            return inputs


       def    lowerCAmelCase   ( self	)   ->	Tuple:



            '''simple docstring'''




            __snake_case            =	'''cpu'''

            __snake_case            =	self.get_dummy_components()
            __snake_case            =	self.pipeline_class(**__SCREAMING_SNAKE_CASE	)
            pipe.to(__SCREAMING_SNAKE_CASE	)
            pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE	)

            __snake_case            =	self.get_dummy_inputs(__SCREAMING_SNAKE_CASE	)
            __snake_case            =	pipe(**__SCREAMING_SNAKE_CASE	).images
            __snake_case            =	image[0, -3:, -3:, -1]

            self.assertEqual(image.shape     ,	(1, 16, 16, 3)	)
            __snake_case            =	np.array([0.2_946, 0.6_601, 0.4_329, 0.3_296, 0.4_144, 0.5_319, 0.7_273, 0.5_013, 0.4_457]	)
            __snake_case            =	np.abs(image_slice.flatten() - expected_slice	).max()
            self.assertLessEqual(__SCREAMING_SNAKE_CASE     ,	1E-3	)


       def    lowerCAmelCase   ( self	)   ->	Any:



            '''simple docstring'''




            self._test_inference_batch_single_identical(relax_max_difference=__SCREAMING_SNAKE_CASE     ,	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    lowerCAmelCase   ( self	)   ->	List[str]:



            '''simple docstring'''




            self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1E-3	)





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


       def    lowerCAmelCase   ( self	)   ->	int:



            '''simple docstring'''




            super().tearDown()
            gc.collect()
            torch.cuda.empty_cache()


       def    lowerCAmelCase   ( self	)   ->	Tuple:



            '''simple docstring'''




            __snake_case            =	torch.manual_seed(0	)

            __snake_case            =	DiTPipeline.from_pretrained('''facebook/DiT-XL-2-256'''	)
            pipe.to('''cuda'''	)

            __snake_case            =	['''vase''', '''umbrella''', '''white shark''', '''white wolf''']
            __snake_case            =	pipe.get_label_ids(__SCREAMING_SNAKE_CASE	)

            __snake_case            =	pipe(__SCREAMING_SNAKE_CASE     ,	generator=__SCREAMING_SNAKE_CASE     ,	num_inference_steps=40     ,	output_type='''np'''	).images

            for word, image in zip(__SCREAMING_SNAKE_CASE     ,	__SCREAMING_SNAKE_CASE	):
                 __snake_case            =	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    lowerCAmelCase   ( self	)   ->	Union[str, Any]:



            '''simple docstring'''




            __snake_case            =	DiTPipeline.from_pretrained('''facebook/DiT-XL-2-512'''	)
            __snake_case            =	DPMSolverMultistepScheduler.from_config(pipe.scheduler.config	)
            pipe.to('''cuda'''	)

            __snake_case            =	['''vase''', '''umbrella''']
            __snake_case            =	pipe.get_label_ids(__SCREAMING_SNAKE_CASE	)

            __snake_case            =	torch.manual_seed(0	)
            __snake_case            =	pipe(__SCREAMING_SNAKE_CASE     ,	generator=__SCREAMING_SNAKE_CASE     ,	num_inference_steps=25     ,	output_type='''np'''	).images

            for word, image in zip(__SCREAMING_SNAKE_CASE     ,	__SCREAMING_SNAKE_CASE	):
                 __snake_case            =	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










def       a_ (       SCREAMING_SNAKE_CASE__   : bytes	):
       '''simple docstring'''





       return "".join([hex(SCREAMING_SNAKE_CASE__	)[2:].zfill(2	).upper() for byte in list(SCREAMING_SNAKE_CASE__	)]	)




def       a_ (       SCREAMING_SNAKE_CASE__   : str	):
       '''simple docstring'''





       if (len(SCREAMING_SNAKE_CASE__	) % 2) != 0:
              raise ValueError(
                  'Base16 encoded data is invalid:\nData does not have an even number of hex digits.'	)
       # Check the character set - the standard base16 alphabet
       # is uppercase according to RFC3548 section 6
       if not set(SCREAMING_SNAKE_CASE__	) <= set('0123456789ABCDEF'	):
              raise ValueError(
                  'Base16 encoded data is invalid:\nData is not uppercase hex or it contains invalid characters.'	)
       # For every two hexadecimal digits (= a byte), turn it into an integer.
       # Then, string the result together into bytes, and return it.
       return bytes(int(data[i] + data[i + 1]						,     16	) for i in range(0						,     len(SCREAMING_SNAKE_CASE__	)						,     2	)	)


if __name__ == "__main__":
 import doctest

 doctest.testmod()


