


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   _lowerCamelCase (					UpperCamelCase					,							UpperCamelCase					,							unittest.TestCase			):




       """simple docstring"""
       snake_case      =    StableDiffusionPanoramaPipeline
       snake_case      =    TEXT_TO_IMAGE_PARAMS
       snake_case      =    TEXT_TO_IMAGE_BATCH_PARAMS
       snake_case      =    TEXT_TO_IMAGE_IMAGE_PARAMS
       snake_case      =    TEXT_TO_IMAGE_IMAGE_PARAMS



       def        _snake_case       (      self		)->Union[str, Any]:




         '''simple docstring'''





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

         A_      :				List[str]		     =					{
             '''unet''': unet,
             '''scheduler''': scheduler,
             '''vae''': vae,
             '''text_encoder''': text_encoder,
             '''tokenizer''': tokenizer,
             '''safety_checker''': None,
             '''feature_extractor''': None,
         }
         return components



       def        _snake_case       (      self				,       _SCREAMING_SNAKE_CASE				,       _SCREAMING_SNAKE_CASE=0		)->Optional[int]:




         '''simple docstring'''





         A_      :				Optional[Any]		     =					torch.manual_seed(_SCREAMING_SNAKE_CASE		)
         A_      :				Dict		     =					{
             '''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        _snake_case       (      self		)->List[str]:




         '''simple docstring'''





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

         A_      :				List[Any]		     =					self.get_dummy_inputs(_SCREAMING_SNAKE_CASE		)
         A_      :				Tuple		     =					sd_pipe(**_SCREAMING_SNAKE_CASE		).images
         A_      :				Any		     =					image[0, -3:, -3:, -1]
         assert image.shape == (1, 64, 64, 3)

         A_      :				Any		     =					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        _snake_case       (      self		)->Dict:




         '''simple docstring'''





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



       def        _snake_case       (      self		)->Optional[Any]:




         '''simple docstring'''





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



       def        _snake_case       (      self		)->str:




         '''simple docstring'''





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

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

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

         A_      :				Union[str, Any]		     =					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        _snake_case       (      self		)->Dict:




         '''simple docstring'''





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

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

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

         A_      :				Optional[int]		     =					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        _snake_case       (      self		)->Optional[Any]:




         '''simple docstring'''





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

         A_      :				Dict		     =					self.get_dummy_inputs(_SCREAMING_SNAKE_CASE		)
         A_      :				str		     =					sd_pipe(**_SCREAMING_SNAKE_CASE		).images
         A_      :				Tuple		     =					image[0, -3:, -3:, -1]

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

         A_      :				List[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        _snake_case       (      self		)->str:




         '''simple docstring'''





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

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

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

         A_      :				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   _lowerCamelCase (					unittest.TestCase			):




       """simple docstring"""



       def        _snake_case       (      self		)->str:




         '''simple docstring'''





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



       def        _snake_case       (      self				,       _SCREAMING_SNAKE_CASE=0		)->int:




         '''simple docstring'''





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



       def        _snake_case       (      self		)->Any:




         '''simple docstring'''





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

         A_      :				str		     =					self.get_inputs()
         A_      :				List[str]		     =					pipe(**_SCREAMING_SNAKE_CASE		).images
         A_      :				Tuple		     =					image[0, -3:, -3:, -1].flatten()

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

         A_      :				List[str]		     =					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        _snake_case       (      self		)->Optional[int]:




         '''simple docstring'''





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

         A_      :				Union[str, Any]		     =					self.get_inputs()
         A_      :				Dict		     =					pipe(**_SCREAMING_SNAKE_CASE		).images
         A_      :				Any		     =					image[0, -3:, -3:, -1].flatten()

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

         A_      :				Optional[int]		     =					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        _snake_case       (      self		)->Optional[int]:




         '''simple docstring'''





         A_      :				List[str]		     =					0

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

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

             A_      :				Tuple		     =					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_      :				int		     =					'''stabilityai/stable-diffusion-2-base'''
         A_      :				str		     =					DDIMScheduler.from_pretrained(_SCREAMING_SNAKE_CASE				,       subfolder='''scheduler'''		)
         A_      :				str		     =					StableDiffusionPanoramaPipeline.from_pretrained(_SCREAMING_SNAKE_CASE				,       scheduler=_SCREAMING_SNAKE_CASE				,       safety_checker=_SCREAMING_SNAKE_CASE		)
         A_      :				Optional[int]		     =					pipe.to(_SCREAMING_SNAKE_CASE		)
         pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE		)
         pipe.enable_attention_slicing()

         A_      :				Optional[int]		     =					self.get_inputs()
         pipe(**_SCREAMING_SNAKE_CASE				,       callback=_SCREAMING_SNAKE_CASE				,       callback_steps=1		)
         assert callback_fn.has_been_called
         assert number_of_steps == 3







       def        _snake_case       (      self		)->List[str]:




         '''simple docstring'''





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

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

         A_      :				int		     =					self.get_inputs()
         A_      :				List[Any]		     =					pipe(**_SCREAMING_SNAKE_CASE		)

         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 typing import TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_tf_available,
    is_torch_available,
    is_vision_available,
)


UpperCamelCase								=	{
    """configuration_mobilevit""": ["""MOBILEVIT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """MobileViTConfig""", """MobileViTOnnxConfig"""],
}

try:
     if not is_vision_available():
          raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
     pass
else:
     UpperCamelCase								=	["""MobileViTFeatureExtractor"""]
     UpperCamelCase								=	["""MobileViTImageProcessor"""]

try:
     if not is_torch_available():
          raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
     pass
else:
     UpperCamelCase								=	[
         """MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST""",
         """MobileViTForImageClassification""",
         """MobileViTForSemanticSegmentation""",
         """MobileViTModel""",
         """MobileViTPreTrainedModel""",
     ]

try:
     if not is_tf_available():
          raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
     pass
else:
     UpperCamelCase								=	[
         """TF_MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST""",
         """TFMobileViTForImageClassification""",
         """TFMobileViTForSemanticSegmentation""",
         """TFMobileViTModel""",
         """TFMobileViTPreTrainedModel""",
     ]

if TYPE_CHECKING:
     from .configuration_mobilevit import MOBILEVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, MobileViTConfig, MobileViTOnnxConfig

     try:
          if not is_vision_available():
               raise OptionalDependencyNotAvailable()
     except OptionalDependencyNotAvailable:
          pass
     else:
          from .feature_extraction_mobilevit import MobileViTFeatureExtractor
          from .image_processing_mobilevit import MobileViTImageProcessor

     try:
          if not is_torch_available():
               raise OptionalDependencyNotAvailable()
     except OptionalDependencyNotAvailable:
          pass
     else:
          from .modeling_mobilevit import (
              MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST,
              MobileViTForImageClassification,
              MobileViTForSemanticSegmentation,
              MobileViTModel,
              MobileViTPreTrainedModel,
          )

     try:
          if not is_tf_available():
               raise OptionalDependencyNotAvailable()
     except OptionalDependencyNotAvailable:
          pass
     else:
          from .modeling_tf_mobilevit import (
              TF_MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST,
              TFMobileViTForImageClassification,
              TFMobileViTForSemanticSegmentation,
              TFMobileViTModel,
              TFMobileViTPreTrainedModel,
          )


else:
     import sys

     UpperCamelCase								=	_LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)




