
'''simple docstring'''
import inspect

import jax
import jax.lax as lax
import jax.numpy as jnp

from ..utils import add_start_docstrings
from ..utils.logging import get_logger


__lowerCAmelCase												=	get_logger(__name__)


__lowerCAmelCase												=	r'\n    Args:\n        input_ids (`jnp.ndarray` of shape `(batch_size, sequence_length)`):\n            Indices of input sequence tokens in the vocabulary.\n\n            Indices can be obtained using [`PreTrainedTokenizer`]. See [`PreTrainedTokenizer.encode`] and\n            [`PreTrainedTokenizer.__call__`] for details.\n\n            [What are input IDs?](../glossary#input-ids)\n        scores (`jnp.ndarray` of shape `(batch_size, config.vocab_size)`):\n            Prediction scores of a language modeling head. These can be logits for each vocabulary when not using beam\n            search or log softmax for each vocabulary token when using beam search\n        kwargs (`Dict[str, Any]`, *optional*):\n            Additional logits processor specific kwargs.\n\n    Return:\n        `jnp.ndarray` of shape `(batch_size, config.vocab_size)`: The processed prediction scores.\n\n'


class       _lowerCAmelCase   :







							'''simple docstring'''

							@add_start_docstrings(UpperCAmelCase  )
							def __call__(self  ,  UpperCAmelCase  ,  UpperCAmelCase  )					->       jnp.ndarray:
														raise NotImplementedError(
														    f"""{self.__class__} is an abstract class. Only classes inheriting this class can be called."""  )


class       _lowerCAmelCase   :







							'''simple docstring'''

							@add_start_docstrings(UpperCAmelCase  )
							def __call__(self  ,  UpperCAmelCase  ,  UpperCAmelCase  )					->       jnp.ndarray:
														raise NotImplementedError(
														    f"""{self.__class__} is an abstract class. Only classes inheriting this class can be called."""  )


class       _lowerCAmelCase   (   __snake_case				):







							'''simple docstring'''

							@add_start_docstrings(UpperCAmelCase  )
							def __call__(self  ,  UpperCAmelCase  ,  UpperCAmelCase  ,  UpperCAmelCase  ,  **UpperCAmelCase  )					->       jnp.ndarray:
														for processor in self:
																					_snake_case       =  inspect.signature(processor.__call__  ).parameters
																					if len(UpperCAmelCase  ) > 3:
																												if not all(arg in kwargs for arg in list(function_args.keys()  )[2:]  ):
																																			raise ValueError(
																																			    f"""Make sure that all the required parameters: {list(function_args.keys()  )} for """
																																			    f"""{processor.__class__} are passed to the logits processor."""  )
																												_snake_case       =  processor(UpperCAmelCase  ,  UpperCAmelCase  ,  UpperCAmelCase  ,  **UpperCAmelCase  )
																					else:
																												_snake_case       =  processor(UpperCAmelCase  ,  UpperCAmelCase  ,  UpperCAmelCase  )
														return scores


class       _lowerCAmelCase   (   __snake_case				):







							'''simple docstring'''

							def __init__(self  ,  UpperCAmelCase  )					->       Dict:
														if not isinstance(UpperCAmelCase  ,  UpperCAmelCase  ) or not (temperature > 0):
																					raise ValueError(f"""`temperature` has to be a strictly positive float, but is {temperature}"""  )

														_snake_case       =  temperature





							def __call__(self  ,  UpperCAmelCase  ,  UpperCAmelCase  ,  UpperCAmelCase  )					->       jnp.ndarray:
														_snake_case       =  scores / self.temperature
														return scores


