

import gc
import unittest

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

from diffusers import (
    AutoencoderKL,
    DDIMScheduler,
    EulerAncestralDiscreteScheduler,
    LMSDiscreteScheduler,
    PNDMScheduler,
    StableDiffusionPanoramaPipeline,
    UNetaDConditionModel,
)
from diffusers.utils import slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, skip_mps

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


enable_full_determinism()


@skip_mps
class  A						(							_UpperCAmelCase    ,							_UpperCAmelCase    ,							unittest.TestCase ):







    """simple docstring"""





    lowerCamelCase			=							StableDiffusionPanoramaPipeline
    lowerCamelCase			=							TEXT_TO_IMAGE_PARAMS
    lowerCamelCase			=							TEXT_TO_IMAGE_BATCH_PARAMS
    lowerCamelCase			=							TEXT_TO_IMAGE_IMAGE_PARAMS
    lowerCamelCase			=							TEXT_TO_IMAGE_IMAGE_PARAMS


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





        '''simple docstring'''







        torch.manual_seed(0		)
        A__          =   UNetaDConditionModel(
            block_out_channels=(3_2, 6_4),layers_per_block=1,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,)
        A__          =   DDIMScheduler()
        torch.manual_seed(0		)
        A__          =   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		)
        A__          =   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,)
        A__          =   CLIPTextModel(lowercase_		)
        A__          =   CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip'		)

        A__          =   {
            'unet': unet,
            'scheduler': scheduler,
            'vae': vae,
            'text_encoder': text_encoder,
            'tokenizer': tokenizer,
            'safety_checker': None,
            'feature_extractor': None,
        }
        return components


    def 						snake_case__     (      self :       str,lowercase_ :       Tuple,lowercase_ :       Optional[int]=0		)->    int:





        '''simple docstring'''







        A__          =   torch.manual_seed(lowercase_		)
        A__          =   {
            'prompt': 'a photo of the dolomites',
            'generator': generator,
            # Setting height and width to None to prevent OOMs on CPU.
            'height': None,
            'width': None,
            'num_inference_steps': 1,
            'guidance_scale': 6.0,
            'output_type': 'numpy',
        }
        return inputs


    def 						snake_case__     (      self :       Optional[Any]		)->    Tuple:





        '''simple docstring'''







        A__          =   'cpu'  # ensure determinism for the device-dependent torch.Generator
        A__          =   self.get_dummy_components()
        A__          =   StableDiffusionPanoramaPipeline(**lowercase_		)
        A__          =   sd_pipe.to(lowercase_		)
        sd_pipe.set_progress_bar_config(disable=lowercase_		)

        A__          =   self.get_dummy_inputs(lowercase_		)
        A__          =   sd_pipe(**lowercase_		).images
        A__          =   image[0, -3:, -3:, -1]
        assert image.shape == (1, 6_4, 6_4, 3)

        A__          =   np.array([0.6_186, 0.5_374, 0.4_915, 0.4_135, 0.4_114, 0.4_563, 0.5_128, 0.4_977, 0.4_757]		)

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


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





        '''simple docstring'''







        super().test_inference_batch_consistent(batch_sizes=[1, 2]		)


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





        '''simple docstring'''







        super().test_inference_batch_single_identical(batch_size=2,expected_max_diff=3.25E-3		)


    def 						snake_case__     (      self :       Optional[Any]		)->    List[str]:





        '''simple docstring'''







        A__          =   'cpu'  # ensure determinism for the device-dependent torch.Generator
        A__          =   self.get_dummy_components()
        A__          =   StableDiffusionPanoramaPipeline(**lowercase_		)
        A__          =   sd_pipe.to(lowercase_		)
        sd_pipe.set_progress_bar_config(disable=lowercase_		)

        A__          =   self.get_dummy_inputs(lowercase_		)
        A__          =   'french fries'
        A__          =   sd_pipe(**lowercase_,negative_prompt=lowercase_		)
        A__          =   output.images
        A__          =   image[0, -3:, -3:, -1]

        assert image.shape == (1, 6_4, 6_4, 3)

        A__          =   np.array([0.6_187, 0.5_375, 0.4_915, 0.4_136, 0.4_114, 0.4_563, 0.5_128, 0.4_976, 0.4_757]		)

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


    def 						snake_case__     (      self :       List[str]		)->    List[str]:





        '''simple docstring'''







        A__          =   'cpu'  # ensure determinism for the device-dependent torch.Generator
        A__          =   self.get_dummy_components()
        A__          =   StableDiffusionPanoramaPipeline(**lowercase_		)
        A__          =   sd_pipe.to(lowercase_		)
        sd_pipe.set_progress_bar_config(disable=lowercase_		)

        A__          =   self.get_dummy_inputs(lowercase_		)
        A__          =   sd_pipe(**lowercase_,view_batch_size=2		)
        A__          =   output.images
        A__          =   image[0, -3:, -3:, -1]

        assert image.shape == (1, 6_4, 6_4, 3)

        A__          =   np.array([0.6_187, 0.5_375, 0.4_915, 0.4_136, 0.4_114, 0.4_563, 0.5_128, 0.4_976, 0.4_757]		)

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


    def 						snake_case__     (      self :       Any		)->    str:





        '''simple docstring'''







        A__          =   'cpu'  # ensure determinism for the device-dependent torch.Generator
        A__          =   self.get_dummy_components()
        A__          =   EulerAncestralDiscreteScheduler(
            beta_start=0.00_085,beta_end=0.012,beta_schedule='scaled_linear'		)
        A__          =   StableDiffusionPanoramaPipeline(**lowercase_		)
        A__          =   sd_pipe.to(lowercase_		)
        sd_pipe.set_progress_bar_config(disable=lowercase_		)

        A__          =   self.get_dummy_inputs(lowercase_		)
        A__          =   sd_pipe(**lowercase_		).images
        A__          =   image[0, -3:, -3:, -1]

        assert image.shape == (1, 6_4, 6_4, 3)

        A__          =   np.array([0.4_024, 0.6_510, 0.4_901, 0.5_378, 0.5_813, 0.5_622, 0.4_795, 0.4_467, 0.4_952]		)

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


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





        '''simple docstring'''







        A__          =   'cpu'  # ensure determinism for the device-dependent torch.Generator
        A__          =   self.get_dummy_components()
        A__          =   PNDMScheduler(
            beta_start=0.00_085,beta_end=0.012,beta_schedule='scaled_linear',skip_prk_steps=lowercase_		)
        A__          =   StableDiffusionPanoramaPipeline(**lowercase_		)
        A__          =   sd_pipe.to(lowercase_		)
        sd_pipe.set_progress_bar_config(disable=lowercase_		)

        A__          =   self.get_dummy_inputs(lowercase_		)
        A__          =   sd_pipe(**lowercase_		).images
        A__          =   image[0, -3:, -3:, -1]

        assert image.shape == (1, 6_4, 6_4, 3)

        A__          =   np.array([0.6_391, 0.6_291, 0.4_861, 0.5_134, 0.5_552, 0.4_578, 0.5_032, 0.5_023, 0.4_539]		)

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




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







    """simple docstring"""





    def 						snake_case__     (      self :       Tuple		)->    Tuple:





        '''simple docstring'''







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


    def 						snake_case__     (      self :       List[Any],lowercase_ :       int=0		)->    Optional[int]:





        '''simple docstring'''







        A__          =   torch.manual_seed(lowercase_		)
        A__          =   {
            'prompt': 'a photo of the dolomites',
            'generator': generator,
            'num_inference_steps': 3,
            'guidance_scale': 7.5,
            'output_type': 'numpy',
        }
        return inputs


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





        '''simple docstring'''







        A__          =   'stabilityai/stable-diffusion-2-base'
        A__          =   DDIMScheduler.from_pretrained(lowercase_,subfolder='scheduler'		)
        A__          =   StableDiffusionPanoramaPipeline.from_pretrained(lowercase_,scheduler=lowercase_,safety_checker=lowercase_		)
        pipe.to(lowercase_		)
        pipe.set_progress_bar_config(disable=lowercase_		)
        pipe.enable_attention_slicing()

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

        assert image.shape == (1, 5_1_2, 2_0_4_8, 3)

        A__          =   np.array(
            [
                0.36_968_392,
                0.27_025_372,
                0.32_446_766,
                0.28_379_387,
                0.36_363_274,
                0.30_733_347,
                0.27_100_027,
                0.27_054_125,
                0.25_536_096,
            ]		)

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


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





        '''simple docstring'''







        A__          =   StableDiffusionPanoramaPipeline.from_pretrained(
            'stabilityai/stable-diffusion-2-base',safety_checker=lowercase_		)
        A__          =   LMSDiscreteScheduler.from_config(pipe.scheduler.config		)
        pipe.to(lowercase_		)
        pipe.set_progress_bar_config(disable=lowercase_		)
        pipe.enable_attention_slicing()

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

        assert image.shape == (1, 5_1_2, 2_0_4_8, 3)

        A__          =   np.array(
            [
                [
                    0.0,
                    0.0,
                    0.0,
                    0.0,
                    0.0,
                    0.0,
                    0.0,
                    0.0,
                    0.0,
                ]
            ]		)

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


    def 						snake_case__     (      self :       Tuple		)->    Any:





        '''simple docstring'''







        A__          =   0

        def callback_fn(lowercase_ :       int,lowercase_ :       int,lowercase_ :       torch.FloatTensor		) -> None:
            A__          =   True
            nonlocal number_of_steps
            number_of_steps += 1
            if step == 1:
                A__          =   latents.detach().cpu().numpy()
                assert latents.shape == (1, 4, 6_4, 2_5_6)
                A__          =   latents[0, -3:, -3:, -1]

                A__          =   np.array(
                    [
                        0.18_681_869,
                        0.33_907_816,
                        0.5_361_276,
                        0.14_432_865,
                        -0.02_856_611,
                        -0.73_941_123,
                        0.23_397_987,
                        0.47_322_682,
                        -0.37_823_164,
                    ]		)
                assert np.abs(latents_slice.flatten() - expected_slice		).max() < 5E-2
            elif step == 2:
                A__          =   latents.detach().cpu().numpy()
                assert latents.shape == (1, 4, 6_4, 2_5_6)
                A__          =   latents[0, -3:, -3:, -1]

                A__          =   np.array(
                    [
                        0.18_539_645,
                        0.33_987_248,
                        0.5_378_559,
                        0.14_437_142,
                        -0.02_455_261,
                        -0.7_338_317,
                        0.23_990_755,
                        0.47_356_272,
                        -0.3_786_505,
                    ]		)

                assert np.abs(latents_slice.flatten() - expected_slice		).max() < 5E-2

        A__          =   False

        A__          =   'stabilityai/stable-diffusion-2-base'
        A__          =   DDIMScheduler.from_pretrained(lowercase_,subfolder='scheduler'		)
        A__          =   StableDiffusionPanoramaPipeline.from_pretrained(lowercase_,scheduler=lowercase_,safety_checker=lowercase_		)
        A__          =   pipe.to(lowercase_		)
        pipe.set_progress_bar_config(disable=lowercase_		)
        pipe.enable_attention_slicing()

        A__          =   self.get_inputs()
        pipe(**lowercase_,callback=lowercase_,callback_steps=1		)
        assert callback_fn.has_been_called
        assert number_of_steps == 3


    def 						snake_case__     (      self :       Dict		)->    List[str]:





        '''simple docstring'''







        torch.cuda.empty_cache()
        torch.cuda.reset_max_memory_allocated()
        torch.cuda.reset_peak_memory_stats()

        A__          =   'stabilityai/stable-diffusion-2-base'
        A__          =   DDIMScheduler.from_pretrained(lowercase_,subfolder='scheduler'		)
        A__          =   StableDiffusionPanoramaPipeline.from_pretrained(lowercase_,scheduler=lowercase_,safety_checker=lowercase_		)
        A__          =   pipe.to(lowercase_		)
        pipe.set_progress_bar_config(disable=lowercase_		)
        pipe.enable_attention_slicing(1		)
        pipe.enable_sequential_cpu_offload()

        A__          =   self.get_inputs()
        A__          =   pipe(**lowercase_		)

        A__          =   torch.cuda.max_memory_allocated()
        # make sure that less than 5.2 GB is allocated
        assert mem_bytes < 5.5 * 1_0**9





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											=       '\n{0} = None\n'

