





from typing import Dict

import numpy as np

from ..utils import add_end_docstrings, is_tf_available, is_torch_available, logging
from .base import PIPELINE_INIT_ARGS, GenericTensor, Pipeline, PipelineException


if is_tf_available():
       import tensorflow as tf

       from ..tf_utils import stable_softmax


if is_torch_available():
       import torch


UpperCamelCase__      =logging.get_logger(__name__)





@add_end_docstrings(
    __UpperCAmelCase  ,     R'\n        top_k (`int`, defaults to 5):\n            The number of predictions to return.\n        targets (`str` or `List[str]`, *optional*):\n            When passed, the model will limit the scores to the passed targets instead of looking up in the whole\n            vocab. If the provided targets are not in the model vocab, they will be tokenized and the first resulting\n            token will be used (with a warning, and that might be slower).\n\n    '  ,     )
class 			lowerCAmelCase__( __UpperCAmelCase    ):






       '''simple docstring'''


       def     UpperCamelCase_			(      self    ,						__lowerCamelCase							)			->     Any:

            if self.framework == "tf":
                 _SCREAMING_SNAKE_CASE       :	Optional[Any]						    =							tf.where(input_ids == self.tokenizer.mask_token_id							).numpy()
            elif self.framework == "pt":
                 _SCREAMING_SNAKE_CASE       :	Optional[int]						    =							torch.nonzero(input_ids == self.tokenizer.mask_token_id    ,						as_tuple=__SCREAMING_SNAKE_CASE							)
            else:
                 raise ValueError("Unsupported framework"							)
            return masked_index




       def     UpperCamelCase_			(      self    ,						__lowerCamelCase							)			->     List[Any]:
            _SCREAMING_SNAKE_CASE       :	Dict						    =							self.get_masked_index(__SCREAMING_SNAKE_CASE							)
            _SCREAMING_SNAKE_CASE       :	str						    =							np.prod(masked_index.shape							)
            if numel < 1:
                 raise PipelineException(
                     "fill-mask"    ,						self.model.base_model_prefix    ,						F"""No mask_token ({self.tokenizer.mask_token}) found on the input"""    ,						)




       def     UpperCamelCase_			(      self    ,						__lowerCamelCase							)			->     Optional[int]:

            if isinstance(__SCREAMING_SNAKE_CASE    ,						__SCREAMING_SNAKE_CASE							):
                 for model_input in model_inputs:
                      self._ensure_exactly_one_mask_token(model_input["input_ids"][0]							)
            else:
                 for input_ids in model_inputs["input_ids"]:
                      self._ensure_exactly_one_mask_token(__SCREAMING_SNAKE_CASE							)




       def     UpperCamelCase_			(      self    ,						__lowerCamelCase    ,						__lowerCamelCase=None    ,						**__lowerCamelCase							)			->     Dict:

            if return_tensors is None:
                 _SCREAMING_SNAKE_CASE       :	Dict						    =							self.framework
            _SCREAMING_SNAKE_CASE       :	Tuple						    =							self.tokenizer(__SCREAMING_SNAKE_CASE    ,						return_tensors=__SCREAMING_SNAKE_CASE							)
            self.ensure_exactly_one_mask_token(__SCREAMING_SNAKE_CASE							)
            return model_inputs




       def     UpperCamelCase_			(      self    ,						__lowerCamelCase							)			->     Optional[Any]:
            _SCREAMING_SNAKE_CASE       :	Tuple						    =							self.model(**__SCREAMING_SNAKE_CASE							)
            _SCREAMING_SNAKE_CASE       :	Tuple						    =							model_inputs["input_ids"]
            return model_outputs




       def     UpperCamelCase_			(      self    ,						__lowerCamelCase    ,						__lowerCamelCase=5    ,						__lowerCamelCase=None							)			->     Optional[Any]:

            if target_ids is not None and target_ids.shape[0] < top_k:
                 _SCREAMING_SNAKE_CASE       :	Dict						    =							target_ids.shape[0]
            _SCREAMING_SNAKE_CASE       :	Optional[Any]						    =							model_outputs["input_ids"][0]
            _SCREAMING_SNAKE_CASE       :	List[str]						    =							model_outputs["logits"]

            if self.framework == "tf":
                 _SCREAMING_SNAKE_CASE       :	Tuple						    =							tf.where(input_ids == self.tokenizer.mask_token_id							).numpy()[:, 0]

                 _SCREAMING_SNAKE_CASE       :	Union[str, Any]						    =							outputs.numpy()

                 _SCREAMING_SNAKE_CASE       :	str						    =							outputs[0, masked_index, :]
                 _SCREAMING_SNAKE_CASE       :	Tuple						    =							stable_softmax(__SCREAMING_SNAKE_CASE    ,						axis=-1							)
                 if target_ids is not None:
                      _SCREAMING_SNAKE_CASE       :	Any						    =							tf.gather_nd(tf.squeeze(__SCREAMING_SNAKE_CASE    ,						0							)    ,						target_ids.reshape(-1    ,						1							)							)
                      _SCREAMING_SNAKE_CASE       :	Union[str, Any]						    =							tf.expand_dims(__SCREAMING_SNAKE_CASE    ,						0							)

                 _SCREAMING_SNAKE_CASE       :	Optional[int]						    =							tf.math.top_k(__SCREAMING_SNAKE_CASE    ,						k=__SCREAMING_SNAKE_CASE							)
                 _SCREAMING_SNAKE_CASE    ,			_SCREAMING_SNAKE_CASE       :	List[str]						    =							topk.values.numpy(), topk.indices.numpy()
            else:
                 _SCREAMING_SNAKE_CASE       :	Optional[int]						    =							torch.nonzero(input_ids == self.tokenizer.mask_token_id    ,						as_tuple=__SCREAMING_SNAKE_CASE							).squeeze(-1							)
                 # Fill mask pipeline supports only one ${mask_token} per sample

                 _SCREAMING_SNAKE_CASE       :	Dict						    =							outputs[0, masked_index, :]
                 _SCREAMING_SNAKE_CASE       :	List[Any]						    =							logits.softmax(dim=-1							)
                 if target_ids is not None:
                      _SCREAMING_SNAKE_CASE       :	Dict						    =							probs[..., target_ids]

                 _SCREAMING_SNAKE_CASE    ,			_SCREAMING_SNAKE_CASE       :	Any						    =							probs.topk(__SCREAMING_SNAKE_CASE							)

            _SCREAMING_SNAKE_CASE       :	Union[str, Any]						    =							[]
            _SCREAMING_SNAKE_CASE       :	str						    =							values.shape[0] == 1
            for i, (_values, _predictions) in enumerate(zip(values.tolist()    ,						predictions.tolist()							)							):
                 _SCREAMING_SNAKE_CASE       :	List[str]						    =							[]
                 for v, p in zip(_values    ,						_predictions							):
                      # Copy is important since we're going to modify this array in place
                      _SCREAMING_SNAKE_CASE       :	Tuple						    =							input_ids.numpy().copy()
                      if target_ids is not None:
                           _SCREAMING_SNAKE_CASE       :	Optional[int]						    =							target_ids[p].tolist()

                      _SCREAMING_SNAKE_CASE       :	str						    =							p
                      # Filter padding out:
                      _SCREAMING_SNAKE_CASE       :	Optional[int]						    =							tokens[np.where(tokens != self.tokenizer.pad_token_id							)]
                      # Originally we skip special tokens to give readable output.
                      # For multi masks though, the other [MASK] would be removed otherwise
                      # making the output look odd, so we add them back
                      _SCREAMING_SNAKE_CASE       :	int						    =							self.tokenizer.decode(__SCREAMING_SNAKE_CASE    ,						skip_special_tokens=__SCREAMING_SNAKE_CASE							)
                      _SCREAMING_SNAKE_CASE       :	Optional[Any]						    =							{"score": v, "token": p, "token_str": self.tokenizer.decode([p]							), "sequence": sequence}
                      row.append(__SCREAMING_SNAKE_CASE							)
                 result.append(__SCREAMING_SNAKE_CASE							)
            if single_mask:
                 return result[0]
            return result




       def     UpperCamelCase_			(      self    ,						__lowerCamelCase    ,						__lowerCamelCase=None							)			->     Union[str, Any]:

            if isinstance(__SCREAMING_SNAKE_CASE    ,						__SCREAMING_SNAKE_CASE							):
                 _SCREAMING_SNAKE_CASE       :	Optional[int]						    =							[targets]
            try:
                 _SCREAMING_SNAKE_CASE       :	str						    =							self.tokenizer.get_vocab()
            except Exception:
                 _SCREAMING_SNAKE_CASE       :	List[str]						    =							{}
            _SCREAMING_SNAKE_CASE       :	int						    =							[]
            for target in targets:
                 _SCREAMING_SNAKE_CASE       :	Optional[Any]						    =							vocab.get(__SCREAMING_SNAKE_CASE    ,						__SCREAMING_SNAKE_CASE							)
                 if id_ is None:
                      _SCREAMING_SNAKE_CASE       :	Tuple						    =							self.tokenizer(
                          __SCREAMING_SNAKE_CASE    ,						add_special_tokens=__SCREAMING_SNAKE_CASE    ,						return_attention_mask=__SCREAMING_SNAKE_CASE    ,						return_token_type_ids=__SCREAMING_SNAKE_CASE    ,						max_length=1    ,						truncation=__SCREAMING_SNAKE_CASE    ,						)["input_ids"]
                      if len(__SCREAMING_SNAKE_CASE							) == 0:
                           logger.warning(
                               F"""The specified target token `{target}` does not exist in the model vocabulary. """
                               "We cannot replace it with anything meaningful, ignoring it"							)
                           continue
                      _SCREAMING_SNAKE_CASE       :	Union[str, Any]						    =							input_ids[0]
                      # XXX: If users encounter this pass
                      # it becomes pretty slow, so let's make sure
                      # The warning enables them to fix the input to
                      # get faster performance.
                      logger.warning(
                          F"""The specified target token `{target}` does not exist in the model vocabulary. """
                          F"""Replacing with `{self.tokenizer.convert_ids_to_tokens(id_							)}`."""							)
                 target_ids.append(id_							)
            _SCREAMING_SNAKE_CASE       :	int						    =							list(set(__SCREAMING_SNAKE_CASE							)							)
            if len(__SCREAMING_SNAKE_CASE							) == 0:
                 raise ValueError("At least one target must be provided when passed."							)
            _SCREAMING_SNAKE_CASE       :	Tuple						    =							np.array(__SCREAMING_SNAKE_CASE							)
            return target_ids




       def     UpperCamelCase_			(      self    ,						__lowerCamelCase=None    ,						__lowerCamelCase=None							)			->     Optional[int]:
            _SCREAMING_SNAKE_CASE       :	List[Any]						    =							{}

            if targets is not None:
                 _SCREAMING_SNAKE_CASE       :	List[str]						    =							self.get_target_ids(__SCREAMING_SNAKE_CASE    ,						__SCREAMING_SNAKE_CASE							)
                 _SCREAMING_SNAKE_CASE       :	Dict						    =							target_ids

            if top_k is not None:
                 _SCREAMING_SNAKE_CASE       :	Any						    =							top_k

            if self.tokenizer.mask_token_id is None:
                 raise PipelineException(
                     "fill-mask"    ,						self.model.base_model_prefix    ,						"The tokenizer does not define a `mask_token`."							)
            return {}, {}, postprocess_params







       def __call__(      self    ,						__lowerCamelCase    ,						*__lowerCamelCase    ,						**__lowerCamelCase							)			->     Dict:
            _SCREAMING_SNAKE_CASE       :	List[Any]						    =							super().__call__(__SCREAMING_SNAKE_CASE    ,						**__SCREAMING_SNAKE_CASE							)
            if isinstance(__SCREAMING_SNAKE_CASE    ,						__SCREAMING_SNAKE_CASE							) and len(__SCREAMING_SNAKE_CASE							) == 1:
                 return outputs[0]
            return outputs









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__( __lowercase  ,     __lowercase  ,     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     UpperCamelCase_			(      self							)			->     Any:
            torch.manual_seed(0							)
            _SCREAMING_SNAKE_CASE       :	Tuple						    =							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    ,						)
            _SCREAMING_SNAKE_CASE       :	Optional[Any]						    =							DDIMScheduler()
            torch.manual_seed(0							)
            _SCREAMING_SNAKE_CASE       :	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							)
            _SCREAMING_SNAKE_CASE       :	int						    =							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    ,						)
            _SCREAMING_SNAKE_CASE       :	Union[str, Any]						    =							CLIPTextModel(__lowerCamelCase							)
            _SCREAMING_SNAKE_CASE       :	int						    =							CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip"							)

            _SCREAMING_SNAKE_CASE       :	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							)			->     Union[str, Any]:
            _SCREAMING_SNAKE_CASE       :	List[Any]						    =							torch.manual_seed(__lowerCamelCase							)
            _SCREAMING_SNAKE_CASE       :	List[str]						    =							{
                "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							)			->     Dict:
            _SCREAMING_SNAKE_CASE       :	Any						    =							"cpu"  # ensure determinism for the device-dependent torch.Generator
            _SCREAMING_SNAKE_CASE       :	Any						    =							self.get_dummy_components()
            _SCREAMING_SNAKE_CASE       :	int						    =							StableDiffusionPanoramaPipeline(**__lowerCamelCase							)
            _SCREAMING_SNAKE_CASE       :	Union[str, Any]						    =							sd_pipe.to(__lowerCamelCase							)
            sd_pipe.set_progress_bar_config(disable=__lowerCamelCase							)

            _SCREAMING_SNAKE_CASE       :	int						    =							self.get_dummy_inputs(__lowerCamelCase							)
            _SCREAMING_SNAKE_CASE       :	Any						    =							sd_pipe(**__lowerCamelCase							).images
            _SCREAMING_SNAKE_CASE       :	List[Any]						    =							image[0, -3:, -3:, -1]
            assert image.shape == (1, 6_4, 6_4, 3)

            _SCREAMING_SNAKE_CASE       :	Union[str, Any]						    =							np.array([0.6186, 0.5374, 0.4915, 0.4135, 0.4114, 0.4563, 0.5128, 0.4977, 0.4757]							)

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




       def     UpperCamelCase_			(      self							)			->     Union[str, Any]:
            super().test_inference_batch_consistent(batch_sizes=[1, 2]							)




       def     UpperCamelCase_			(      self							)			->     List[str]:
            super().test_inference_batch_single_identical(batch_size=2    ,						expected_max_diff=3.25E-3							)




       def     UpperCamelCase_			(      self							)			->     Dict:
            _SCREAMING_SNAKE_CASE       :	List[str]						    =							"cpu"  # ensure determinism for the device-dependent torch.Generator
            _SCREAMING_SNAKE_CASE       :	List[Any]						    =							self.get_dummy_components()
            _SCREAMING_SNAKE_CASE       :	Any						    =							StableDiffusionPanoramaPipeline(**__lowerCamelCase							)
            _SCREAMING_SNAKE_CASE       :	Optional[int]						    =							sd_pipe.to(__lowerCamelCase							)
            sd_pipe.set_progress_bar_config(disable=__lowerCamelCase							)

            _SCREAMING_SNAKE_CASE       :	int						    =							self.get_dummy_inputs(__lowerCamelCase							)
            _SCREAMING_SNAKE_CASE       :	str						    =							"french fries"
            _SCREAMING_SNAKE_CASE       :	str						    =							sd_pipe(**__lowerCamelCase    ,						negative_prompt=__lowerCamelCase							)
            _SCREAMING_SNAKE_CASE       :	int						    =							output.images
            _SCREAMING_SNAKE_CASE       :	str						    =							image[0, -3:, -3:, -1]

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

            _SCREAMING_SNAKE_CASE       :	Optional[int]						    =							np.array([0.6187, 0.5375, 0.4915, 0.4136, 0.4114, 0.4563, 0.5128, 0.4976, 0.4757]							)

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




       def     UpperCamelCase_			(      self							)			->     str:
            _SCREAMING_SNAKE_CASE       :	Any						    =							"cpu"  # ensure determinism for the device-dependent torch.Generator
            _SCREAMING_SNAKE_CASE       :	List[Any]						    =							self.get_dummy_components()
            _SCREAMING_SNAKE_CASE       :	Dict						    =							StableDiffusionPanoramaPipeline(**__lowerCamelCase							)
            _SCREAMING_SNAKE_CASE       :	Tuple						    =							sd_pipe.to(__lowerCamelCase							)
            sd_pipe.set_progress_bar_config(disable=__lowerCamelCase							)

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

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

            _SCREAMING_SNAKE_CASE       :	List[Any]						    =							np.array([0.6187, 0.5375, 0.4915, 0.4136, 0.4114, 0.4563, 0.5128, 0.4976, 0.4757]							)

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




       def     UpperCamelCase_			(      self							)			->     int:
            _SCREAMING_SNAKE_CASE       :	List[Any]						    =							"cpu"  # ensure determinism for the device-dependent torch.Generator
            _SCREAMING_SNAKE_CASE       :	int						    =							self.get_dummy_components()
            _SCREAMING_SNAKE_CASE       :	Tuple						    =							EulerAncestralDiscreteScheduler(
                beta_start=0.0_0085    ,						beta_end=0.012    ,						beta_schedule="scaled_linear"							)
            _SCREAMING_SNAKE_CASE       :	Optional[int]						    =							StableDiffusionPanoramaPipeline(**__lowerCamelCase							)
            _SCREAMING_SNAKE_CASE       :	List[Any]						    =							sd_pipe.to(__lowerCamelCase							)
            sd_pipe.set_progress_bar_config(disable=__lowerCamelCase							)

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

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

            _SCREAMING_SNAKE_CASE       :	Any						    =							np.array([0.4024, 0.6510, 0.4901, 0.5378, 0.5813, 0.5622, 0.4795, 0.4467, 0.4952]							)

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







       def     UpperCamelCase_			(      self							)			->     int:
            _SCREAMING_SNAKE_CASE       :	Dict						    =							"cpu"  # ensure determinism for the device-dependent torch.Generator
            _SCREAMING_SNAKE_CASE       :	int						    =							self.get_dummy_components()
            _SCREAMING_SNAKE_CASE       :	List[str]						    =							PNDMScheduler(
                beta_start=0.0_0085    ,						beta_end=0.012    ,						beta_schedule="scaled_linear"    ,						skip_prk_steps=__lowerCamelCase							)
            _SCREAMING_SNAKE_CASE       :	Optional[int]						    =							StableDiffusionPanoramaPipeline(**__lowerCamelCase							)
            _SCREAMING_SNAKE_CASE       :	int						    =							sd_pipe.to(__lowerCamelCase							)
            sd_pipe.set_progress_bar_config(disable=__lowerCamelCase							)

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

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

            _SCREAMING_SNAKE_CASE       :	Union[str, Any]						    =							np.array([0.6391, 0.6291, 0.4861, 0.5134, 0.5552, 0.4578, 0.5032, 0.5023, 0.4539]							)

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





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






       '''simple docstring'''


       def     UpperCamelCase_			(      self							)			->     List[Any]:
            super().tearDown()
            gc.collect()
            torch.cuda.empty_cache()




       def     UpperCamelCase_			(      self    ,						__lowerCamelCase=0							)			->     int:
            _SCREAMING_SNAKE_CASE       :	List[str]						    =							torch.manual_seed(__lowerCamelCase							)
            _SCREAMING_SNAKE_CASE       :	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							)			->     Union[str, Any]:
            _SCREAMING_SNAKE_CASE       :	int						    =							"stabilityai/stable-diffusion-2-base"
            _SCREAMING_SNAKE_CASE       :	Any						    =							DDIMScheduler.from_pretrained(__lowerCamelCase    ,						subfolder="scheduler"							)
            _SCREAMING_SNAKE_CASE       :	Any						    =							StableDiffusionPanoramaPipeline.from_pretrained(__lowerCamelCase    ,						scheduler=__lowerCamelCase    ,						safety_checker=__lowerCamelCase							)
            pipe.to(__lowerCamelCase							)
            pipe.set_progress_bar_config(disable=__lowerCamelCase							)
            pipe.enable_attention_slicing()

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

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

            _SCREAMING_SNAKE_CASE       :	List[str]						    =							np.array(
                [
                    0.3696_8392,
                    0.2702_5372,
                    0.3244_6766,
                    0.2837_9387,
                    0.3636_3274,
                    0.3073_3347,
                    0.2710_0027,
                    0.2705_4125,
                    0.2553_6096,
                ]							)

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




       def     UpperCamelCase_			(      self							)			->     Optional[int]:
            _SCREAMING_SNAKE_CASE       :	Dict						    =							StableDiffusionPanoramaPipeline.from_pretrained(
                "stabilityai/stable-diffusion-2-base"    ,						safety_checker=__lowerCamelCase							)
            _SCREAMING_SNAKE_CASE       :	Union[str, Any]						    =							LMSDiscreteScheduler.from_config(pipe.scheduler.config							)
            pipe.to(__lowerCamelCase							)
            pipe.set_progress_bar_config(disable=__lowerCamelCase							)
            pipe.enable_attention_slicing()

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

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

            _SCREAMING_SNAKE_CASE       :	Optional[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     UpperCamelCase_			(      self							)			->     Dict:
            _SCREAMING_SNAKE_CASE       :	Optional[int]						    =							0

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

                      _SCREAMING_SNAKE_CASE       :	Dict						    =							np.array(
                          [
                              0.1868_1869,
                              0.3390_7816,
                              0.536_1276,
                              0.1443_2865,
                              -0.0285_6611,
                              -0.7394_1123,
                              0.2339_7987,
                              0.4732_2682,
                              -0.3782_3164,
                          ]							)
                      assert np.abs(latents_slice.flatten() - expected_slice							).max() < 5E-2
                 elif step == 2:
                      _SCREAMING_SNAKE_CASE       :	Union[str, Any]						    =							latents.detach().cpu().numpy()
                      assert latents.shape == (1, 4, 6_4, 2_5_6)
                      _SCREAMING_SNAKE_CASE       :	str						    =							latents[0, -3:, -3:, -1]

                      _SCREAMING_SNAKE_CASE       :	Dict						    =							np.array(
                          [
                              0.1853_9645,
                              0.3398_7248,
                              0.537_8559,
                              0.1443_7142,
                              -0.0245_5261,
                              -0.733_8317,
                              0.2399_0755,
                              0.4735_6272,
                              -0.378_6505,
                          ]							)

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

            _SCREAMING_SNAKE_CASE       :	List[Any]						    =							False

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

            _SCREAMING_SNAKE_CASE       :	List[str]						    =							self.get_inputs()
            pipe(**__lowerCamelCase    ,						callback=__lowerCamelCase    ,						callback_steps=1							)
            assert callback_fn.has_been_called
            assert number_of_steps == 3







       def     UpperCamelCase_			(      self							)			->     Optional[int]:
            torch.cuda.empty_cache()
            torch.cuda.reset_max_memory_allocated()
            torch.cuda.reset_peak_memory_stats()

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

            _SCREAMING_SNAKE_CASE       :	Dict						    =							self.get_inputs()
            _SCREAMING_SNAKE_CASE       :	str						    =							pipe(**__lowerCamelCase							)

            _SCREAMING_SNAKE_CASE       :	Union[str, Any]						    =							torch.cuda.max_memory_allocated()
            # make sure that less than 5.2 GB is allocated
            assert mem_bytes < 5.5 * 1_0**9