class       _lowerCAmelCase   (   __snake_case				):







							'''simple docstring'''

							def __init__(self  ,  UpperCAmelCase  ,  UpperCAmelCase = -float("""Inf"""  )  ,  UpperCAmelCase = 1  )					->       Any:
														if not isinstance(UpperCAmelCase  ,  UpperCAmelCase  ) or (top_p < 0 or top_p > 1.0):
																					raise ValueError(f"""`top_p` has to be a float > 0 and < 1, but is {top_p}"""  )
														if not isinstance(UpperCAmelCase  ,  UpperCAmelCase  ) or (min_tokens_to_keep < 1):
																					raise ValueError(f"""`min_tokens_to_keep` has to be a positive integer, but is {min_tokens_to_keep}"""  )

														_snake_case       =  top_p
														_snake_case       =  filter_value
														_snake_case       =  min_tokens_to_keep





							def __call__(self  ,  UpperCAmelCase  ,  UpperCAmelCase  ,  UpperCAmelCase  )					->       jnp.ndarray:
														_snake_case,							_snake_case       =  lax.top_k(UpperCAmelCase  ,  scores.shape[-1]  )

														_snake_case       =  jnp.full_like(UpperCAmelCase  ,  self.filter_value  )
														_snake_case       =  jax.nn.softmax(UpperCAmelCase  ,  axis=-1  ).cumsum(axis=-1  )
														_snake_case       =  cumulative_probs < self.top_p

														# include the token that is higher than top_p as well
														_snake_case       =  jnp.roll(UpperCAmelCase  ,  1  )
														score_mask |= score_mask.at[:, 0].set(UpperCAmelCase  )

														# min tokens to keep
														_snake_case       =  score_mask.at[:, : self.min_tokens_to_keep].set(UpperCAmelCase  )

														_snake_case       =  jnp.where(UpperCAmelCase  ,  UpperCAmelCase  ,  UpperCAmelCase  )
														_snake_case       =  jax.lax.sort_key_val(UpperCAmelCase  ,  UpperCAmelCase  )[-1]

														return next_scores


class       _lowerCAmelCase   (   __snake_case				):







							'''simple docstring'''

							def __init__(self  ,  UpperCAmelCase  ,  UpperCAmelCase = -float("""Inf"""  )  ,  UpperCAmelCase = 1  )					->       Optional[Any]:
														if not isinstance(UpperCAmelCase  ,  UpperCAmelCase  ) or top_k <= 0:
																					raise ValueError(f"""`top_k` has to be a strictly positive integer, but is {top_k}"""  )

														_snake_case       =  max(UpperCAmelCase  ,  UpperCAmelCase  )
														_snake_case       =  filter_value





							def __call__(self  ,  UpperCAmelCase  ,  UpperCAmelCase  ,  UpperCAmelCase  )					->       jnp.ndarray:
														_snake_case,							_snake_case       =  scores.shape
														_snake_case       =  jnp.full(batch_size * vocab_size  ,  self.filter_value  )

														_snake_case       =  min(self.top_k  ,  scores.shape[-1]  )  # Safety check
														_snake_case,							_snake_case       =  lax.top_k(UpperCAmelCase  ,  UpperCAmelCase  )
														_snake_case       =  jnp.broadcast_to((jnp.arange(UpperCAmelCase  ) * vocab_size)[:, None]  ,  (batch_size, topk)  ).flatten()
														_snake_case       =  topk_scores.flatten()
														_snake_case       =  topk_indices.flatten() + shift

														_snake_case       =  next_scores_flat.at[topk_indices_flat].set(UpperCAmelCase  )
														_snake_case       =  next_scores_flat.reshape(UpperCAmelCase  ,  UpperCAmelCase  )
														return next_scores


class       _lowerCAmelCase   (   __snake_case				):







							'''simple docstring'''

							def __init__(self  ,  UpperCAmelCase  )					->       List[Any]:
														_snake_case       =  bos_token_id





							def __call__(self  ,  UpperCAmelCase  ,  UpperCAmelCase  ,  UpperCAmelCase  )					->       jnp.ndarray:
														_snake_case       =  jnp.full(scores.shape  ,  -float("""inf"""  )  )

														_snake_case       =  1 - jnp.bool_(cur_len - 1  )

														_snake_case       =  jnp.where(UpperCAmelCase  ,  new_scores.at[:, self.bos_token_id].set(0  )  ,  UpperCAmelCase  )

														return scores


class       _lowerCAmelCase   (   __snake_case				):







							'''simple docstring'''

							def __init__(self  ,  UpperCAmelCase  ,  UpperCAmelCase  )					->       Tuple:
														_snake_case       =  max_length
														_snake_case       =  eos_token_id





							def __call__(self  ,  UpperCAmelCase  ,  UpperCAmelCase  ,  UpperCAmelCase  )					->       jnp.ndarray:
														_snake_case       =  jnp.full(scores.shape  ,  -float("""inf"""  )  )

														_snake_case       =  1 - jnp.bool_(cur_len - self.max_length + 1  )

														_snake_case       =  jnp.where(UpperCAmelCase  ,  new_scores.at[:, self.eos_token_id].set(0  )  ,  UpperCAmelCase  )

														return scores


