
import gc
import unittest

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

from diffusers import AutoencoderKL, DDIMScheduler, LDMTextToImagePipeline, UNetaDConditionModel
from diffusers.utils.testing_utils import (
    enable_full_determinism,
    load_numpy,
    nightly,
    require_torch_gpu,
    slow,
    torch_device,
)

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


enable_full_determinism()







class 					lowerCamelCase		(  A_							,			unittest.TestCase  ):
     UpperCAmelCase__    :							List[Any]									=		LDMTextToImagePipeline
     UpperCAmelCase__    :							Any									=		TEXT_TO_IMAGE_PARAMS - {
         "negative_prompt",
         "negative_prompt_embeds",
         "cross_attention_kwargs",
         "prompt_embeds",
     }
     UpperCAmelCase__    :							Tuple									=		PipelineTesterMixin.required_optional_params - {
         "num_images_per_prompt",
         "callback",
         "callback_steps",
     }
     UpperCAmelCase__    :							Any									=		TEXT_TO_IMAGE_BATCH_PARAMS
     UpperCAmelCase__    :							Union[str, Any]									=		False





     def 		UpperCAmelCase(self				:   Dict       )						->						Tuple:
         torch.manual_seed(0       )
         snake_case								= UNetaDConditionModel(
             block_out_channels=(3_2, 6_4)    ,   layers_per_block=2    ,   sample_size=3_2    ,   in_channels=4    ,   out_channels=4    ,   down_block_types=("DownBlock2D", "CrossAttnDownBlock2D")    ,   up_block_types=("CrossAttnUpBlock2D", "UpBlock2D")    ,   cross_attention_dim=3_2    ,   )
         snake_case								= DDIMScheduler(
             beta_start=0.0_00_85    ,   beta_end=0.0_12    ,   beta_schedule="scaled_linear"    ,   clip_sample=_A    ,   set_alpha_to_one=_A    ,   )
         torch.manual_seed(0       )
         snake_case								= AutoencoderKL(
             block_out_channels=(3_2, 6_4)    ,   in_channels=3    ,   out_channels=3    ,   down_block_types=("DownEncoderBlock2D", "DownEncoderBlock2D")    ,   up_block_types=("UpDecoderBlock2D", "UpDecoderBlock2D")    ,   latent_channels=4    ,   )
         torch.manual_seed(0       )
         snake_case								= CLIPTextConfig(
             bos_token_id=0    ,   eos_token_id=2    ,   hidden_size=3_2    ,   intermediate_size=3_7    ,   layer_norm_eps=1E-05    ,   num_attention_heads=4    ,   num_hidden_layers=5    ,   pad_token_id=1    ,   vocab_size=1_0_0_0    ,   )
         snake_case								= CLIPTextModel(_A       )
         snake_case								= CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip"       )

         snake_case								= {
             "unet": unet,
             "scheduler": scheduler,
             "vqvae": vae,
             "bert": text_encoder,
             "tokenizer": tokenizer,
         }
         return components





     def 		UpperCAmelCase(self				:   Optional[Any]    ,   _A				:   List[str]    ,   _A				:   Dict=0       )						->						Optional[Any]:
         if str(_A       ).startswith("mps"       ):
             snake_case								= torch.manual_seed(_A       )
         else:
             snake_case								= torch.Generator(device=_A       ).manual_seed(_A       )
         snake_case								= {
             "prompt": "A painting of a squirrel eating a burger",
             "generator": generator,
             "num_inference_steps": 2,
             "guidance_scale": 6.0,
             "output_type": "numpy",
         }
         return inputs





     def 		UpperCAmelCase(self				:   Optional[int]       )						->						str:
         snake_case								= "cpu"  # ensure determinism for the device-dependent torch.Generator

         snake_case								= self.get_dummy_components()
         snake_case								= LDMTextToImagePipeline(**_A       )
         pipe.to(_A       )
         pipe.set_progress_bar_config(disable=_A       )

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

         assert image.shape == (1, 1_6, 1_6, 3)
         snake_case								= np.array([0.61_01, 0.61_56, 0.56_22, 0.48_95, 0.66_61, 0.38_04, 0.57_48, 0.61_36, 0.50_14]       )

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







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





     def 		UpperCAmelCase(self				:   Dict       )						->						Any:
         super().tearDown()
         gc.collect()
         torch.cuda.empty_cache()





     def 		UpperCAmelCase(self				:   int    ,   _A				:   Optional[Any]    ,   _A				:   Union[str, Any]=torch.floataa    ,   _A				:   str=0       )						->						Optional[Any]:
         snake_case								= torch.manual_seed(_A       )
         snake_case								= np.random.RandomState(_A       ).standard_normal((1, 4, 3_2, 3_2)       )
         snake_case								= torch.from_numpy(_A       ).to(device=_A    ,   dtype=_A       )
         snake_case								= {
             "prompt": "A painting of a squirrel eating a burger",
             "latents": latents,
             "generator": generator,
             "num_inference_steps": 3,
             "guidance_scale": 6.0,
             "output_type": "numpy",
         }
         return inputs





     def 		UpperCAmelCase(self				:   int       )						->						str:
         snake_case								= LDMTextToImagePipeline.from_pretrained("CompVis/ldm-text2im-large-256"       ).to(_A       )
         pipe.set_progress_bar_config(disable=_A       )

         snake_case								= self.get_inputs(_A       )
         snake_case								= pipe(**_A       ).images
         snake_case								= image[0, -3:, -3:, -1].flatten()

         assert image.shape == (1, 2_5_6, 2_5_6, 3)
         snake_case								= np.array([0.5_18_25, 0.5_28_50, 0.5_25_43, 0.5_42_58, 0.5_23_04, 0.5_25_69, 0.5_43_63, 0.5_52_76, 0.5_68_78]       )
         snake_case								= np.abs(expected_slice - image_slice       ).max()
         assert max_diff < 1E-3







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





     def 		UpperCAmelCase(self				:   List[Any]       )						->						Optional[int]:
         super().tearDown()
         gc.collect()
         torch.cuda.empty_cache()





     def 		UpperCAmelCase(self				:   int    ,   _A				:   Tuple    ,   _A				:   Any=torch.floataa    ,   _A				:   int=0       )						->						str:
         snake_case								= torch.manual_seed(_A       )
         snake_case								= np.random.RandomState(_A       ).standard_normal((1, 4, 3_2, 3_2)       )
         snake_case								= torch.from_numpy(_A       ).to(device=_A    ,   dtype=_A       )
         snake_case								= {
             "prompt": "A painting of a squirrel eating a burger",
             "latents": latents,
             "generator": generator,
             "num_inference_steps": 5_0,
             "guidance_scale": 6.0,
             "output_type": "numpy",
         }
         return inputs





     def 		UpperCAmelCase(self				:   Optional[int]       )						->						Optional[Any]:
         snake_case								= LDMTextToImagePipeline.from_pretrained("CompVis/ldm-text2im-large-256"       ).to(_A       )
         pipe.set_progress_bar_config(disable=_A       )

         snake_case								= self.get_inputs(_A       )
         snake_case								= pipe(**_A       ).images[0]

         snake_case								= load_numpy(
             "https://huggingface.co/datasets/diffusers/test-arrays/resolve/main/ldm_text2img/ldm_large_256_ddim.npy"       )
         snake_case								= np.abs(expected_image - image       ).max()
         assert max_diff < 1E-3






