




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 (     __SCREAMING_SNAKE_CASE       ,						__SCREAMING_SNAKE_CASE       ,						unittest.TestCase  ):
						"""simple docstring"""

						UpperCamelCase_	:       Union[str, Any]       	=		StableDiffusionPanoramaPipeline
						UpperCamelCase_	:       Union[str, Any]       	=		TEXT_TO_IMAGE_PARAMS
						UpperCamelCase_	:       List[Any]       	=		TEXT_TO_IMAGE_BATCH_PARAMS
						UpperCamelCase_	:       List[str]       	=		TEXT_TO_IMAGE_IMAGE_PARAMS
						UpperCamelCase_	:       Dict       	=		TEXT_TO_IMAGE_IMAGE_PARAMS






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


													torch.manual_seed(0				)
													__lowercase      =    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				,							)
													__lowercase      =    DDIMScheduler()
													torch.manual_seed(0				)
													__lowercase      =    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				)
													__lowercase      =    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=1_000				,							)
													__lowercase      =    CLIPTextModel(lowerCamelCase__				)
													__lowercase      =    CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip'''				)

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






						def     UpperCAmelCase_      ( self :     Any				,							lowerCamelCase__ :     Optional[Any]				,							lowerCamelCase__ :     List[str]=0				)    ->						Optional[int]:
													"""simple docstring"""


													__lowercase      =    torch.manual_seed(lowerCamelCase__				)
													__lowercase      =    {
													    '''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     UpperCAmelCase_      ( self :     Tuple				)    ->						str:
													"""simple docstring"""


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

													__lowercase      =    self.get_dummy_inputs(lowerCamelCase__				)
													__lowercase      =    sd_pipe(**lowerCamelCase__				).images
													__lowercase      =    image[0, -3:, -3:, -1]
													assert image.shape == (1, 64, 64, 3)

													__lowercase      =    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     UpperCAmelCase_      ( self :     str				)    ->						Any:
													"""simple docstring"""


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






						def     UpperCAmelCase_      ( self :     str				)    ->						Tuple:
													"""simple docstring"""


													super().test_inference_batch_single_identical(batch_size=2				,							expected_max_diff=3.2_5e-3				)






						def     UpperCAmelCase_      ( self :     List[str]				)    ->						List[str]:
													"""simple docstring"""


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

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

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

													__lowercase      =    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     UpperCAmelCase_      ( self :     Union[str, Any]				)    ->						Union[str, Any]:
													"""simple docstring"""


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

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

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

													__lowercase      =    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     UpperCAmelCase_      ( self :     str				)    ->						List[Any]:
													"""simple docstring"""


													__lowercase      =    '''cpu'''  # ensure determinism for the device-dependent torch.Generator
													__lowercase      =    self.get_dummy_components()
													__lowercase      =    EulerAncestralDiscreteScheduler(
													    beta_start=0.0_0_0_8_5				,							beta_end=0.0_1_2				,							beta_schedule='''scaled_linear'''				)
													__lowercase      =    StableDiffusionPanoramaPipeline(**lowerCamelCase__				)
													__lowercase      =    sd_pipe.to(lowerCamelCase__				)
													sd_pipe.set_progress_bar_config(disable=lowerCamelCase__				)

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

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

													__lowercase      =    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     UpperCAmelCase_      ( self :     str				)    ->						List[Any]:
													"""simple docstring"""


													__lowercase      =    '''cpu'''  # ensure determinism for the device-dependent torch.Generator
													__lowercase      =    self.get_dummy_components()
													__lowercase      =    PNDMScheduler(
													    beta_start=0.0_0_0_8_5				,							beta_end=0.0_1_2				,							beta_schedule='''scaled_linear'''				,							skip_prk_steps=lowerCamelCase__				)
													__lowercase      =    StableDiffusionPanoramaPipeline(**lowerCamelCase__				)
													__lowercase      =    sd_pipe.to(lowerCamelCase__				)
													sd_pipe.set_progress_bar_config(disable=lowerCamelCase__				)

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

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

													__lowercase      =    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 a (     unittest.TestCase  ):
						"""simple docstring"""

						def     UpperCAmelCase_      ( self :     List[Any]				)    ->						Tuple:
													"""simple docstring"""


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






						def     UpperCAmelCase_      ( self :     Optional[Any]				,							lowerCamelCase__ :     Dict=0				)    ->						List[Any]:
													"""simple docstring"""


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






						def     UpperCAmelCase_      ( self :     Optional[int]				)    ->						Optional[int]:
													"""simple docstring"""


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

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

													assert image.shape == (1, 512, 2_048, 3)

													__lowercase      =    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     UpperCAmelCase_      ( self :     int				)    ->						Dict:
													"""simple docstring"""


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

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

													assert image.shape == (1, 512, 2_048, 3)

													__lowercase      =    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     UpperCAmelCase_      ( self :     Union[str, Any]				)    ->						str:
													"""simple docstring"""


													__lowercase      =    0

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

																											__lowercase      =    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:
																											__lowercase      =    latents.detach().cpu().numpy()
																											assert latents.shape == (1, 4, 64, 256)
																											__lowercase      =    latents[0, -3:, -3:, -1]

																											__lowercase      =    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

													__lowercase      =    False

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

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






						def     UpperCAmelCase_      ( self :     List[Any]				)    ->						int:
													"""simple docstring"""


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

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

													__lowercase      =    self.get_inputs()
													__lowercase      =    pipe(**lowerCamelCase__				)

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












