'''simple docstring'''

import math
from dataclasses import dataclass
from typing import List, Optional, Tuple, Union

import numpy as np
import torch

from ..configuration_utils import ConfigMixin, register_to_config
from ..utils import BaseOutput, logging, randn_tensor
from .scheduling_utils import KarrasDiffusionSchedulers, SchedulerMixin


_A      :				int 				=    logging.get_logger(__name__)  # pylint: disable=invalid-name







@dataclass
# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->EulerAncestralDiscrete
class     _lowercase					(    UpperCAmelCase__      ):


 '''simple docstring'''






 _SCREAMING_SNAKE_CASE					:	torch.FloatTensor
 _SCREAMING_SNAKE_CASE					:	Optional[torch.FloatTensor]				     = None







def 					UpperCamelCase_						( snake_case_	:	Dict						,		snake_case_	:	str=0.9_9_9						,		snake_case_	:	Dict="cosine"						,		) ->					List[Any]:






 '''simple docstring'''

 if alpha_transform_type == "cosine":

  def alpha_bar_fn(snake_case_	:	List[Any]				):
   return math.cos((t + 0.0_0_8) / 1.0_0_8 * math.pi / 2				) ** 2

 elif alpha_transform_type == "exp":

  def alpha_bar_fn(snake_case_	:	str				):
   return math.exp(t * -1_2.0				)

 else:
  raise ValueError(f"""Unsupported alpha_tranform_type: {alpha_transform_type}"""				)

 __lowerCAmelCase    							=						[]
 for i in range(snake_case_				):
  __lowerCAmelCase    							=						i / num_diffusion_timesteps
  __lowerCAmelCase    							=						(i + 1) / num_diffusion_timesteps
  betas.append(min(1 - alpha_bar_fn(snake_case_				) / alpha_bar_fn(snake_case_				)						,		snake_case_				)				)
 return torch.tensor(snake_case_						,		dtype=torch.floataa				)