lowerCamelCase											=       '\nclass {0}(metaclass=DummyObject):\n    _backends = {1}\n\n    def __init__(self, *args, **kwargs):\n        requires_backends(self, {1})\n'


lowerCamelCase											=       '\ndef {0}(*args, **kwargs):\n    requires_backends({0}, {1})\n'




class A  (   unittest.TestCase     ):






      def        lowerCamelCase       (					self						:     Tuple )					->						Union[str, Any]:
             """simple docstring"""




             _lowerCamelCase       :		int		=find_backend('    _import_structure["models.albert"].append("AlbertTokenizerFast")' )
             self.assertIsNone(lowercase_ )

             _lowerCamelCase       :		List[str]		=find_backend('    if not is_tokenizers_available():' )
             self.assertEqual(lowercase_			,   'tokenizers' )

             _lowerCamelCase       :		List[Any]		=find_backend('    if not is_tensorflow_text_available():' )
             self.assertEqual(lowercase_			,   'tensorflow_text' )

             _lowerCamelCase       :		int		=find_backend('    if not (is_sentencepiece_available() and is_tokenizers_available()):' )
             self.assertEqual(lowercase_			,   'sentencepiece_and_tokenizers' )

             _lowerCamelCase       :		Dict		=find_backend(
                 '    if not (is_sentencepiece_available() and is_tensorflow_text_available()):' )
             self.assertEqual(lowercase_			,   'sentencepiece_and_tensorflow_text' )

             _lowerCamelCase       :		List[Any]		=find_backend(
                 '    if not (is_sentencepiece_available() and is_tokenizers_available() and is_vision_available()):' )
             self.assertEqual(lowercase_			,   'sentencepiece_and_tokenizers_and_vision' )






      def        lowerCamelCase       (					self						:     Optional[Any] )					->						List[str]:
             """simple docstring"""




             _lowerCamelCase       :		Union[str, Any]		=read_init()
             # We don't assert on the exact list of keys to allow for smooth grow of backend-specific objects
             self.assertIn('torch'			,   lowercase_ )
             self.assertIn('tensorflow_text'			,   lowercase_ )
             self.assertIn('sentencepiece_and_tokenizers'			,   lowercase_ )

             # 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        lowerCamelCase       (					self						:     int )					->						Optional[Any]:
             """simple docstring"""




             _lowerCamelCase       :		Optional[Any]		=create_dummy_object('CONSTANT'			,   '\'torch\'' )
             self.assertEqual(lowercase_			,   '\nCONSTANT = None\n' )

             _lowerCamelCase       :		Dict		=create_dummy_object('function'			,   '\'torch\'' )
             self.assertEqual(
                 lowercase_			,   '\ndef function(*args, **kwargs):\n    requires_backends(function, \'torch\')\n' )

             _lowerCamelCase       :		Union[str, Any]		='\nclass FakeClass(metaclass=DummyObject):\n    _backends = \'torch\'\n\n    def __init__(self, *args, **kwargs):\n        requires_backends(self, \'torch\')\n'
             _lowerCamelCase       :		Tuple		=create_dummy_object('FakeClass'			,   '\'torch\'' )
             self.assertEqual(lowercase_			,   lowercase_ )






      def        lowerCamelCase       (					self						:     List[Any] )					->						Dict:
             """simple docstring"""




             _lowerCamelCase       :		Dict		='# This file is autogenerated by the command `make fix-copies`, do not edit.\nfrom ..utils import DummyObject, requires_backends\n\n\nCONSTANT = None\n\n\ndef function(*args, **kwargs):\n    requires_backends(function, ["torch"])\n\n\nclass FakeClass(metaclass=DummyObject):\n    _backends = ["torch"]\n\n    def __init__(self, *args, **kwargs):\n        requires_backends(self, ["torch"])\n'
             _lowerCamelCase       :		Optional[int]		=create_dummy_files({'torch': ['CONSTANT', 'function', 'FakeClass']} )
             self.assertEqual(dummy_files['torch']			,   lowercase_ )