class       _lowerCAmelCase   (   __snake_case				):







							'''simple docstring'''

							def __init__(self  ,  UpperCAmelCase  ,  UpperCAmelCase  )					->       Union[str, Any]:
														if not isinstance(UpperCAmelCase  ,  UpperCAmelCase  ) or min_length < 0:
																					raise ValueError(f"""`min_length` has to be a positive integer, but is {min_length}"""  )

														if not isinstance(UpperCAmelCase  ,  UpperCAmelCase  ) or eos_token_id < 0:
																					raise ValueError(f"""`eos_token_id` has to be a positive integer, but is {eos_token_id}"""  )

														_snake_case       =  min_length
														_snake_case       =  eos_token_id





							def __call__(self  ,  UpperCAmelCase  ,  UpperCAmelCase  ,  UpperCAmelCase  )					->       jnp.ndarray:
														# create boolean flag to decide if min length penalty should be applied
														_snake_case       =  1 - jnp.clip(cur_len - self.min_length  ,  0  ,  1  )

														_snake_case       =  jnp.where(UpperCAmelCase  ,  scores.at[:, self.eos_token_id].set(-float("""inf"""  )  )  ,  UpperCAmelCase  )

														return scores


class       _lowerCAmelCase   (   __snake_case				):







							'''simple docstring'''

							def __init__(self  ,  UpperCAmelCase  ,  UpperCAmelCase  )					->       int:
														_snake_case       =  list(UpperCAmelCase  )
														_snake_case       =  begin_index





							def __call__(self  ,  UpperCAmelCase  ,  UpperCAmelCase  ,  UpperCAmelCase  )					->       Tuple:
														_snake_case       =  1 - jnp.bool_(cur_len - self.begin_index  )

														_snake_case       =  jnp.where(UpperCAmelCase  ,  scores.at[:, self.begin_suppress_tokens].set(-float("""inf"""  )  )  ,  UpperCAmelCase  )

														return scores


class       _lowerCAmelCase   (   __snake_case				):







							'''simple docstring'''

							def __init__(self  ,  UpperCAmelCase  )					->       Union[str, Any]:
														_snake_case       =  list(UpperCAmelCase  )





							def __call__(self  ,  UpperCAmelCase  ,  UpperCAmelCase  ,  UpperCAmelCase  )					->       jnp.ndarray:
														_snake_case       =  scores.at[..., self.suppress_tokens].set(-float("""inf"""  )  )

														return scores


class       _lowerCAmelCase   (   __snake_case				):







							'''simple docstring'''

							def __init__(self  ,  UpperCAmelCase  )					->       str:
														_snake_case       =  dict(UpperCAmelCase  )
														# Converts the dictionary of format {index: token} containing the tokens to be forced to an array, where the
														# index of the array corresponds to the index of the token to be forced, for XLA compatibility.
														# Indexes without forced tokens will have a negative value.
														_snake_case       =  jnp.ones((max(force_token_map.keys()  ) + 1)  ,  dtype=jnp.intaa  ) * -1
														for index, token in force_token_map.items():
																					if token is not None:
																												_snake_case       =  force_token_array.at[index].set(UpperCAmelCase  )
														_snake_case       =  jnp.intaa(UpperCAmelCase  )





							def __call__(self  ,  UpperCAmelCase  ,  UpperCAmelCase  ,  UpperCAmelCase  )					->       jnp.ndarray:
														def _force_token(UpperCAmelCase  ):
																					_snake_case       =  scores.shape[0]
																					_snake_case       =  self.force_token_array[generation_idx]

																					_snake_case       =  jnp.ones_like(UpperCAmelCase  ,  dtype=scores.dtype  ) * -float("""inf"""  )
																					_snake_case       =  jnp.zeros((batch_size, 1)  ,  dtype=scores.dtype  )
																					_snake_case       =  lax.dynamic_update_slice(UpperCAmelCase  ,  UpperCAmelCase  ,  (0, current_token)  )
																					return new_scores

														_snake_case       =  lax.cond(
														    cur_len >= self.force_token_array.shape[0]  ,  lambda: scores  ,  lambda: lax.cond(
														        self.force_token_array[cur_len] >= 0  ,  lambda: _force_token(UpperCAmelCase  )  ,  lambda: scores  ,  )  ,  )
														return scores