# This code is adapted from OpenAI's release
# https://github.com/openai/human-eval/blob/master/human_eval/execution.py

import contextlib
import faulthandler
import io
import multiprocessing
import os
import platform
import signal
import tempfile







def 		_A(       UpperCamelCase__							:			Any				,       UpperCamelCase__							:			int				,       UpperCamelCase__							:			List[Any]				,       UpperCamelCase__							:			int				)    -> List[Any]:
							'''simple docstring'''


							__lowercase      =    multiprocessing.Manager()
							__lowercase      =    manager.list()

							__lowercase      =    multiprocessing.Process(target=UpperCamelCase__				,       args=(check_program, result, timeout)				)
							p.start()
							p.join(timeout=timeout + 1				)
							if p.is_alive():
														p.kill()

							if not result:
														result.append('''timed out'''				)

							return {
							    "task_id": task_id,
							    "passed": result[0] == "passed",
							    "result": result[0],
							    "completion_id": completion_id,
							}







def 		_A(       UpperCamelCase__							:			int				,       UpperCamelCase__							:			List[Any]				,       UpperCamelCase__							:			Optional[int]				)    -> List[Any]:
							'''simple docstring'''


							with create_tempdir():
														# These system calls are needed when cleaning up tempdir.
														import os
														import shutil

														__lowercase      =    shutil.rmtree
														__lowercase      =    os.rmdir
														__lowercase      =    os.chdir

														# Disable functionalities that can make destructive changes to the test.
														reliability_guard()

														# Run program.
														try:
																					__lowercase      =    {}
																					with swallow_io():
																												with time_limit(UpperCamelCase__				):
																																			exec(UpperCamelCase__				,       UpperCamelCase__				)
																					result.append('''passed'''				)
														except TimeoutException:
																					result.append('''timed out'''				)
														except BaseException as e:
																					result.append(F'failed: {e}'				)

														# Needed for cleaning up.
														__lowercase      =    rmtree
														__lowercase      =    rmdir
														__lowercase      =    chdir







@contextlib.contextmanager
def 		_A(       UpperCamelCase__							:			Union[str, Any]				)    -> Optional[int]:
							'''simple docstring'''


							def signal_handler(UpperCamelCase__							:			List[str]				,       UpperCamelCase__							:			Optional[Any]				):
														raise TimeoutException('''Timed out!'''				)

							signal.setitimer(signal.ITIMER_REAL				,       UpperCamelCase__				)
							signal.signal(signal.SIGALRM				,       UpperCamelCase__				)
							try:
														yield
							finally:
														signal.setitimer(signal.ITIMER_REAL				,       0				)