class     _lowercase					(    UpperCAmelCase__  ,							UpperCAmelCase__      ):


 '''simple docstring'''






 _SCREAMING_SNAKE_CASE					:	Union[str, Any]				     = [e.name for e in KarrasDiffusionSchedulers]
 _SCREAMING_SNAKE_CASE					:	Any				     = 1
 @register_to_config
 def __init__(				self       :     Any				,	SCREAMING_SNAKE_CASE__       :     int = 10_00				,	SCREAMING_SNAKE_CASE__       :     float = 0.0_0_0_1				,	SCREAMING_SNAKE_CASE__       :     float = 0.0_2				,	SCREAMING_SNAKE_CASE__       :     str = "linear"				,	SCREAMING_SNAKE_CASE__       :     Optional[Union[np.ndarray, List[float]]] = None				,	SCREAMING_SNAKE_CASE__       :     str = "epsilon"				,	SCREAMING_SNAKE_CASE__       :     str = "linspace"				,	SCREAMING_SNAKE_CASE__       :     int = 0				,	)  ->   Optional[int]:
  if trained_betas is not None:
   __lowerCAmelCase    							=						torch.tensor(SCREAMING_SNAKE_CASE__				,	dtype=torch.floataa							)
  elif beta_schedule == "linear":
   __lowerCAmelCase    							=						torch.linspace(SCREAMING_SNAKE_CASE__				,	SCREAMING_SNAKE_CASE__				,	SCREAMING_SNAKE_CASE__				,	dtype=torch.floataa							)
  elif beta_schedule == "scaled_linear":
   # this schedule is very specific to the latent diffusion model.
   __lowerCAmelCase    							=						(
       torch.linspace(beta_start**0.5				,	beta_end**0.5				,	SCREAMING_SNAKE_CASE__				,	dtype=torch.floataa							) ** 2
   )
  elif beta_schedule == "squaredcos_cap_v2":
   # Glide cosine schedule
   __lowerCAmelCase    							=						betas_for_alpha_bar(SCREAMING_SNAKE_CASE__							)
  else:
   raise NotImplementedError(f"""{beta_schedule} does is not implemented for {self.__class__}"""							)

  __lowerCAmelCase    							=						1.0 - self.betas
  __lowerCAmelCase    							=						torch.cumprod(self.alphas				,	dim=0							)

  __lowerCAmelCase    							=						np.array(((1 - self.alphas_cumprod) / self.alphas_cumprod) ** 0.5							)
  __lowerCAmelCase    							=						np.concatenate([sigmas[::-1], [0.0]]							).astype(np.floataa							)
  __lowerCAmelCase    							=						torch.from_numpy(SCREAMING_SNAKE_CASE__							)

  # setable values
  __lowerCAmelCase    							=						None
  __lowerCAmelCase    							=						np.linspace(0				,	num_train_timesteps - 1				,	SCREAMING_SNAKE_CASE__				,	dtype=SCREAMING_SNAKE_CASE__							)[::-1].copy()
  __lowerCAmelCase    							=						torch.from_numpy(SCREAMING_SNAKE_CASE__							)
  __lowerCAmelCase    							=						False
 @property
 def a (				self       :     str							)  ->   Optional[Any]:
  # standard deviation of the initial noise distribution
  if self.config.timestep_spacing in ["linspace", "trailing"]:
   return self.sigmas.max()

  return (self.sigmas.max() ** 2 + 1) ** 0.5
 def a (				self       :     List[Any]				,	SCREAMING_SNAKE_CASE__       :     torch.FloatTensor				,	SCREAMING_SNAKE_CASE__       :     Union[float, torch.FloatTensor]							)  ->   torch.FloatTensor:
  if isinstance(SCREAMING_SNAKE_CASE__				,	torch.Tensor							):
   __lowerCAmelCase    							=						timestep.to(self.timesteps.device							)
  __lowerCAmelCase    							=						(self.timesteps == timestep).nonzero().item()
  __lowerCAmelCase    							=						self.sigmas[step_index]
  __lowerCAmelCase    							=						sample / ((sigma**2 + 1) ** 0.5)
  __lowerCAmelCase    							=						True
  return sample
 def a (				self       :     Tuple				,	SCREAMING_SNAKE_CASE__       :     int				,	SCREAMING_SNAKE_CASE__       :     Union[str, torch.device] = None							)  ->   Union[str, Any]:
  __lowerCAmelCase    							=						num_inference_steps

  # "linspace", "leading", "trailing" corresponds to annotation of Table 2. of https://arxiv.org/abs/2305.08891
  if self.config.timestep_spacing == "linspace":
   __lowerCAmelCase    							=						np.linspace(0				,	self.config.num_train_timesteps - 1				,	SCREAMING_SNAKE_CASE__				,	dtype=SCREAMING_SNAKE_CASE__							)[
       ::-1
   ].copy()
  elif self.config.timestep_spacing == "leading":
   __lowerCAmelCase    							=						self.config.num_train_timesteps // self.num_inference_steps
   # creates integer timesteps by multiplying by ratio
   # casting to int to avoid issues when num_inference_step is power of 3
   __lowerCAmelCase    							=						(np.arange(0				,	SCREAMING_SNAKE_CASE__							) * step_ratio).round()[::-1].copy().astype(SCREAMING_SNAKE_CASE__							)
   timesteps += self.config.steps_offset
  elif self.config.timestep_spacing == "trailing":
   __lowerCAmelCase    							=						self.config.num_train_timesteps / self.num_inference_steps
   # creates integer timesteps by multiplying by ratio
   # casting to int to avoid issues when num_inference_step is power of 3
   __lowerCAmelCase    							=						(np.arange(self.config.num_train_timesteps				,	0				,	-step_ratio							)).round().copy().astype(SCREAMING_SNAKE_CASE__							)
   timesteps -= 1
  else:
   raise ValueError(
       f"""{self.config.timestep_spacing} is not supported. Please make sure to choose one of 'linspace', 'leading' or 'trailing'."""							)

  __lowerCAmelCase    							=						np.array(((1 - self.alphas_cumprod) / self.alphas_cumprod) ** 0.5							)
  __lowerCAmelCase    							=						np.interp(SCREAMING_SNAKE_CASE__				,	np.arange(0				,	len(SCREAMING_SNAKE_CASE__							)							)				,	SCREAMING_SNAKE_CASE__							)
  __lowerCAmelCase    							=						np.concatenate([sigmas, [0.0]]							).astype(np.floataa							)
  __lowerCAmelCase    							=						torch.from_numpy(SCREAMING_SNAKE_CASE__							).to(device=SCREAMING_SNAKE_CASE__							)
  if str(SCREAMING_SNAKE_CASE__							).startswith("""mps"""							):
   # mps does not support float64
   __lowerCAmelCase    							=						torch.from_numpy(SCREAMING_SNAKE_CASE__							).to(SCREAMING_SNAKE_CASE__				,	dtype=torch.floataa							)
  else:
   __lowerCAmelCase    							=						torch.from_numpy(SCREAMING_SNAKE_CASE__							).to(device=SCREAMING_SNAKE_CASE__							)
 def a (				self       :     Optional[int]				,	SCREAMING_SNAKE_CASE__       :     torch.FloatTensor				,	SCREAMING_SNAKE_CASE__       :     Union[float, torch.FloatTensor]				,	SCREAMING_SNAKE_CASE__       :     torch.FloatTensor				,	SCREAMING_SNAKE_CASE__       :     Optional[torch.Generator] = None				,	SCREAMING_SNAKE_CASE__       :     bool = True				,	)  ->   Union[EulerAncestralDiscreteSchedulerOutput, Tuple]:

  if (
      isinstance(SCREAMING_SNAKE_CASE__				,	SCREAMING_SNAKE_CASE__							)
      or isinstance(SCREAMING_SNAKE_CASE__				,	torch.IntTensor							)
      or isinstance(SCREAMING_SNAKE_CASE__				,	torch.LongTensor							)
  ):
   raise ValueError(
       (
           """Passing integer indices (e.g. from `enumerate(timesteps)`) as timesteps to"""
           """ `EulerDiscreteScheduler.step()` is not supported. Make sure to pass"""
           """ one of the `scheduler.timesteps` as a timestep."""
       )				,	)

  if not self.is_scale_input_called:
   logger.warning(
       """The `scale_model_input` function should be called before `step` to ensure correct denoising. """
       """See `StableDiffusionPipeline` for a usage example."""							)

  if isinstance(SCREAMING_SNAKE_CASE__				,	torch.Tensor							):
   __lowerCAmelCase    							=						timestep.to(self.timesteps.device							)

  __lowerCAmelCase    							=						(self.timesteps == timestep).nonzero().item()
  __lowerCAmelCase    							=						self.sigmas[step_index]

  # 1. compute predicted original sample (x_0) from sigma-scaled predicted noise
  if self.config.prediction_type == "epsilon":
   __lowerCAmelCase    							=						sample - sigma * model_output
  elif self.config.prediction_type == "v_prediction":
   # * c_out + input * c_skip
   __lowerCAmelCase    							=						model_output * (-sigma / (sigma**2 + 1) ** 0.5) + (sample / (sigma**2 + 1))
  elif self.config.prediction_type == "sample":
   raise NotImplementedError("""prediction_type not implemented yet: sample"""							)
  else:
   raise ValueError(
       f"""prediction_type given as {self.config.prediction_type} must be one of `epsilon`, or `v_prediction`"""							)

  __lowerCAmelCase    							=						self.sigmas[step_index]
  __lowerCAmelCase    							=						self.sigmas[step_index + 1]
  __lowerCAmelCase    							=						(sigma_to**2 * (sigma_from**2 - sigma_to**2) / sigma_from**2) ** 0.5
  __lowerCAmelCase    							=						(sigma_to**2 - sigma_up**2) ** 0.5

  # 2. Convert to an ODE derivative
  __lowerCAmelCase    							=						(sample - pred_original_sample) / sigma

  __lowerCAmelCase    							=						sigma_down - sigma

  __lowerCAmelCase    							=						sample + derivative * dt

  __lowerCAmelCase    							=						model_output.device
  __lowerCAmelCase    							=						randn_tensor(model_output.shape				,	dtype=model_output.dtype				,	device=SCREAMING_SNAKE_CASE__				,	generator=SCREAMING_SNAKE_CASE__							)

  __lowerCAmelCase    							=						prev_sample + noise * sigma_up

  if not return_dict:
   return (prev_sample,)

  return EulerAncestralDiscreteSchedulerOutput(
      prev_sample=SCREAMING_SNAKE_CASE__				,	pred_original_sample=SCREAMING_SNAKE_CASE__							)
 def a (				self       :     str				,	SCREAMING_SNAKE_CASE__       :     torch.FloatTensor				,	SCREAMING_SNAKE_CASE__       :     torch.FloatTensor				,	SCREAMING_SNAKE_CASE__       :     torch.FloatTensor				,	)  ->   torch.FloatTensor:
  # Make sure sigmas and timesteps have the same device and dtype as original_samples
  __lowerCAmelCase    							=						self.sigmas.to(device=original_samples.device				,	dtype=original_samples.dtype							)
  if original_samples.device.type == "mps" and torch.is_floating_point(SCREAMING_SNAKE_CASE__							):
   # mps does not support float64
   __lowerCAmelCase    							=						self.timesteps.to(original_samples.device				,	dtype=torch.floataa							)
   __lowerCAmelCase    							=						timesteps.to(original_samples.device				,	dtype=torch.floataa							)
  else:
   __lowerCAmelCase    							=						self.timesteps.to(original_samples.device							)
   __lowerCAmelCase    							=						timesteps.to(original_samples.device							)

  __lowerCAmelCase    							=						[(schedule_timesteps == t).nonzero().item() for t in timesteps]

  __lowerCAmelCase    							=						sigmas[step_indices].flatten()
  while len(sigma.shape							) < len(original_samples.shape							):
   __lowerCAmelCase    							=						sigma.unsqueeze(-1							)

  __lowerCAmelCase    							=						original_samples + noise * sigma
  return noisy_samples





 def __len__(				self       :     List[Any]							)  ->   int:
  return self.config.num_train_timesteps