import unittest

from transformers.utils.backbone_utils import (
    BackboneMixin,
    get_aligned_output_features_output_indices,
    verify_out_features_out_indices,
)







class 					lowerCamelCase		(  unittest.TestCase  ):





     def 		UpperCAmelCase(self				:   Tuple       )						->						List[str]:
         snake_case								= ["a", "b", "c"]

         # Defaults to last layer if both are None
         snake_case					,							snake_case								= get_aligned_output_features_output_indices(_A    ,   _A    ,   _A       )
         self.assertEqual(_A    ,   ["c"]       )
         self.assertEqual(_A    ,   [2]       )

         # Out indices set to match out features
         snake_case					,							snake_case								= get_aligned_output_features_output_indices(["a", "c"]    ,   _A    ,   _A       )
         self.assertEqual(_A    ,   ["a", "c"]       )
         self.assertEqual(_A    ,   [0, 2]       )

         # Out features set to match out indices
         snake_case					,							snake_case								= get_aligned_output_features_output_indices(_A    ,   [0, 2]    ,   _A       )
         self.assertEqual(_A    ,   ["a", "c"]       )
         self.assertEqual(_A    ,   [0, 2]       )

         # Out features selected from negative indices
         snake_case					,							snake_case								= get_aligned_output_features_output_indices(_A    ,   [-3, -1]    ,   _A       )
         self.assertEqual(_A    ,   ["a", "c"]       )
         self.assertEqual(_A    ,   [-3, -1]       )





     def 		UpperCAmelCase(self				:   Optional[int]       )						->						str:
         # Stage names must be set
         with self.assertRaises(_A       ):
             verify_out_features_out_indices(["a", "b"]    ,   (0, 1)    ,   _A       )

         # Out features must be a list
         with self.assertRaises(_A       ):
             verify_out_features_out_indices(("a", "b")    ,   (0, 1)    ,   ["a", "b"]       )

         # Out features must be a subset of stage names
         with self.assertRaises(_A       ):
             verify_out_features_out_indices(["a", "b"]    ,   (0, 1)    ,   ["a"]       )

         # Out indices must be a list or tuple
         with self.assertRaises(_A       ):
             verify_out_features_out_indices(_A    ,   0    ,   ["a", "b"]       )

         # Out indices must be a subset of stage names
         with self.assertRaises(_A       ):
             verify_out_features_out_indices(_A    ,   (0, 1)    ,   ["a"]       )

         # Out features and out indices must be the same length
         with self.assertRaises(_A       ):
             verify_out_features_out_indices(["a", "b"]    ,   (0,)    ,   ["a", "b", "c"]       )

         # Out features should match out indices
         with self.assertRaises(_A       ):
             verify_out_features_out_indices(["a", "b"]    ,   (0, 2)    ,   ["a", "b", "c"]       )

         # Out features and out indices should be in order
         with self.assertRaises(_A       ):
             verify_out_features_out_indices(["b", "a"]    ,   (0, 1)    ,   ["a", "b"]       )

         # Check passes with valid inputs
         verify_out_features_out_indices(["a", "b", "d"]    ,   (0, 1, -1)    ,   ["a", "b", "c", "d"]       )





     def 		UpperCAmelCase(self				:   List[str]       )						->						str:
         snake_case								= BackboneMixin()

         snake_case								= ["a", "b", "c"]
         snake_case								= ["a", "c"]
         snake_case								= [0, 2]

         # Check that the output features and indices are set correctly
         self.assertEqual(backbone.out_features    ,   ["a", "c"]       )
         self.assertEqual(backbone.out_indices    ,   [0, 2]       )

         # Check out features and indices are updated correctly
         snake_case								= ["a", "b"]
         self.assertEqual(backbone.out_features    ,   ["a", "b"]       )
         self.assertEqual(backbone.out_indices    ,   [0, 1]       )

         snake_case								= [-3, -1]
         self.assertEqual(backbone.out_features    ,   ["a", "c"]       )
         self.assertEqual(backbone.out_indices    ,   [-3, -1]       )

