

'''simple docstring'''







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        A__   (   _snake_case    ,    unittest.TestCase      ):
    lowercase						       =		LDMTextToImagePipeline
    lowercase						       =		TEXT_TO_IMAGE_PARAMS - {
        "negative_prompt",
        "negative_prompt_embeds",
        "cross_attention_kwargs",
        "prompt_embeds",
    }
    lowercase						       =		PipelineTesterMixin.required_optional_params - {
        "num_images_per_prompt",
        "callback",
        "callback_steps",
    }
    lowercase						       =		TEXT_TO_IMAGE_BATCH_PARAMS
    lowercase						       =		False



    def        snake_case_      (       self							)    ->   Dict:





           '''simple docstring'''
           torch.manual_seed(0							)
           A_						       =   UNetaDConditionModel(
               block_out_channels=(32, 64)		,					layers_per_block=2		,					sample_size=32		,					in_channels=4		,					out_channels=4		,					down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""")		,					up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""")		,					cross_attention_dim=32		,					)
           A_						       =   DDIMScheduler(
               beta_start=0.00085		,					beta_end=0.012		,					beta_schedule="""scaled_linear"""		,					clip_sample=UpperCamelCase__		,					set_alpha_to_one=UpperCamelCase__		,					)
           torch.manual_seed(0							)
           A_						       =   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		,					)
           torch.manual_seed(0							)
           A_						       =   CLIPTextConfig(
               bos_token_id=0		,					eos_token_id=2		,					hidden_size=32		,					intermediate_size=37		,					layer_norm_eps=1e-0_5		,					num_attention_heads=4		,					num_hidden_layers=5		,					pad_token_id=1		,					vocab_size=1000		,					)
           A_						       =   CLIPTextModel(UpperCamelCase__							)
           A_						       =   CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip"""							)

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



    def        snake_case_      (       self		,					UpperCamelCase__		,					UpperCamelCase__=0							)    ->   Union[str, Any]:





           '''simple docstring'''
           if str(UpperCamelCase__							).startswith("""mps"""							):
                  A_						       =   torch.manual_seed(UpperCamelCase__							)
           else:
                  A_						       =   torch.Generator(device=UpperCamelCase__							).manual_seed(UpperCamelCase__							)
           A_						       =   {
               """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        snake_case_      (       self							)    ->   Optional[Any]:





           '''simple docstring'''
           A_						       =   """cpu"""  # ensure determinism for the device-dependent torch.Generator

           A_						       =   self.get_dummy_components()
           A_						       =   LDMTextToImagePipeline(**UpperCamelCase__							)
           pipe.to(UpperCamelCase__							)
           pipe.set_progress_bar_config(disable=UpperCamelCase__							)

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

           assert image.shape == (1, 16, 16, 3)
           A_						       =   np.array([0.6101, 0.6156, 0.5622, 0.4895, 0.6661, 0.3804, 0.5748, 0.6136, 0.5014]							)

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


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



    def        snake_case_      (       self							)    ->   Optional[Any]:





           '''simple docstring'''
           super().tearDown()
           gc.collect()
           torch.cuda.empty_cache()



    def        snake_case_      (       self		,					UpperCamelCase__		,					UpperCamelCase__=torch.floataa		,					UpperCamelCase__=0							)    ->   List[str]:





           '''simple docstring'''
           A_						       =   torch.manual_seed(UpperCamelCase__							)
           A_						       =   np.random.RandomState(UpperCamelCase__							).standard_normal((1, 4, 32, 32)							)
           A_						       =   torch.from_numpy(UpperCamelCase__							).to(device=UpperCamelCase__		,					dtype=UpperCamelCase__							)
           A_						       =   {
               """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        snake_case_      (       self							)    ->   Optional[int]:





           '''simple docstring'''
           A_						       =   LDMTextToImagePipeline.from_pretrained("""CompVis/ldm-text2im-large-256"""							).to(UpperCamelCase__							)
           pipe.set_progress_bar_config(disable=UpperCamelCase__							)

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

           assert image.shape == (1, 256, 256, 3)
           A_						       =   np.array([0.51825, 0.52850, 0.52543, 0.54258, 0.52304, 0.52569, 0.54363, 0.55276, 0.56878]							)
           A_						       =   np.abs(expected_slice - image_slice							).max()
           assert max_diff < 1e-3


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



    def        snake_case_      (       self							)    ->   Union[str, Any]:





           '''simple docstring'''
           super().tearDown()
           gc.collect()
           torch.cuda.empty_cache()



    def        snake_case_      (       self		,					UpperCamelCase__		,					UpperCamelCase__=torch.floataa		,					UpperCamelCase__=0							)    ->   Optional[int]:





           '''simple docstring'''
           A_						       =   torch.manual_seed(UpperCamelCase__							)
           A_						       =   np.random.RandomState(UpperCamelCase__							).standard_normal((1, 4, 32, 32)							)
           A_						       =   torch.from_numpy(UpperCamelCase__							).to(device=UpperCamelCase__		,					dtype=UpperCamelCase__							)
           A_						       =   {
               """prompt""": """A painting of a squirrel eating a burger""",
               """latents""": latents,
               """generator""": generator,
               """num_inference_steps""": 50,
               """guidance_scale""": 6.0,
               """output_type""": """numpy""",
           }
           return inputs







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





           '''simple docstring'''
           A_						       =   LDMTextToImagePipeline.from_pretrained("""CompVis/ldm-text2im-large-256"""							).to(UpperCamelCase__							)
           pipe.set_progress_bar_config(disable=UpperCamelCase__							)

           A_						       =   self.get_inputs(UpperCamelCase__							)
           A_						       =   pipe(**UpperCamelCase__							).images[0]

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



'''simple docstring'''







import os
import sys
import unittest


__lowerCamelCase									=     os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
sys.path.append(os.path.join(git_repo_path, '''utils'''))

import check_dummies  # noqa: E402
from check_dummies import create_dummy_files, create_dummy_object, find_backend, read_init  # noqa: E402


# Align TRANSFORMERS_PATH in check_dummies with the current path
__lowerCamelCase									=     os.path.join(git_repo_path, '''src''', '''transformers''')

__lowerCamelCase									=     '''
{0} = None
'''

__lowerCamelCase									=     '''
class {0}(metaclass=DummyObject):
    _backends = {1}

    def __init__(self, *args, **kwargs):
        requires_backends(self, {1})
'''


__lowerCamelCase									=     '''
def {0}(*args, **kwargs):
    requires_backends({0}, {1})
'''


class        A__   (   unittest.TestCase      ):



    def        snake_case_      (       self							)    ->   Dict:





           '''simple docstring'''
           A_						       =   find_backend("""    _import_structure[\"models.albert\"].append(\"AlbertTokenizerFast\")"""							)
           self.assertIsNone(UpperCamelCase__							)

           A_						       =   find_backend("""    if not is_tokenizers_available():"""							)
           self.assertEqual(UpperCamelCase__		,					"""tokenizers"""							)

           A_						       =   find_backend("""    if not is_tensorflow_text_available():"""							)
           self.assertEqual(UpperCamelCase__		,					"""tensorflow_text"""							)

           A_						       =   find_backend("""    if not (is_sentencepiece_available() and is_tokenizers_available()):"""							)
           self.assertEqual(UpperCamelCase__		,					"""sentencepiece_and_tokenizers"""							)

           A_						       =   find_backend(
               """    if not (is_sentencepiece_available() and is_tensorflow_text_available()):"""							)
           self.assertEqual(UpperCamelCase__		,					"""sentencepiece_and_tensorflow_text"""							)

           A_						       =   find_backend(
               """    if not (is_sentencepiece_available() and is_tokenizers_available() and is_vision_available()):"""							)
           self.assertEqual(UpperCamelCase__		,					"""sentencepiece_and_tokenizers_and_vision"""							)



    def        snake_case_      (       self							)    ->   int:





           '''simple docstring'''
           A_						       =   read_init()
           # We don't assert on the exact list of keys to allow for smooth grow of backend-specific objects
           self.assertIn("""torch"""		,					UpperCamelCase__							)
           self.assertIn("""tensorflow_text"""		,					UpperCamelCase__							)
           self.assertIn("""sentencepiece_and_tokenizers"""		,					UpperCamelCase__							)

           # Likewise, we can't assert on the exact content of a key
           self.assertIn("""BertModel"""		,					objects["""torch"""]							)
           self.assertIn("""TFBertModel"""		,					objects["""tf"""]							)
           self.assertIn("""FlaxBertModel"""		,					objects["""flax"""]							)
           self.assertIn("""BertModel"""		,					objects["""torch"""]							)
           self.assertIn("""TFBertTokenizer"""		,					objects["""tensorflow_text"""]							)
           self.assertIn("""convert_slow_tokenizer"""		,					objects["""sentencepiece_and_tokenizers"""]							)



    def        snake_case_      (       self							)    ->   str:





           '''simple docstring'''
           A_						       =   create_dummy_object("""CONSTANT"""		,					"""'torch'"""							)
           self.assertEqual(UpperCamelCase__		,					"""\nCONSTANT = None\n"""							)

           A_						       =   create_dummy_object("""function"""		,					"""'torch'"""							)
           self.assertEqual(
               UpperCamelCase__		,					"""\ndef function(*args, **kwargs):\n    requires_backends(function, 'torch')\n"""							)

           A_						       =   """
class FakeClass(metaclass=DummyObject):
    _backends = 'torch'

    def __init__(self, *args, **kwargs):
        requires_backends(self, 'torch')
"""
           A_						       =   create_dummy_object("""FakeClass"""		,					"""'torch'"""							)
           self.assertEqual(UpperCamelCase__		,					UpperCamelCase__							)







    def        snake_case_      (       self							)    ->   str:





           '''simple docstring'''
           A_						       =   """# This file is autogenerated by the command `make fix-copies`, do not edit.
from ..utils import DummyObject, requires_backends


CONSTANT = None


def function(*args, **kwargs):
    requires_backends(function, [\"torch\"])


class FakeClass(metaclass=DummyObject):
    _backends = [\"torch\"]

    def __init__(self, *args, **kwargs):
        requires_backends(self, [\"torch\"])
"""
           A_						       =   create_dummy_files({"""torch""": ["""CONSTANT""", """function""", """FakeClass"""]}							)
           self.assertEqual(dummy_files["""torch"""]		,					UpperCamelCase__							)
