





import logging
import os
from dataclasses import dataclass
from typing import List, Optional, Union

import tqdm
from filelock import FileLock

from transformers import (
    BartTokenizer,
    BartTokenizerFast,
    DataProcessor,
    PreTrainedTokenizer,
    RobertaTokenizer,
    RobertaTokenizerFast,
    XLMRobertaTokenizer,
    is_tf_available,
    is_torch_available,
)


UpperCamelCase__      =logging.getLogger(__name__)





@dataclass(frozen=__snake_case    )
class 			lowerCAmelCase__:






       '''simple docstring'''


       __snake_case 			=    42
       __snake_case 			=    42
       __snake_case 			=    None
       __snake_case 			=    None
       __snake_case 			=    None





@dataclass(frozen=__snake_case    )
class 			lowerCAmelCase__:






       '''simple docstring'''


       __snake_case 			=    42
       __snake_case 			=    None
       __snake_case 			=    None
       __snake_case 			=    None
       __snake_case 			=    None


if is_torch_available():
       import torch
       from torch.utils.data import Dataset





       class 			lowerCAmelCase__( __snake_case    ):






              '''simple docstring'''


              __snake_case 			=    42




              def __init__(      self    ,						__lowerCamelCase    ,						__lowerCamelCase    ,						__lowerCamelCase    ,						__lowerCamelCase = None    ,						__lowerCamelCase=False    ,						__lowerCamelCase = False    ,						)			->     str:
                   _SCREAMING_SNAKE_CASE       :	Optional[Any]						    =							hans_processors[task]()

                   _SCREAMING_SNAKE_CASE       :	Optional[Any]						    =							os.path.join(
                       A_    ,						"cached_{}_{}_{}_{}".format(
                           "dev" if evaluate else "train"    ,						tokenizer.__class__.__name__    ,						str(A_							)    ,						A_    ,						)    ,						)
                   _SCREAMING_SNAKE_CASE       :	List[str]						    =							processor.get_labels()
                   if tokenizer.__class__ in (
                       RobertaTokenizer,
                       RobertaTokenizerFast,
                       XLMRobertaTokenizer,
                       BartTokenizer,
                       BartTokenizerFast,
                   ):
                        # HACK(label indices are swapped in RoBERTa pretrained model)
                        _SCREAMING_SNAKE_CASE       :	int						    =							label_list[2], label_list[1]
                   _SCREAMING_SNAKE_CASE       :	Dict						    =							label_list

                   # Make sure only the first process in distributed training processes the dataset,
                   # and the others will use the cache.
                   _SCREAMING_SNAKE_CASE       :	int						    =							cached_features_file + ".lock"
                   with FileLock(A_							):
                        if os.path.exists(A_							) and not overwrite_cache:
                             logger.info(F"""Loading features from cached file {cached_features_file}"""							)
                             _SCREAMING_SNAKE_CASE       :	List[str]						    =							torch.load(A_							)
                        else:
                             logger.info(F"""Creating features from dataset file at {data_dir}"""							)

                             _SCREAMING_SNAKE_CASE       :	List[Any]						    =							(
                                 processor.get_dev_examples(A_							) if evaluate else processor.get_train_examples(A_							)
                             )

                             logger.info("Training examples: %s"    ,						len(A_							)							)
                             _SCREAMING_SNAKE_CASE       :	Tuple						    =							hans_convert_examples_to_features(A_    ,						A_    ,						A_    ,						A_							)
                             logger.info("Saving features into cached file %s"    ,						A_							)
                             torch.save(self.features    ,						A_							)




              def __len__(      self							)			->     str:
                   return len(self.features							)




              def __getitem__(      self    ,						__lowerCamelCase							)			->     Dict:
                   return self.features[i]







              def     UpperCamelCase_			(      self							)			->     Tuple:
                   return self.label_list


