

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 	__UpperCamelCase    (    __UpperCAmelCase							,							__UpperCAmelCase							,							unittest.TestCase						):
  _UpperCAmelCase          =		StableDiffusionPanoramaPipeline
  _UpperCAmelCase          =		TEXT_TO_IMAGE_PARAMS
  _UpperCAmelCase          =		TEXT_TO_IMAGE_BATCH_PARAMS
  _UpperCAmelCase          =		TEXT_TO_IMAGE_IMAGE_PARAMS
  _UpperCAmelCase          =		TEXT_TO_IMAGE_IMAGE_PARAMS

  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      torch.manual_seed(0      )
      _lowerCAmelCase       :   Optional[Any]  =    UNetaDConditionModel(
          block_out_channels=(32, 64)    ,layers_per_block=1    ,sample_size=32    ,in_channels=4    ,out_channels=4    ,down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D')    ,up_block_types=('CrossAttnUpBlock2D', 'UpBlock2D')    ,cross_attention_dim=32    ,)
      _lowerCAmelCase       :   Any  =    DDIMScheduler()
      torch.manual_seed(0      )
      _lowerCAmelCase       :   Tuple  =    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      )
      _lowerCAmelCase       :   Any  =    CLIPTextConfig(
          bos_token_id=0    ,eos_token_id=2    ,hidden_size=32    ,intermediate_size=37    ,layer_norm_eps=1E-05    ,num_attention_heads=4    ,num_hidden_layers=5    ,pad_token_id=1    ,vocab_size=1000    ,)
      _lowerCAmelCase       :   Union[str, Any]  =    CLIPTextModel(UpperCAmelCase_      )
      _lowerCAmelCase       :   int  =    CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip'      )

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

  def __lowerCamelCase		(		self    ,_A    ,_A=0      ):
      '''simple docstring'''

      _lowerCAmelCase       :   Union[str, Any]  =    torch.manual_seed(UpperCAmelCase_      )
      _lowerCAmelCase       :   int  =    {
          '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 __lowerCamelCase		(		self      ):
      '''simple docstring'''

      _lowerCAmelCase       :   List[Any]  =    'cpu'  # ensure determinism for the device-dependent torch.Generator
      _lowerCAmelCase       :   Dict  =    self.get_dummy_components()
      _lowerCAmelCase       :   Optional[int]  =    StableDiffusionPanoramaPipeline(**UpperCAmelCase_      )
      _lowerCAmelCase       :   str  =    sd_pipe.to(UpperCAmelCase_      )
      sd_pipe.set_progress_bar_config(disable=UpperCAmelCase_      )

      _lowerCAmelCase       :   Dict  =    self.get_dummy_inputs(UpperCAmelCase_      )
      _lowerCAmelCase       :   int  =    sd_pipe(**UpperCAmelCase_      ).images
      _lowerCAmelCase       :   Tuple  =    image[0, -3:, -3:, -1]
      assert image.shape == (1, 64, 64, 3)

      _lowerCAmelCase       :   Dict  =    np.array([0.6_1_8_6, 0.5_3_7_4, 0.4_9_1_5, 0.4_1_3_5, 0.4_1_1_4, 0.4_5_6_3, 0.5_1_2_8, 0.4_9_7_7, 0.4_7_5_7]      )

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

  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

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

  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

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

  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      _lowerCAmelCase       :   Tuple  =    'cpu'  # ensure determinism for the device-dependent torch.Generator
      _lowerCAmelCase       :   Union[str, Any]  =    self.get_dummy_components()
      _lowerCAmelCase       :   List[Any]  =    StableDiffusionPanoramaPipeline(**UpperCAmelCase_      )
      _lowerCAmelCase       :   Tuple  =    sd_pipe.to(UpperCAmelCase_      )
      sd_pipe.set_progress_bar_config(disable=UpperCAmelCase_      )

      _lowerCAmelCase       :   Optional[int]  =    self.get_dummy_inputs(UpperCAmelCase_      )
      _lowerCAmelCase       :   Dict  =    'french fries'
      _lowerCAmelCase       :   List[Any]  =    sd_pipe(**UpperCAmelCase_    ,negative_prompt=UpperCAmelCase_      )
      _lowerCAmelCase       :   List[Any]  =    output.images
      _lowerCAmelCase       :   Tuple  =    image[0, -3:, -3:, -1]

      assert image.shape == (1, 64, 64, 3)

      _lowerCAmelCase       :   Tuple  =    np.array([0.6_1_8_7, 0.5_3_7_5, 0.4_9_1_5, 0.4_1_3_6, 0.4_1_1_4, 0.4_5_6_3, 0.5_1_2_8, 0.4_9_7_6, 0.4_7_5_7]      )

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

  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      _lowerCAmelCase       :   List[Any]  =    'cpu'  # ensure determinism for the device-dependent torch.Generator
      _lowerCAmelCase       :   Union[str, Any]  =    self.get_dummy_components()
      _lowerCAmelCase       :   List[Any]  =    StableDiffusionPanoramaPipeline(**UpperCAmelCase_      )
      _lowerCAmelCase       :   Optional[Any]  =    sd_pipe.to(UpperCAmelCase_      )
      sd_pipe.set_progress_bar_config(disable=UpperCAmelCase_      )

      _lowerCAmelCase       :   List[str]  =    self.get_dummy_inputs(UpperCAmelCase_      )
      _lowerCAmelCase       :   Dict  =    sd_pipe(**UpperCAmelCase_    ,view_batch_size=2      )
      _lowerCAmelCase       :   Dict  =    output.images
      _lowerCAmelCase       :   str  =    image[0, -3:, -3:, -1]

      assert image.shape == (1, 64, 64, 3)

      _lowerCAmelCase       :   List[str]  =    np.array([0.6_1_8_7, 0.5_3_7_5, 0.4_9_1_5, 0.4_1_3_6, 0.4_1_1_4, 0.4_5_6_3, 0.5_1_2_8, 0.4_9_7_6, 0.4_7_5_7]      )

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

  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      _lowerCAmelCase       :   Union[str, Any]  =    'cpu'  # ensure determinism for the device-dependent torch.Generator
      _lowerCAmelCase       :   str  =    self.get_dummy_components()
      _lowerCAmelCase       :   Optional[int]  =    EulerAncestralDiscreteScheduler(
          beta_start=0.0_0_0_8_5    ,beta_end=0.0_1_2    ,beta_schedule='scaled_linear'      )
      _lowerCAmelCase       :   Tuple  =    StableDiffusionPanoramaPipeline(**UpperCAmelCase_      )
      _lowerCAmelCase       :   List[Any]  =    sd_pipe.to(UpperCAmelCase_      )
      sd_pipe.set_progress_bar_config(disable=UpperCAmelCase_      )

      _lowerCAmelCase       :   List[Any]  =    self.get_dummy_inputs(UpperCAmelCase_      )
      _lowerCAmelCase       :   Optional[int]  =    sd_pipe(**UpperCAmelCase_      ).images
      _lowerCAmelCase       :   List[Any]  =    image[0, -3:, -3:, -1]

      assert image.shape == (1, 64, 64, 3)

      _lowerCAmelCase       :   Optional[Any]  =    np.array([0.4_0_2_4, 0.6_5_1_0, 0.4_9_0_1, 0.5_3_7_8, 0.5_8_1_3, 0.5_6_2_2, 0.4_7_9_5, 0.4_4_6_7, 0.4_9_5_2]      )

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







  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      _lowerCAmelCase       :   List[Any]  =    'cpu'  # ensure determinism for the device-dependent torch.Generator
      _lowerCAmelCase       :   List[str]  =    self.get_dummy_components()
      _lowerCAmelCase       :   Optional[int]  =    PNDMScheduler(
          beta_start=0.0_0_0_8_5    ,beta_end=0.0_1_2    ,beta_schedule='scaled_linear'    ,skip_prk_steps=UpperCAmelCase_      )
      _lowerCAmelCase       :   Optional[Any]  =    StableDiffusionPanoramaPipeline(**UpperCAmelCase_      )
      _lowerCAmelCase       :   Optional[Any]  =    sd_pipe.to(UpperCAmelCase_      )
      sd_pipe.set_progress_bar_config(disable=UpperCAmelCase_      )

      _lowerCAmelCase       :   List[str]  =    self.get_dummy_inputs(UpperCAmelCase_      )
      _lowerCAmelCase       :   Tuple  =    sd_pipe(**UpperCAmelCase_      ).images
      _lowerCAmelCase       :   List[Any]  =    image[0, -3:, -3:, -1]

      assert image.shape == (1, 64, 64, 3)

      _lowerCAmelCase       :   Tuple  =    np.array([0.6_3_9_1, 0.6_2_9_1, 0.4_8_6_1, 0.5_1_3_4, 0.5_5_5_2, 0.4_5_7_8, 0.5_0_3_2, 0.5_0_2_3, 0.4_5_3_9]      )

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







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

  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

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

  def __lowerCamelCase		(		self    ,_A=0      ):
      '''simple docstring'''

      _lowerCAmelCase       :   List[Any]  =    torch.manual_seed(UpperCAmelCase_      )
      _lowerCAmelCase       :   Union[str, Any]  =    {
          'prompt': 'a photo of the dolomites',
          'generator': generator,
          'num_inference_steps': 3,
          'guidance_scale': 7.5,
          'output_type': 'numpy',
      }
      return inputs

  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      _lowerCAmelCase       :   Union[str, Any]  =    'stabilityai/stable-diffusion-2-base'
      _lowerCAmelCase       :   str  =    DDIMScheduler.from_pretrained(UpperCAmelCase_    ,subfolder='scheduler'      )
      _lowerCAmelCase       :   List[Any]  =    StableDiffusionPanoramaPipeline.from_pretrained(UpperCAmelCase_    ,scheduler=UpperCAmelCase_    ,safety_checker=UpperCAmelCase_      )
      pipe.to(UpperCAmelCase_      )
      pipe.set_progress_bar_config(disable=UpperCAmelCase_      )
      pipe.enable_attention_slicing()

      _lowerCAmelCase       :   Tuple  =    self.get_inputs()
      _lowerCAmelCase       :   Any  =    pipe(**UpperCAmelCase_      ).images
      _lowerCAmelCase       :   Optional[int]  =    image[0, -3:, -3:, -1].flatten()

      assert image.shape == (1, 512, 2048, 3)

      _lowerCAmelCase       :   List[Any]  =    np.array(
          [
              0.3_6_9_6_8_3_9_2,
              0.2_7_0_2_5_3_7_2,
              0.3_2_4_4_6_7_6_6,
              0.2_8_3_7_9_3_8_7,
              0.3_6_3_6_3_2_7_4,
              0.3_0_7_3_3_3_4_7,
              0.2_7_1_0_0_0_2_7,
              0.2_7_0_5_4_1_2_5,
              0.2_5_5_3_6_0_9_6,
          ]      )

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

  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      _lowerCAmelCase       :   Any  =    StableDiffusionPanoramaPipeline.from_pretrained(
          'stabilityai/stable-diffusion-2-base'    ,safety_checker=UpperCAmelCase_      )
      _lowerCAmelCase       :   str  =    LMSDiscreteScheduler.from_config(pipe.scheduler.config      )
      pipe.to(UpperCAmelCase_      )
      pipe.set_progress_bar_config(disable=UpperCAmelCase_      )
      pipe.enable_attention_slicing()

      _lowerCAmelCase       :   List[str]  =    self.get_inputs()
      _lowerCAmelCase       :   int  =    pipe(**UpperCAmelCase_      ).images
      _lowerCAmelCase       :   Dict  =    image[0, -3:, -3:, -1].flatten()

      assert image.shape == (1, 512, 2048, 3)

      _lowerCAmelCase       :   Optional[Any]  =    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 __lowerCamelCase		(		self      ):
      '''simple docstring'''

      _lowerCAmelCase       :   Tuple  =    0

      def callback_fn(_A    ,_A    ,_A      ) -> None:
          _lowerCAmelCase       :   Any  =    True
          nonlocal number_of_steps
          number_of_steps += 1
          if step == 1:
              _lowerCAmelCase       :   int  =    latents.detach().cpu().numpy()
              assert latents.shape == (1, 4, 64, 256)
              _lowerCAmelCase       :   List[Any]  =    latents[0, -3:, -3:, -1]

              _lowerCAmelCase       :   Any  =    np.array(
                  [
                      0.1_8_6_8_1_8_6_9,
                      0.3_3_9_0_7_8_1_6,
                      0.5_3_6_1_2_7_6,
                      0.1_4_4_3_2_8_6_5,
                      -0.0_2_8_5_6_6_1_1,
                      -0.7_3_9_4_1_1_2_3,
                      0.2_3_3_9_7_9_8_7,
                      0.4_7_3_2_2_6_8_2,
                      -0.3_7_8_2_3_1_6_4,
                  ]      )
              assert np.abs(latents_slice.flatten() - expected_slice      ).max() < 5E-2
          elif step == 2:
              _lowerCAmelCase       :   Optional[Any]  =    latents.detach().cpu().numpy()
              assert latents.shape == (1, 4, 64, 256)
              _lowerCAmelCase       :   Dict  =    latents[0, -3:, -3:, -1]

              _lowerCAmelCase       :   str  =    np.array(
                  [
                      0.1_8_5_3_9_6_4_5,
                      0.3_3_9_8_7_2_4_8,
                      0.5_3_7_8_5_5_9,
                      0.1_4_4_3_7_1_4_2,
                      -0.0_2_4_5_5_2_6_1,
                      -0.7_3_3_8_3_1_7,
                      0.2_3_9_9_0_7_5_5,
                      0.4_7_3_5_6_2_7_2,
                      -0.3_7_8_6_5_0_5,
                  ]      )

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

      _lowerCAmelCase       :   int  =    False

      _lowerCAmelCase       :   Union[str, Any]  =    'stabilityai/stable-diffusion-2-base'
      _lowerCAmelCase       :   int  =    DDIMScheduler.from_pretrained(UpperCAmelCase_    ,subfolder='scheduler'      )
      _lowerCAmelCase       :   List[Any]  =    StableDiffusionPanoramaPipeline.from_pretrained(UpperCAmelCase_    ,scheduler=UpperCAmelCase_    ,safety_checker=UpperCAmelCase_      )
      _lowerCAmelCase       :   Dict  =    pipe.to(UpperCAmelCase_      )
      pipe.set_progress_bar_config(disable=UpperCAmelCase_      )
      pipe.enable_attention_slicing()

      _lowerCAmelCase       :   List[str]  =    self.get_inputs()
      pipe(**UpperCAmelCase_    ,callback=UpperCAmelCase_    ,callback_steps=1      )
      assert callback_fn.has_been_called
      assert number_of_steps == 3







  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

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

      _lowerCAmelCase       :   List[Any]  =    'stabilityai/stable-diffusion-2-base'
      _lowerCAmelCase       :   int  =    DDIMScheduler.from_pretrained(UpperCAmelCase_    ,subfolder='scheduler'      )
      _lowerCAmelCase       :   List[str]  =    StableDiffusionPanoramaPipeline.from_pretrained(UpperCAmelCase_    ,scheduler=UpperCAmelCase_    ,safety_checker=UpperCAmelCase_      )
      _lowerCAmelCase       :   str  =    pipe.to(UpperCAmelCase_      )
      pipe.set_progress_bar_config(disable=UpperCAmelCase_      )
      pipe.enable_attention_slicing(1      )
      pipe.enable_sequential_cpu_offload()

      _lowerCAmelCase       :   str  =    self.get_inputs()
      _lowerCAmelCase       :   Any  =    pipe(**UpperCAmelCase_      )

      _lowerCAmelCase       :   Optional[Any]  =    torch.cuda.max_memory_allocated()
      # make sure that less than 5.2 GB is allocated
      assert mem_bytes < 5.5 * 10**9








"""simple docstring"""






from __future__ import annotations

def 		lowerCamelCase__		(					_lowerCamelCase   ):

    '''simple docstring'''



    create_state_space_tree(_lowerCamelCase ,   [] ,   0 ,   [0 for i in range(len(_lowerCamelCase   )   )]   )

def 		lowerCamelCase__		(					_lowerCamelCase ,   _lowerCamelCase ,   _lowerCamelCase ,   _lowerCamelCase ,   ):

    '''simple docstring'''



    if index == len(_lowerCamelCase   ):
        print(_lowerCamelCase   )
        return

    for i in range(len(_lowerCamelCase   )   ):
        if not index_used[i]:
            current_sequence.append(sequence[i]   )
            _lowerCAmelCase       :   List[str]  =    True
            create_state_space_tree(_lowerCamelCase ,   _lowerCamelCase ,   index + 1 ,   _lowerCamelCase   )
            current_sequence.pop()
            _lowerCAmelCase       :   int  =    False
_lowerCAmelCase						=		[3, 1, 2, 4]
generate_all_permutations(sequence)

_lowerCAmelCase						=		["A", "B", "C"]

generate_all_permutations(sequence_a)





