





"""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     ):





 """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 					UpperCamelCase__(    self  ):



     '''simple docstring'''




     torch.manual_seed(0  )
     __A    :						List[str]						 =     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					,						)
     __A    :						List[Any]						 =     DDIMScheduler()
     torch.manual_seed(0  )
     __A    :						List[Any]						 =     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  )
     __A    :						Any						 =     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=1000					,						)
     __A    :						List[Any]						 =     CLIPTextModel(lowercase_  )
     __A    :						Dict						 =     CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip'''  )

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

 def 					UpperCamelCase__(    self					,						__lowerCamelCase					,						__lowerCamelCase=0  ):



     '''simple docstring'''




     __A    :						Optional[int]						 =     torch.manual_seed(lowercase_  )
     __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 					UpperCamelCase__(    self  ):



     '''simple docstring'''




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

     __A    :						Optional[Any]						 =     self.get_dummy_inputs(lowercase_  )
     __A    :						Optional[int]						 =     sd_pipe(**lowercase_  ).images
     __A    :						List[str]						 =     image[0, -3:, -3:, -1]
     assert image.shape == (1, 64, 64, 3)

     __A    :						int						 =     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  ):



     '''simple docstring'''




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

 def 					UpperCamelCase__(    self  ):



     '''simple docstring'''




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

 def 					UpperCamelCase__(    self  ):



     '''simple docstring'''




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

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

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

     __A    :						Dict						 =     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  ):



     '''simple docstring'''




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

     __A    :						Optional[int]						 =     self.get_dummy_inputs(lowercase_  )
     __A    :						Union[str, Any]						 =     sd_pipe(**lowercase_					,						view_batch_size=2  )
     __A    :						Tuple						 =     output.images
     __A    :						List[Any]						 =     image[0, -3:, -3:, -1]

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

     __A    :						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 					UpperCamelCase__(    self  ):



     '''simple docstring'''




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

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

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

     __A    :						Optional[int]						 =     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  ):



     '''simple docstring'''




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

     __A    :						List[Any]						 =     self.get_dummy_inputs(lowercase_  )
     __A    :						Dict						 =     sd_pipe(**lowercase_  ).images
     __A    :						Union[str, Any]						 =     image[0, -3:, -3:, -1]

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

     __A    :						List[Any]						 =     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 		__snake_case					(		unittest.TestCase     ):





 """simple docstring"""


 def 					UpperCamelCase__(    self  ):



     '''simple docstring'''




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

 def 					UpperCamelCase__(    self					,						__lowerCamelCase=0  ):



     '''simple docstring'''




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

 def 					UpperCamelCase__(    self  ):



     '''simple docstring'''




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

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

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

     __A    :						Dict						 =     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  ):



     '''simple docstring'''




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

     __A    :						Dict						 =     self.get_inputs()
     __A    :						int						 =     pipe(**lowercase_  ).images
     __A    :						List[Any]						 =     image[0, -3:, -3:, -1].flatten()

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

     __A    :						Tuple						 =     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  ):



     '''simple docstring'''




     __A    :						Union[str, Any]						 =     0

     def callback_fn(__lowerCamelCase					,						__lowerCamelCase					,						__lowerCamelCase  ) -> None:
         __A    :						Dict						 =     True
         nonlocal number_of_steps
         number_of_steps += 1
         if step == 1:
             __A    :						Optional[int]						 =     latents.detach().cpu().numpy()
             assert latents.shape == (1, 4, 64, 256)
             __A    :						Union[str, Any]						 =     latents[0, -3:, -3:, -1]

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

             __A    :						List[Any]						 =     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

     __A    :						int						 =     False

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

     __A    :						Union[str, Any]						 =     self.get_inputs()
     pipe(**lowercase_					,						callback=lowercase_					,						callback_steps=1  )
     assert callback_fn.has_been_called
     assert number_of_steps == 3







 def 					UpperCamelCase__(    self  ):



     '''simple docstring'''




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

     __A    :						Tuple						 =     '''stabilityai/stable-diffusion-2-base'''
     __A    :						Optional[Any]						 =     DDIMScheduler.from_pretrained(lowercase_					,						subfolder='''scheduler'''  )
     __A    :						Union[str, Any]						 =     StableDiffusionPanoramaPipeline.from_pretrained(lowercase_					,						scheduler=lowercase_					,						safety_checker=lowercase_  )
     __A    :						Dict						 =     pipe.to(lowercase_  )
     pipe.set_progress_bar_config(disable=lowercase_  )
     pipe.enable_attention_slicing(1  )
     pipe.enable_sequential_cpu_offload()

     __A    :						int						 =     self.get_inputs()
     __A    :						Dict						 =     pipe(**lowercase_  )

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







from argparse import ArgumentParser

from datasets.commands.convert import ConvertCommand
from datasets.commands.dummy_data import DummyDataCommand
from datasets.commands.env import EnvironmentCommand
from datasets.commands.run_beam import RunBeamCommand
from datasets.commands.test import TestCommand
from datasets.utils.logging import set_verbosity_info
def 						_snake_case(    SCREAMING_SNAKE_CASE__			:	Tuple      )							->      Tuple:





    '''simple docstring'''






    return {key.lstrip('-'      ): value for key, value in zip(unknown_args[::2]    ,			unknown_args[1::2]      )}
def 						_snake_case(    )							->      Dict:





    '''simple docstring'''






    A__          =   ArgumentParser(
        'HuggingFace Datasets CLI tool'    ,			usage='datasets-cli <command> [<args>]'    ,			allow_abbrev=SCREAMING_SNAKE_CASE__      )
    A__          =   parser.add_subparsers(help='datasets-cli command helpers'      )
    set_verbosity_info()

    # Register commands
    ConvertCommand.register_subcommand(SCREAMING_SNAKE_CASE__      )
    EnvironmentCommand.register_subcommand(SCREAMING_SNAKE_CASE__      )
    TestCommand.register_subcommand(SCREAMING_SNAKE_CASE__      )
    RunBeamCommand.register_subcommand(SCREAMING_SNAKE_CASE__      )
    DummyDataCommand.register_subcommand(SCREAMING_SNAKE_CASE__      )

    # Parse args
    A__      ,						A__          =   parser.parse_known_args()
    if not hasattr(SCREAMING_SNAKE_CASE__    ,			'func'      ):
        parser.print_help()
        exit(1      )
    A__          =   parse_unknown_args(SCREAMING_SNAKE_CASE__      )

    # Run
    A__          =   args.func(SCREAMING_SNAKE_CASE__    ,			**SCREAMING_SNAKE_CASE__      )
    service.run()


if __name__ == "__main__":
     main()