'''simple docstring'''

import gc
import unittest

import numpy as np
import torch
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer

from diffusers import (
    AutoencoderKL,
    DDIMScheduler,
    EulerAncestralDiscreteScheduler,
    PNDMScheduler,
    StableDiffusionModelEditingPipeline,
    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 PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin


enable_full_determinism()







@skip_mps
class     _lowercase					(    UpperCAmelCase__  ,							UpperCAmelCase__  ,							UpperCAmelCase__  ,							unittest.TestCase      ):


 '''simple docstring'''






 _SCREAMING_SNAKE_CASE					:	int				     = StableDiffusionModelEditingPipeline
 _SCREAMING_SNAKE_CASE					:	List[Any]				     = TEXT_TO_IMAGE_PARAMS
 _SCREAMING_SNAKE_CASE					:	Tuple				     = TEXT_TO_IMAGE_BATCH_PARAMS
 _SCREAMING_SNAKE_CASE					:	List[Any]				     = TEXT_TO_IMAGE_IMAGE_PARAMS
 _SCREAMING_SNAKE_CASE					:	Optional[int]				     = TEXT_TO_IMAGE_IMAGE_PARAMS
 def a (				self       :     Tuple							)  ->   Any:
  torch.manual_seed(0							)
  __lowerCAmelCase    							=						UNetaDConditionModel(
      block_out_channels=(32, 64)				,	layers_per_block=2				,	sample_size=32				,	in_channels=4				,	out_channels=4				,	down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""")				,	up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""")				,	cross_attention_dim=32				,	)
  __lowerCAmelCase    							=						DDIMScheduler()
  torch.manual_seed(0							)
  __lowerCAmelCase    							=						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							)
  __lowerCAmelCase    							=						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=10_00				,	)
  __lowerCAmelCase    							=						CLIPTextModel(SCREAMING_SNAKE_CASE__							)
  __lowerCAmelCase    							=						CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip"""							)

  __lowerCAmelCase    							=						{
      """unet""": unet,
      """scheduler""": scheduler,
      """vae""": vae,
      """text_encoder""": text_encoder,
      """tokenizer""": tokenizer,
      """safety_checker""": None,
      """feature_extractor""": None,
  }
  return components
 def a (				self       :     List[Any]				,	SCREAMING_SNAKE_CASE__       :     Union[str, Any]				,	SCREAMING_SNAKE_CASE__       :     Dict=0							)  ->   Tuple:
  __lowerCAmelCase    							=						torch.manual_seed(SCREAMING_SNAKE_CASE__							)
  __lowerCAmelCase    							=						{
      """prompt""": """A field of roses""",
      """generator""": generator,
      # Setting height and width to None to prevent OOMs on CPU.
      """height""": None,
      """width""": None,
      """num_inference_steps""": 2,
      """guidance_scale""": 6.0,
      """output_type""": """numpy""",
  }
  return inputs
 def a (				self       :     int							)  ->   Optional[int]:
  __lowerCAmelCase    							=						"""cpu"""  # ensure determinism for the device-dependent torch.Generator
  __lowerCAmelCase    							=						self.get_dummy_components()
  __lowerCAmelCase    							=						StableDiffusionModelEditingPipeline(**SCREAMING_SNAKE_CASE__							)
  __lowerCAmelCase    							=						sd_pipe.to(SCREAMING_SNAKE_CASE__							)
  sd_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__							)

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

  __lowerCAmelCase    							=						np.array([0.4_7_5_5, 0.5_1_3_2, 0.4_9_7_6, 0.3_9_0_4, 0.3_5_5_4, 0.4_7_6_5, 0.5_1_3_9, 0.5_1_5_8, 0.4_8_8_9]							)

  assert np.abs(image_slice.flatten() - expected_slice							).max() < 1e-2
 def a (				self       :     Dict							)  ->   Tuple:
  __lowerCAmelCase    							=						"""cpu"""  # ensure determinism for the device-dependent torch.Generator
  __lowerCAmelCase    							=						self.get_dummy_components()
  __lowerCAmelCase    							=						StableDiffusionModelEditingPipeline(**SCREAMING_SNAKE_CASE__							)
  __lowerCAmelCase    							=						sd_pipe.to(SCREAMING_SNAKE_CASE__							)
  sd_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__							)

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

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

  __lowerCAmelCase    							=						np.array([0.4_9_9_2, 0.5_1_0_1, 0.5_0_0_4, 0.3_9_4_9, 0.3_6_0_4, 0.4_7_3_5, 0.5_2_1_6, 0.5_2_0_4, 0.4_9_1_3]							)

  assert np.abs(image_slice.flatten() - expected_slice							).max() < 1e-2
 def a (				self       :     Union[str, Any]							)  ->   int:
  __lowerCAmelCase    							=						"""cpu"""  # ensure determinism for the device-dependent torch.Generator
  __lowerCAmelCase    							=						self.get_dummy_components()
  __lowerCAmelCase    							=						EulerAncestralDiscreteScheduler(
      beta_start=0.0_0_0_8_5				,	beta_end=0.0_1_2				,	beta_schedule="""scaled_linear"""							)
  __lowerCAmelCase    							=						StableDiffusionModelEditingPipeline(**SCREAMING_SNAKE_CASE__							)
  __lowerCAmelCase    							=						sd_pipe.to(SCREAMING_SNAKE_CASE__							)
  sd_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__							)

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

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

  __lowerCAmelCase    							=						np.array([0.4_7_4_7, 0.5_3_7_2, 0.4_7_7_9, 0.4_9_8_2, 0.5_5_4_3, 0.4_8_1_6, 0.5_2_3_8, 0.4_9_0_4, 0.5_0_2_7]							)

  assert np.abs(image_slice.flatten() - expected_slice							).max() < 1e-2
 def a (				self       :     Optional[int]							)  ->   Optional[int]:
  __lowerCAmelCase    							=						"""cpu"""  # ensure determinism for the device-dependent torch.Generator
  __lowerCAmelCase    							=						self.get_dummy_components()
  __lowerCAmelCase    							=						PNDMScheduler()
  __lowerCAmelCase    							=						StableDiffusionModelEditingPipeline(**SCREAMING_SNAKE_CASE__							)
  __lowerCAmelCase    							=						sd_pipe.to(SCREAMING_SNAKE_CASE__							)
  sd_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__							)

  __lowerCAmelCase    							=						self.get_dummy_inputs(SCREAMING_SNAKE_CASE__							)
  # the pipeline does not expect pndm so test if it raises error.
  with self.assertRaises(SCREAMING_SNAKE_CASE__							):
   __lowerCAmelCase    							=						sd_pipe(**SCREAMING_SNAKE_CASE__							).images
 def a (				self       :     Tuple							)  ->   List[str]:
  super().test_inference_batch_single_identical(expected_max_diff=5e-3							)





 def a (				self       :     Optional[Any]							)  ->   List[str]:
  super().test_attention_slicing_forward_pass(expected_max_diff=5e-3							)







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


 '''simple docstring'''






 def a (				self       :     Optional[int]							)  ->   List[Any]:
  super().tearDown()
  gc.collect()
  torch.cuda.empty_cache()
 def a (				self       :     Dict				,	SCREAMING_SNAKE_CASE__       :     Dict=0							)  ->   int:
  __lowerCAmelCase    							=						torch.manual_seed(SCREAMING_SNAKE_CASE__							)
  __lowerCAmelCase    							=						{
      """prompt""": """A field of roses""",
      """generator""": generator,
      """num_inference_steps""": 3,
      """guidance_scale""": 7.5,
      """output_type""": """numpy""",
  }
  return inputs
 def a (				self       :     str							)  ->   Tuple:
  __lowerCAmelCase    							=						"""CompVis/stable-diffusion-v1-4"""
  __lowerCAmelCase    							=						StableDiffusionModelEditingPipeline.from_pretrained(SCREAMING_SNAKE_CASE__				,	safety_checker=SCREAMING_SNAKE_CASE__							)
  pipe.to(SCREAMING_SNAKE_CASE__							)
  pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__							)
  pipe.enable_attention_slicing()

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

  assert image.shape == (1, 5_12, 5_12, 3)

  __lowerCAmelCase    							=						np.array(
      [0.6_7_4_9_4_9_6, 0.6_3_8_6_4_5_3, 0.5_1_4_4_3_2_6_7, 0.6_6_0_9_4_9_0_5, 0.6_1_9_2_1_2_1_5, 0.5_4_9_1_3_3_2, 0.5_7_4_4_4_1_7, 0.5_8_0_7_5_1_0_6, 0.5_1_7_4_6_5_8]							)

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

  # make sure image changes after editing
  pipe.edit_model("""A pack of roses"""				,	"""A pack of blue roses"""							)

  __lowerCAmelCase    							=						pipe(**SCREAMING_SNAKE_CASE__							).images
  __lowerCAmelCase    							=						image[0, -3:, -3:, -1].flatten()

  assert image.shape == (1, 5_12, 5_12, 3)

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





 def a (				self       :     Tuple							)  ->   Optional[Any]:
  torch.cuda.empty_cache()
  torch.cuda.reset_max_memory_allocated()
  torch.cuda.reset_peak_memory_stats()

  __lowerCAmelCase    							=						"""CompVis/stable-diffusion-v1-4"""
  __lowerCAmelCase    							=						DDIMScheduler.from_pretrained(SCREAMING_SNAKE_CASE__				,	subfolder="""scheduler"""							)
  __lowerCAmelCase    							=						StableDiffusionModelEditingPipeline.from_pretrained(
      SCREAMING_SNAKE_CASE__				,	scheduler=SCREAMING_SNAKE_CASE__				,	safety_checker=SCREAMING_SNAKE_CASE__							)
  __lowerCAmelCase    							=						pipe.to(SCREAMING_SNAKE_CASE__							)
  pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__							)
  pipe.enable_attention_slicing(1							)
  pipe.enable_sequential_cpu_offload()

  __lowerCAmelCase    							=						self.get_inputs()
  __lowerCAmelCase    							=						pipe(**SCREAMING_SNAKE_CASE__							)

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






