






"""simple docstring"""


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 						snake_case  (  UpperCAmelCase       ,			UpperCAmelCase       ,			unittest.TestCase	):
    __magic_name__   					=					StableDiffusionPanoramaPipeline
    __magic_name__   					=					TEXT_TO_IMAGE_PARAMS
    __magic_name__   					=					TEXT_TO_IMAGE_BATCH_PARAMS
    __magic_name__   					=					TEXT_TO_IMAGE_IMAGE_PARAMS
    __magic_name__   					=					TEXT_TO_IMAGE_IMAGE_PARAMS





    def     lowerCamelCase__				(							self     : str      ):


      '''simple docstring'''




      torch.manual_seed(0      )
      a					:      int    =       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					:      Optional[Any]    =       DDIMScheduler()
      torch.manual_seed(0      )
      a					:      Optional[Any]    =       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					:      str    =       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					:      Dict    =       CLIPTextModel(A      )
      a					:      str    =       CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip'      )

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





    def     lowerCamelCase__				(							self     : Optional[Any]    ,		A     : int    ,		A     : Dict=0      ):


      '''simple docstring'''




      a					:      int    =       torch.manual_seed(A      )
      a					:      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     : Dict      ):


      '''simple docstring'''




      a					:      int    =       'cpu'  # ensure determinism for the device-dependent torch.Generator
      a					:      Tuple    =       self.get_dummy_components()
      a					:      Optional[Any]    =       StableDiffusionPanoramaPipeline(**A      )
      a					:      int    =       sd_pipe.to(A      )
      sd_pipe.set_progress_bar_config(disable=A      )

      a					:      Optional[int]    =       self.get_dummy_inputs(A      )
      a					:      Dict    =       sd_pipe(**A      ).images
      a					:      Any    =       image[0, -3:, -3:, -1]
      assert image.shape == (1, 6_4, 6_4, 3)

      a					:      Any    =       np.array([0.61_86, 0.53_74, 0.49_15, 0.41_35, 0.41_14, 0.45_63, 0.51_28, 0.49_77, 0.47_57]      )

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





    def     lowerCamelCase__				(							self     : Union[str, Any]      ):


      '''simple docstring'''




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





    def     lowerCamelCase__				(							self     : Dict      ):


      '''simple docstring'''




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





    def     lowerCamelCase__				(							self     : Tuple      ):


      '''simple docstring'''




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

      a					:      Any    =       self.get_dummy_inputs(A      )
      a					:      str    =       'french fries'
      a					:      Optional[int]    =       sd_pipe(**A    ,		negative_prompt=A      )
      a					:      Union[str, Any]    =       output.images
      a					:      Optional[int]    =       image[0, -3:, -3:, -1]

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

      a					:      str    =       np.array([0.61_87, 0.53_75, 0.49_15, 0.41_36, 0.41_14, 0.45_63, 0.51_28, 0.49_76, 0.47_57]      )

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





    def     lowerCamelCase__				(							self     : int      ):


      '''simple docstring'''




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

      a					:      int    =       self.get_dummy_inputs(A      )
      a					:      Dict    =       sd_pipe(**A    ,		view_batch_size=2      )
      a					:      Dict    =       output.images
      a					:      List[Any]    =       image[0, -3:, -3:, -1]

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

      a					:      List[str]    =       np.array([0.61_87, 0.53_75, 0.49_15, 0.41_36, 0.41_14, 0.45_63, 0.51_28, 0.49_76, 0.47_57]      )

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





    def     lowerCamelCase__				(							self     : Any      ):


      '''simple docstring'''




      a					:      List[Any]    =       'cpu'  # ensure determinism for the device-dependent torch.Generator
      a					:      Optional[Any]    =       self.get_dummy_components()
      a					:      Tuple    =       EulerAncestralDiscreteScheduler(
          beta_start=0.0_00_85    ,		beta_end=0.0_12    ,		beta_schedule='scaled_linear'      )
      a					:      Optional[int]    =       StableDiffusionPanoramaPipeline(**A      )
      a					:      int    =       sd_pipe.to(A      )
      sd_pipe.set_progress_bar_config(disable=A      )

      a					:      Any    =       self.get_dummy_inputs(A      )
      a					:      Any    =       sd_pipe(**A      ).images
      a					:      Tuple    =       image[0, -3:, -3:, -1]

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

      a					:      Dict    =       np.array([0.40_24, 0.65_10, 0.49_01, 0.53_78, 0.58_13, 0.56_22, 0.47_95, 0.44_67, 0.49_52]      )

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





    def     lowerCamelCase__				(							self     : Dict      ):


      '''simple docstring'''




      a					:      int    =       'cpu'  # ensure determinism for the device-dependent torch.Generator
      a					:      str    =       self.get_dummy_components()
      a					:      Dict    =       PNDMScheduler(
          beta_start=0.0_00_85    ,		beta_end=0.0_12    ,		beta_schedule='scaled_linear'    ,		skip_prk_steps=A      )
      a					:      List[str]    =       StableDiffusionPanoramaPipeline(**A      )
      a					:      Union[str, Any]    =       sd_pipe.to(A      )
      sd_pipe.set_progress_bar_config(disable=A      )

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

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

      a					:      Dict    =       np.array([0.63_91, 0.62_91, 0.48_61, 0.51_34, 0.55_52, 0.45_78, 0.50_32, 0.50_23, 0.45_39]      )

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






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





    def     lowerCamelCase__				(							self     : Union[str, Any]      ):


      '''simple docstring'''




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





    def     lowerCamelCase__				(							self     : List[Any]    ,		A     : Tuple=0      ):


      '''simple docstring'''




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





    def     lowerCamelCase__				(							self     : List[Any]      ):


      '''simple docstring'''




      a					:      Dict    =       'stabilityai/stable-diffusion-2-base'
      a					:      Tuple    =       DDIMScheduler.from_pretrained(A    ,		subfolder='scheduler'      )
      a					:      Dict    =       StableDiffusionPanoramaPipeline.from_pretrained(A    ,		scheduler=A    ,		safety_checker=A      )
      pipe.to(A      )
      pipe.set_progress_bar_config(disable=A      )
      pipe.enable_attention_slicing()

      a					:      Optional[Any]    =       self.get_inputs()
      a					:      Any    =       pipe(**A      ).images
      a					:      Optional[Any]    =       image[0, -3:, -3:, -1].flatten()

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

      a					:      List[Any]    =       np.array(
          [
              0.36_96_83_92,
              0.27_02_53_72,
              0.32_44_67_66,
              0.28_37_93_87,
              0.36_36_32_74,
              0.30_73_33_47,
              0.27_10_00_27,
              0.27_05_41_25,
              0.25_53_60_96,
          ]      )

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





    def     lowerCamelCase__				(							self     : List[Any]      ):


      '''simple docstring'''




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

      a					:      Any    =       self.get_inputs()
      a					:      int    =       pipe(**A      ).images
      a					:      List[str]    =       image[0, -3:, -3:, -1].flatten()

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

      a					:      Union[str, 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     : str      ):


      '''simple docstring'''




      a					:      Optional[Any]    =       0

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

          a					:      int    =       np.array(
              [
                  0.18_68_18_69,
                  0.33_90_78_16,
                  0.5_36_12_76,
                  0.14_43_28_65,
                  -0.02_85_66_11,
                  -0.73_94_11_23,
                  0.23_39_79_87,
                  0.47_32_26_82,
                  -0.37_82_31_64,
              ]      )
          assert np.abs(latents_slice.flatten() - expected_slice      ).max() < 5E-2
        elif step == 2:
          a					:      List[str]    =       latents.detach().cpu().numpy()
          assert latents.shape == (1, 4, 6_4, 2_5_6)
          a					:      Tuple    =       latents[0, -3:, -3:, -1]

          a					:      Optional[int]    =       np.array(
              [
                  0.18_53_96_45,
                  0.33_98_72_48,
                  0.5_37_85_59,
                  0.14_43_71_42,
                  -0.02_45_52_61,
                  -0.7_33_83_17,
                  0.23_99_07_55,
                  0.47_35_62_72,
                  -0.3_78_65_05,
              ]      )

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

      a					:      Any    =       False

      a					:      Optional[int]    =       'stabilityai/stable-diffusion-2-base'
      a					:      List[Any]    =       DDIMScheduler.from_pretrained(A    ,		subfolder='scheduler'      )
      a					:      Optional[Any]    =       StableDiffusionPanoramaPipeline.from_pretrained(A    ,		scheduler=A    ,		safety_checker=A      )
      a					:      Optional[int]    =       pipe.to(A      )
      pipe.set_progress_bar_config(disable=A      )
      pipe.enable_attention_slicing()

      a					:      Dict    =       self.get_inputs()
      pipe(**A    ,		callback=A    ,		callback_steps=1      )
      assert callback_fn.has_been_called
      assert number_of_steps == 3





    def     lowerCamelCase__				(							self     : List[str]      ):


      '''simple docstring'''




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

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

      a					:      Union[str, Any]    =       self.get_inputs()
      a					:      str    =       pipe(**A      )

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












