



"""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 			_a (					lowerCAmelCase			,							lowerCAmelCase			,							unittest.TestCase):
			"""simple docstring"""
			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  lowercase__						(		self     :    Dict   )->Union[str, Any]:
							torch.manual_seed(0   )
							_UpperCAmelCase					=    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				,   )
							_UpperCAmelCase					=    DDIMScheduler()
							torch.manual_seed(0   )
							_UpperCAmelCase					=    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   )
							_UpperCAmelCase					=    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				,   )
							_UpperCAmelCase					=    CLIPTextModel(__UpperCamelCase   )
							_UpperCAmelCase					=    CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip'''   )

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



			def  lowercase__						(		self     :    int				,   __UpperCamelCase     :    Any				,   __UpperCamelCase     :    Optional[int]=0   )->Tuple:
							_UpperCAmelCase					=    torch.manual_seed(__UpperCamelCase   )
							_UpperCAmelCase					=    {
							    '''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  lowercase__						(		self     :    int   )->Dict:
							_UpperCAmelCase					=    '''cpu'''  # ensure determinism for the device-dependent torch.Generator
							_UpperCAmelCase					=    self.get_dummy_components()
							_UpperCAmelCase					=    StableDiffusionPanoramaPipeline(**__UpperCamelCase   )
							_UpperCAmelCase					=    sd_pipe.to(__UpperCamelCase   )
							sd_pipe.set_progress_bar_config(disable=__UpperCamelCase   )

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

							_UpperCAmelCase					=    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  lowercase__						(		self     :    Any   )->List[Any]:
							super().test_inference_batch_consistent(batch_sizes=[1, 2]   )



			def  lowercase__						(		self     :    Optional[Any]   )->Tuple:
							super().test_inference_batch_single_identical(batch_size=2				,   expected_max_diff=3.25e-3   )



			def  lowercase__						(		self     :    int   )->Optional[int]:
							_UpperCAmelCase					=    '''cpu'''  # ensure determinism for the device-dependent torch.Generator
							_UpperCAmelCase					=    self.get_dummy_components()
							_UpperCAmelCase					=    StableDiffusionPanoramaPipeline(**__UpperCamelCase   )
							_UpperCAmelCase					=    sd_pipe.to(__UpperCamelCase   )
							sd_pipe.set_progress_bar_config(disable=__UpperCamelCase   )

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

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

							_UpperCAmelCase					=    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  lowercase__						(		self     :    Dict   )->Union[str, Any]:
							_UpperCAmelCase					=    '''cpu'''  # ensure determinism for the device-dependent torch.Generator
							_UpperCAmelCase					=    self.get_dummy_components()
							_UpperCAmelCase					=    StableDiffusionPanoramaPipeline(**__UpperCamelCase   )
							_UpperCAmelCase					=    sd_pipe.to(__UpperCamelCase   )
							sd_pipe.set_progress_bar_config(disable=__UpperCamelCase   )

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

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

							_UpperCAmelCase					=    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  lowercase__						(		self     :    Optional[int]   )->Union[str, Any]:
							_UpperCAmelCase					=    '''cpu'''  # ensure determinism for the device-dependent torch.Generator
							_UpperCAmelCase					=    self.get_dummy_components()
							_UpperCAmelCase					=    EulerAncestralDiscreteScheduler(
							    beta_start=0.0_0_0_8_5				,   beta_end=0.0_1_2				,   beta_schedule='''scaled_linear'''   )
							_UpperCAmelCase					=    StableDiffusionPanoramaPipeline(**__UpperCamelCase   )
							_UpperCAmelCase					=    sd_pipe.to(__UpperCamelCase   )
							sd_pipe.set_progress_bar_config(disable=__UpperCamelCase   )

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

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

							_UpperCAmelCase					=    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  lowercase__						(		self     :    str   )->Tuple:
							_UpperCAmelCase					=    '''cpu'''  # ensure determinism for the device-dependent torch.Generator
							_UpperCAmelCase					=    self.get_dummy_components()
							_UpperCAmelCase					=    PNDMScheduler(
							    beta_start=0.0_0_0_8_5				,   beta_end=0.0_1_2				,   beta_schedule='''scaled_linear'''				,   skip_prk_steps=__UpperCamelCase   )
							_UpperCAmelCase					=    StableDiffusionPanoramaPipeline(**__UpperCamelCase   )
							_UpperCAmelCase					=    sd_pipe.to(__UpperCamelCase   )
							sd_pipe.set_progress_bar_config(disable=__UpperCamelCase   )

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

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

							_UpperCAmelCase					=    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  lowercase__						(		self     :    Union[str, Any]   )->List[str]:
							super().tearDown()
							gc.collect()
							torch.cuda.empty_cache()



			def  lowercase__						(		self     :    Any				,   __UpperCamelCase     :    str=0   )->Optional[int]:
							_UpperCAmelCase					=    torch.manual_seed(__UpperCamelCase   )
							_UpperCAmelCase					=    {
							    '''prompt''': '''a photo of the dolomites''',
							    '''generator''': generator,
							    '''num_inference_steps''': 3,
							    '''guidance_scale''': 7.5,
							    '''output_type''': '''numpy''',
							}
							return inputs



			def  lowercase__						(		self     :    Tuple   )->List[Any]:
							_UpperCAmelCase					=    '''stabilityai/stable-diffusion-2-base'''
							_UpperCAmelCase					=    DDIMScheduler.from_pretrained(__UpperCamelCase				,   subfolder='''scheduler'''   )
							_UpperCAmelCase					=    StableDiffusionPanoramaPipeline.from_pretrained(__UpperCamelCase				,   scheduler=__UpperCamelCase				,   safety_checker=__UpperCamelCase   )
							pipe.to(__UpperCamelCase   )
							pipe.set_progress_bar_config(disable=__UpperCamelCase   )
							pipe.enable_attention_slicing()

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

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

							_UpperCAmelCase					=    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  lowercase__						(		self     :    Tuple   )->Union[str, Any]:
							_UpperCAmelCase					=    StableDiffusionPanoramaPipeline.from_pretrained(
							    '''stabilityai/stable-diffusion-2-base'''				,   safety_checker=__UpperCamelCase   )
							_UpperCAmelCase					=    LMSDiscreteScheduler.from_config(pipe.scheduler.config   )
							pipe.to(__UpperCamelCase   )
							pipe.set_progress_bar_config(disable=__UpperCamelCase   )
							pipe.enable_attention_slicing()

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

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

							_UpperCAmelCase					=    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  lowercase__						(		self     :    List[str]   )->Optional[Any]:
							_UpperCAmelCase					=    0

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

															_UpperCAmelCase					=    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:
															_UpperCAmelCase					=    latents.detach().cpu().numpy()
															assert latents.shape == (1, 4, 6_4, 2_5_6)
															_UpperCAmelCase					=    latents[0, -3:, -3:, -1]

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

							_UpperCAmelCase					=    False

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

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



			def  lowercase__						(		self     :    Union[str, Any]   )->Dict:
							torch.cuda.empty_cache()
							torch.cuda.reset_max_memory_allocated()
							torch.cuda.reset_peak_memory_stats()

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

							_UpperCAmelCase					=    self.get_inputs()
							_UpperCAmelCase					=    pipe(**__UpperCamelCase   )

							_UpperCAmelCase					=    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 typing import Optional

from .. import Features, NamedSplit
from ..packaged_modules.text.text import Text
from ..utils.typing import NestedDataStructureLike, PathLike
from .abc import AbstractDatasetReader
class 			_a (					lowerCAmelCase):
			"""simple docstring"""



			def __init__(		self     :    List[str]				,   __UpperCamelCase     :    NestedDataStructureLike[PathLike]				,   __UpperCamelCase     :    Optional[NamedSplit] = None				,   __UpperCamelCase     :    Optional[Features] = None				,   __UpperCamelCase     :    str = None				,   __UpperCamelCase     :    bool = False				,   __UpperCamelCase     :    bool = False				,   __UpperCamelCase     :    Optional[int] = None				,   **__UpperCamelCase     :    Optional[Any]				,   )->Any:
							super().__init__(
							    __UpperCamelCase				,   split=__UpperCamelCase				,   features=__UpperCamelCase				,   cache_dir=__UpperCamelCase				,   keep_in_memory=__UpperCamelCase				,   streaming=__UpperCamelCase				,   num_proc=__UpperCamelCase				,   **__UpperCamelCase				,   )
							_UpperCAmelCase					=    path_or_paths if isinstance(__UpperCamelCase				,   __UpperCamelCase   ) else {self.split: path_or_paths}
							_UpperCAmelCase					=    Text(
							    cache_dir=__UpperCamelCase				,   data_files=__UpperCamelCase				,   features=__UpperCamelCase				,   **__UpperCamelCase				,   )



			def  lowercase__						(		self     :    Optional[Any]   )->str:
							# Build iterable dataset
							if self.streaming:
											_UpperCAmelCase					=    self.builder.as_streaming_dataset(split=self.split   )
							# Build regular (map-style) dataset
							else:
											_UpperCAmelCase					=    None
											_UpperCAmelCase					=    None
											_UpperCAmelCase					=    None
											_UpperCAmelCase					=    None

											self.builder.download_and_prepare(
											    download_config=__UpperCamelCase				,   download_mode=__UpperCamelCase				,   verification_mode=__UpperCamelCase				,   base_path=__UpperCamelCase				,   num_proc=self.num_proc				,   )
											_UpperCAmelCase					=    self.builder.as_dataset(
											    split=self.split				,   verification_mode=__UpperCamelCase				,   in_memory=self.keep_in_memory   )
							return dataset