@contextlib.contextmanager
def 		_A(       )    -> Any:
							'''simple docstring'''


							__lowercase      =    WriteOnlyStringIO()
							with contextlib.redirect_stdout(UpperCamelCase__				):
														with contextlib.redirect_stderr(UpperCamelCase__				):
																					with redirect_stdin(UpperCamelCase__				):
																												yield







@contextlib.contextmanager
def 		_A(       )    -> Tuple:
							'''simple docstring'''


							with tempfile.TemporaryDirectory() as dirname:
														with chdir(UpperCamelCase__				):
																					yield dirname







class a (     __SCREAMING_SNAKE_CASE  ):
						"""simple docstring"""

						pass







class a (     io.StringIO  ):
						"""simple docstring"""

						def     UpperCAmelCase_      ( self :     List[str]				,							*lowerCamelCase__ :     str				,							**lowerCamelCase__ :     str				)    ->						Tuple:
													"""simple docstring"""


													raise OSError






						def     UpperCAmelCase_      ( self :     List[str]				,							*lowerCamelCase__ :     List[str]				,							**lowerCamelCase__ :     Dict				)    ->						List[Any]:
													"""simple docstring"""


													raise OSError






						def     UpperCAmelCase_      ( self :     List[str]				,							*lowerCamelCase__ :     Dict				,							**lowerCamelCase__ :     Dict				)    ->						Optional[int]:
													"""simple docstring"""


													raise OSError






						def     UpperCAmelCase_      ( self :     Tuple				,							*lowerCamelCase__ :     Optional[Any]				,							**lowerCamelCase__ :     Tuple				)    ->						Optional[Any]:
													"""simple docstring"""


													return False







class a (     contextlib._RedirectStream  ):  # type: ignore
						"""simple docstring"""

						UpperCamelCase_	:       str       	=		'stdin'







@contextlib.contextmanager
def 		_A(       UpperCamelCase__							:			int				)    -> Any:
							'''simple docstring'''


							if root == ".":
														yield
														return
							__lowercase      =    os.getcwd()
							os.chdir(UpperCamelCase__				)
							try:
														yield
							except BaseException as exc:
														raise exc
							finally:
														os.chdir(UpperCamelCase__				)







def 		_A(       UpperCamelCase__							:			Optional[Any]=None				)    -> Any:
							'''simple docstring'''


							if maximum_memory_bytes is not None:
														import resource

														resource.setrlimit(resource.RLIMIT_AS				,       (maximum_memory_bytes, maximum_memory_bytes)				)
														resource.setrlimit(resource.RLIMIT_DATA				,       (maximum_memory_bytes, maximum_memory_bytes)				)
														if not platform.uname().system == "Darwin":
																					resource.setrlimit(resource.RLIMIT_STACK				,       (maximum_memory_bytes, maximum_memory_bytes)				)

							faulthandler.disable()

							import builtins

							__lowercase      =    None
							__lowercase      =    None

							import os

							__lowercase      =    '''1'''

							__lowercase      =    None
							__lowercase      =    None
							__lowercase      =    None
							__lowercase      =    None
							__lowercase      =    None
							__lowercase      =    None
							__lowercase      =    None
							__lowercase      =    None
							__lowercase      =    None
							__lowercase      =    None
							__lowercase      =    None
							__lowercase      =    None
							__lowercase      =    None
							__lowercase      =    None
							__lowercase      =    None
							__lowercase      =    None
							__lowercase      =    None
							__lowercase      =    None
							__lowercase      =    None
							__lowercase      =    None
							__lowercase      =    None
							__lowercase      =    None
							__lowercase      =    None
							__lowercase      =    None
							__lowercase      =    None
							__lowercase      =    None
							__lowercase      =    None

							import shutil

							__lowercase      =    None
							__lowercase      =    None
							__lowercase      =    None

							import subprocess

							__lowercase      =    None  # type: ignore

							__lowercase      =    None

							import sys

							__lowercase      =    None
							__lowercase      =    None
							__lowercase      =    None
							__lowercase      =    None
							__lowercase      =    None