if is_tf_available():
       import tensorflow as tf





       class 			lowerCAmelCase__:






              '''simple docstring'''


              __snake_case 			=    42




              def __init__(      self    ,						__lowerCamelCase    ,						__lowerCamelCase    ,						__lowerCamelCase    ,						__lowerCamelCase = 1_2_8    ,						__lowerCamelCase=False    ,						__lowerCamelCase = False    ,						)			->     Any:
                   _SCREAMING_SNAKE_CASE       :	Optional[Any]						    =							hans_processors[task]()
                   _SCREAMING_SNAKE_CASE       :	Optional[int]						    =							processor.get_labels()
                   if tokenizer.__class__ in (
                       RobertaTokenizer,
                       RobertaTokenizerFast,
                       XLMRobertaTokenizer,
                       BartTokenizer,
                       BartTokenizerFast,
                   ):
                        # HACK(label indices are swapped in RoBERTa pretrained model)
                        _SCREAMING_SNAKE_CASE       :	Any						    =							label_list[2], label_list[1]
                   _SCREAMING_SNAKE_CASE       :	Tuple						    =							label_list

                   _SCREAMING_SNAKE_CASE       :	Optional[Any]						    =							processor.get_dev_examples(A_							) if evaluate else processor.get_train_examples(A_							)
                   _SCREAMING_SNAKE_CASE       :	str						    =							hans_convert_examples_to_features(A_    ,						A_    ,						A_    ,						A_							)

                   def gen():
                        for ex_index, ex in tqdm.tqdm(enumerate(self.features							)    ,						desc="convert examples to features"							):
                             if ex_index % 1_0_0_0_0 == 0:
                                  logger.info("Writing example %d of %d" % (ex_index, len(A_							))							)

                             yield (
                                 {
                                     "example_id": 0,
                                     "input_ids": ex.input_ids,
                                     "attention_mask": ex.attention_mask,
                                     "token_type_ids": ex.token_type_ids,
                                 },
                                 ex.label,
                             )

                   _SCREAMING_SNAKE_CASE       :	str						    =							tf.data.Dataset.from_generator(
                       A_    ,						(
                           {
                               "example_id": tf.intaa,
                               "input_ids": tf.intaa,
                               "attention_mask": tf.intaa,
                               "token_type_ids": tf.intaa,
                           },
                           tf.intaa,
                       )    ,						(
                           {
                               "example_id": tf.TensorShape([]							),
                               "input_ids": tf.TensorShape([None, None]							),
                               "attention_mask": tf.TensorShape([None, None]							),
                               "token_type_ids": tf.TensorShape([None, None]							),
                           },
                           tf.TensorShape([]							),
                       )    ,						)




              def     UpperCamelCase_			(      self							)			->     Dict:
                   return self.dataset




              def __len__(      self							)			->     str:
                   return len(self.features							)




              def __getitem__(      self    ,						__lowerCamelCase							)			->     Tuple:
                   return self.features[i]







              def     UpperCamelCase_			(      self							)			->     Union[str, Any]:
                   return self.label_list





class 			lowerCAmelCase__( __snake_case    ):






       '''simple docstring'''


       def     UpperCamelCase_			(      self    ,						__lowerCamelCase							)			->     int:
            return self._create_examples(self._read_tsv(os.path.join(A_    ,						"heuristics_train_set.txt"							)							)    ,						"train"							)




       def     UpperCamelCase_			(      self    ,						__lowerCamelCase							)			->     Union[str, Any]:
            return self._create_examples(self._read_tsv(os.path.join(A_    ,						"heuristics_evaluation_set.txt"							)							)    ,						"dev"							)




       def     UpperCamelCase_			(      self							)			->     List[Any]:
            return ["contradiction", "entailment", "neutral"]







       def     UpperCamelCase_			(      self    ,						__lowerCamelCase    ,						__lowerCamelCase							)			->     Union[str, Any]:
            _SCREAMING_SNAKE_CASE       :	Optional[Any]						    =							[]
            for i, line in enumerate(A_							):
                 if i == 0:
                      continue
                 _SCREAMING_SNAKE_CASE       :	Union[str, Any]						    =							"%s-%s" % (set_type, line[0])
                 _SCREAMING_SNAKE_CASE       :	Optional[int]						    =							line[5]
                 _SCREAMING_SNAKE_CASE       :	Tuple						    =							line[6]
                 _SCREAMING_SNAKE_CASE       :	int						    =							line[7][2:] if line[7].startswith("ex"							) else line[7]
                 _SCREAMING_SNAKE_CASE       :	Optional[Any]						    =							line[0]
                 examples.append(InputExample(guid=A_    ,						text_a=A_    ,						text_b=A_    ,						label=A_    ,						pairID=A_							)							)
            return examples






def     lowerCamelCase__			(__lowerCamelCase,       __lowerCamelCase,       __lowerCamelCase,       __lowerCamelCase,       ):
     _SCREAMING_SNAKE_CASE       :	Optional[int]						    =							{label: i for i, label in enumerate(_lowerCAmelCase	)}

     _SCREAMING_SNAKE_CASE       :	List[str]						    =							[]
     for ex_index, example in tqdm.tqdm(enumerate(_lowerCAmelCase	),       desc="convert examples to features"	):
          if ex_index % 10000 == 0:
               logger.info("Writing example %d" % (ex_index)	)

          _SCREAMING_SNAKE_CASE       :	List[str]						    =							tokenizer(
              example.text_a,       example.text_b,       add_special_tokens=_lowerCAmelCase,       max_length=_lowerCAmelCase,       padding="max_length",       truncation=_lowerCAmelCase,       return_overflowing_tokens=_lowerCAmelCase,       )

          _SCREAMING_SNAKE_CASE       :	str						    =							label_map[example.label] if example.label in label_map else 0

          _SCREAMING_SNAKE_CASE       :	Tuple						    =							int(example.pairID	)

          features.append(InputFeatures(**_lowerCAmelCase,       label=_lowerCAmelCase,       pairID=_lowerCAmelCase	)	)

     for i, example in enumerate(examples[:5]	):
          logger.info("*** Example ***"	)
          logger.info(f"""guid: {example}"""	)
          logger.info(f"""features: {features[i]}"""	)

     return features


UpperCamelCase__      ={
    """hans""": 3,
}

UpperCamelCase__      ={
    """hans""": HansProcessor,
}









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