class       _lowerCAmelCase   (   __snake_case				):







							'''simple docstring'''

							def __init__(self  ,  UpperCAmelCase  ,  UpperCAmelCase  ,  UpperCAmelCase  )					->       Dict:
														_snake_case       =  generate_config.eos_token_id
														_snake_case       =  generate_config.no_timestamps_token_id
														_snake_case       =  generate_config.no_timestamps_token_id + 1

														_snake_case       =  decoder_input_length + 1

														if generate_config.is_multilingual:
																					# room for language token and task token
																					self.begin_index += 2
														if hasattr(UpperCAmelCase  ,  """max_initial_timestamp_index"""  ):
																					_snake_case       =  generate_config.max_initial_timestamp_index
														else:
																					_snake_case       =  model_config.vocab_size
														if self.max_initial_timestamp_index is None:
																					_snake_case       =  model_config.vocab_size





							def __call__(self  ,  UpperCAmelCase  ,  UpperCAmelCase  ,  UpperCAmelCase  )					->       Optional[int]:
														# suppress <|notimestamps|> which is handled by without_timestamps
														_snake_case       =  scores.at[:, self.no_timestamps_token_id].set(-float("""inf"""  )  )

														def handle_pairs(UpperCAmelCase  ,  UpperCAmelCase  ):
																					_snake_case       =  jnp.where((cur_len - self.begin_index) >= 1  ,  UpperCAmelCase  ,  UpperCAmelCase  )
																					_snake_case       =  jnp.where(
																					    input_ids_k[cur_len - 1] >= self.timestamp_begin  ,  True and last_was_timestamp  ,  UpperCAmelCase  ,  )

																					_snake_case       =  jnp.where((cur_len - self.begin_index) < 2  ,  UpperCAmelCase  ,  UpperCAmelCase  )
																					_snake_case       =  jnp.where(
																					    input_ids_k[cur_len - 2] >= self.timestamp_begin  ,  UpperCAmelCase  ,  UpperCAmelCase  ,  )

																					return jnp.where(
																					    UpperCAmelCase  ,  jnp.where(
																					        penultimate_was_timestamp > 0  ,  scores_k.at[self.timestamp_begin :].set(-float("""inf"""  )  )  ,  scores_k.at[: self.eos_token_id].set(-float("""inf"""  )  )  ,  )  ,  UpperCAmelCase  ,  )

														_snake_case       =  jax.vmap(UpperCAmelCase  )(UpperCAmelCase  ,  UpperCAmelCase  )

														_snake_case       =  jnp.where(cur_len == self.begin_index  ,  UpperCAmelCase  ,  UpperCAmelCase  )
														_snake_case       =  jnp.where(
														    self.max_initial_timestamp_index is not None  ,  True and apply_max_initial_timestamp  ,  UpperCAmelCase  ,  )

														_snake_case       =  self.timestamp_begin + self.max_initial_timestamp_index

														_snake_case       =  jnp.where(
														    UpperCAmelCase  ,  scores.at[:, last_allowed + 1 :].set(-float("""inf"""  )  )  ,  UpperCAmelCase  ,  )

														# if sum of probability over timestamps is above any other token, sample timestamp
														_snake_case       =  jax.nn.log_softmax(UpperCAmelCase  ,  axis=-1  )

														def handle_cumulative_probs(UpperCAmelCase  ,  UpperCAmelCase  ):
																					_snake_case       =  jax.nn.logsumexp(logprobs_k[self.timestamp_begin :]  ,  axis=-1  )
																					_snake_case       =  jnp.max(logprobs_k[: self.timestamp_begin]  )
																					return jnp.where(
																					    timestamp_logprob > max_text_token_logprob  ,  scores_k.at[: self.timestamp_begin].set(-float("""inf"""  )  )  ,  UpperCAmelCase  ,  )

														_snake_case       =  jax.vmap(UpperCAmelCase  )(UpperCAmelCase  ,  UpperCAmelCase  )

														return scores