"""simple docstring"""


from __future__ import annotations

import math

import numpy as np
from numpy.linalg import norm




def       snake_case  (A_				:np.ndarray     ,      A_				:np.ndarray				):







  '''simple docstring'''

  return math.sqrt(sum(pow(a - b     ,      2				) for a, b in zip(A_     ,      A_				)				)				)




def       snake_case  (A_				:np.ndarray     ,      A_				:np.ndarray				):







  '''simple docstring'''

  if dataset.ndim != value_array.ndim:
    a					:      Optional[Any]    =       (
        'Wrong input data\'s dimensions... '
        f'''dataset : {dataset.ndim}, value_array : {value_array.ndim}'''
    )
    raise ValueError(A_				)

  try:
    if dataset.shape[1] != value_array.shape[1]:
      a					:      Optional[int]    =       (
          'Wrong input data\'s shape... '
          f'''dataset : {dataset.shape[1]}, value_array : {value_array.shape[1]}'''
      )
      raise ValueError(A_				)
  except IndexError:
    if dataset.ndim != value_array.ndim:
      raise TypeError('Wrong shape'				)

  if dataset.dtype != value_array.dtype:
    a					:      Optional[Any]    =       (
        'Input data have different datatype... '
        f'''dataset : {dataset.dtype}, value_array : {value_array.dtype}'''
    )
    raise TypeError(A_				)

  a					:      Tuple    =       []

  for value in value_array:
    a					:      List[Any]    =       euclidean(A_     ,      dataset[0]				)
    a					:      int    =       dataset[0].tolist()

    for dataset_value in dataset[1:]:
      a					:      Optional[int]    =       euclidean(A_     ,      A_				)

      if dist > temp_dist:
        a					:      List[str]    =       temp_dist
        a					:      int    =       dataset_value.tolist()

    answer.append([vector, dist]				)

  return answer




def       snake_case  (A_				:np.ndarray     ,      A_				:np.ndarray				):







  '''simple docstring'''

  return np.dot(A_     ,      A_				) / (norm(A_				) * norm(A_				))


if __name__ == "__main__":
   import doctest

   doctest.testmod()