'''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       _lowerCAmelCase   (   __snake_case					,							__snake_case					,							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 	lowercase							(self  )					->       List[Any]:
														torch.manual_seed(0  )
														_snake_case       =  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  ,  )
														_snake_case       =  DDIMScheduler()
														torch.manual_seed(0  )
														_snake_case       =  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  )
														_snake_case       =  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  ,  )
														_snake_case       =  CLIPTextModel(UpperCAmelCase  )
														_snake_case       =  CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip"""  )

														_snake_case       =  {
														    """unet""": unet,
														    """scheduler""": scheduler,
														    """vae""": vae,
														    """text_encoder""": text_encoder,
														    """tokenizer""": tokenizer,
														    """safety_checker""": None,
														    """feature_extractor""": None,
														}
														return components

							def 	lowercase							(self  ,  UpperCAmelCase  ,  UpperCAmelCase=0  )					->       Tuple:
														_snake_case       =  torch.manual_seed(UpperCAmelCase  )
														_snake_case       =  {
														    """prompt""": """a photo of the dolomites""",
														    """generator""": generator,
														    # Setting height and width to None to prevent OOMs on CPU.
														    """height""": None,
														    """width""": None,
														    """num_inference_steps""": 1,
														    """guidance_scale""": 6.0,
														    """output_type""": """numpy""",
														}
														return inputs

							def 	lowercase							(self  )					->       Tuple:
														_snake_case       =  """cpu"""  # ensure determinism for the device-dependent torch.Generator
														_snake_case       =  self.get_dummy_components()
														_snake_case       =  StableDiffusionPanoramaPipeline(**UpperCAmelCase  )
														_snake_case       =  sd_pipe.to(UpperCAmelCase  )
														sd_pipe.set_progress_bar_config(disable=UpperCAmelCase  )

														_snake_case       =  self.get_dummy_inputs(UpperCAmelCase  )
														_snake_case       =  sd_pipe(**UpperCAmelCase  ).images
														_snake_case       =  image[0, -3:, -3:, -1]
														assert image.shape == (1, 64, 64, 3)

														_snake_case       =  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 	lowercase							(self  )					->       Tuple:
														super().test_inference_batch_consistent(batch_sizes=[1, 2]  )

							def 	lowercase							(self  )					->       Any:
														super().test_inference_batch_single_identical(batch_size=2  ,  expected_max_diff=3.2_5e-3  )

							def 	lowercase							(self  )					->       Any:
														_snake_case       =  """cpu"""  # ensure determinism for the device-dependent torch.Generator
														_snake_case       =  self.get_dummy_components()
														_snake_case       =  StableDiffusionPanoramaPipeline(**UpperCAmelCase  )
														_snake_case       =  sd_pipe.to(UpperCAmelCase  )
														sd_pipe.set_progress_bar_config(disable=UpperCAmelCase  )

														_snake_case       =  self.get_dummy_inputs(UpperCAmelCase  )
														_snake_case       =  """french fries"""
														_snake_case       =  sd_pipe(**UpperCAmelCase  ,  negative_prompt=UpperCAmelCase  )
														_snake_case       =  output.images
														_snake_case       =  image[0, -3:, -3:, -1]

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

														_snake_case       =  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 	lowercase							(self  )					->       str:
														_snake_case       =  """cpu"""  # ensure determinism for the device-dependent torch.Generator
														_snake_case       =  self.get_dummy_components()
														_snake_case       =  StableDiffusionPanoramaPipeline(**UpperCAmelCase  )
														_snake_case       =  sd_pipe.to(UpperCAmelCase  )
														sd_pipe.set_progress_bar_config(disable=UpperCAmelCase  )

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

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

														_snake_case       =  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 	lowercase							(self  )					->       Tuple:
														_snake_case       =  """cpu"""  # ensure determinism for the device-dependent torch.Generator
														_snake_case       =  self.get_dummy_components()
														_snake_case       =  EulerAncestralDiscreteScheduler(
														    beta_start=0.0_0085  ,  beta_end=0.012  ,  beta_schedule="""scaled_linear"""  )
														_snake_case       =  StableDiffusionPanoramaPipeline(**UpperCAmelCase  )
														_snake_case       =  sd_pipe.to(UpperCAmelCase  )
														sd_pipe.set_progress_bar_config(disable=UpperCAmelCase  )

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

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

														_snake_case       =  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 	lowercase							(self  )					->       str:
														_snake_case       =  """cpu"""  # ensure determinism for the device-dependent torch.Generator
														_snake_case       =  self.get_dummy_components()
														_snake_case       =  PNDMScheduler(
														    beta_start=0.0_0085  ,  beta_end=0.012  ,  beta_schedule="""scaled_linear"""  ,  skip_prk_steps=UpperCAmelCase  )
														_snake_case       =  StableDiffusionPanoramaPipeline(**UpperCAmelCase  )
														_snake_case       =  sd_pipe.to(UpperCAmelCase  )
														sd_pipe.set_progress_bar_config(disable=UpperCAmelCase  )

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

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

														_snake_case       =  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 	lowercase							(self  )					->       Optional[Any]:
														super().tearDown()
														gc.collect()
														torch.cuda.empty_cache()

							def 	lowercase							(self  ,  UpperCAmelCase=0  )					->       List[str]:
														_snake_case       =  torch.manual_seed(UpperCAmelCase  )
														_snake_case       =  {
														    """prompt""": """a photo of the dolomites""",
														    """generator""": generator,
														    """num_inference_steps""": 3,
														    """guidance_scale""": 7.5,
														    """output_type""": """numpy""",
														}
														return inputs

							def 	lowercase							(self  )					->       List[Any]:
														_snake_case       =  """stabilityai/stable-diffusion-2-base"""
														_snake_case       =  DDIMScheduler.from_pretrained(UpperCAmelCase  ,  subfolder="""scheduler"""  )
														_snake_case       =  StableDiffusionPanoramaPipeline.from_pretrained(UpperCAmelCase  ,  scheduler=UpperCAmelCase  ,  safety_checker=UpperCAmelCase  )
														pipe.to(UpperCAmelCase  )
														pipe.set_progress_bar_config(disable=UpperCAmelCase  )
														pipe.enable_attention_slicing()

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

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

														_snake_case       =  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 	lowercase							(self  )					->       str:
														_snake_case       =  StableDiffusionPanoramaPipeline.from_pretrained(
														    """stabilityai/stable-diffusion-2-base"""  ,  safety_checker=UpperCAmelCase  )
														_snake_case       =  LMSDiscreteScheduler.from_config(pipe.scheduler.config  )
														pipe.to(UpperCAmelCase  )
														pipe.set_progress_bar_config(disable=UpperCAmelCase  )
														pipe.enable_attention_slicing()

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

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

														_snake_case       =  np.array(
														    [
														        [
														            0.0,
														            0.0,
														            0.0,
														            0.0,
														            0.0,
														            0.0,
														            0.0,
														            0.0,
														            0.0,
														        ]
														    ]  )

														assert np.abs(expected_slice - image_slice  ).max() < 1e-3

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

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

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

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

														_snake_case       =  False

														_snake_case       =  """stabilityai/stable-diffusion-2-base"""
														_snake_case       =  DDIMScheduler.from_pretrained(UpperCAmelCase  ,  subfolder="""scheduler"""  )
														_snake_case       =  StableDiffusionPanoramaPipeline.from_pretrained(UpperCAmelCase  ,  scheduler=UpperCAmelCase  ,  safety_checker=UpperCAmelCase  )
														_snake_case       =  pipe.to(UpperCAmelCase  )
														pipe.set_progress_bar_config(disable=UpperCAmelCase  )
														pipe.enable_attention_slicing()

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





							def 	lowercase							(self  )					->       List[Any]:
														torch.cuda.empty_cache()
														torch.cuda.reset_max_memory_allocated()
														torch.cuda.reset_peak_memory_stats()

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

														_snake_case       =  self.get_inputs()
														_snake_case       =  pipe(**UpperCAmelCase  )

														_snake_case       =  torch.cuda.max_memory_allocated()
														# make sure that less than 5.2 GB is allocated
														assert mem_bytes < 5.5 * 10**9