


'''simple docstring'''

from .number_theory.prime_numbers import next_prime







class     _lowercase					:


 '''simple docstring'''






 def __init__(				self       :     Tuple				,	SCREAMING_SNAKE_CASE__       :     int				,	SCREAMING_SNAKE_CASE__       :     int | None = None				,	SCREAMING_SNAKE_CASE__       :     float | None = None				,	)  ->   None:
  __lowerCAmelCase    							=						size_table
  __lowerCAmelCase    							=						[None] * self.size_table
  __lowerCAmelCase    							=						0.7_5 if lim_charge is None else lim_charge
  __lowerCAmelCase    							=						1 if charge_factor is None else charge_factor
  __lowerCAmelCase    							=						[]
  __lowerCAmelCase    							=						{}
 def a (				self       :     Dict							)  ->   Union[str, Any]:
  return self._keys
 def a (				self       :     Optional[int]							)  ->   Union[str, Any]:
  return sum(1 for slot in self.values if slot is not None							) / (
      self.size_table * self.charge_factor
  )
 def a (				self       :     Dict				,	SCREAMING_SNAKE_CASE__       :     Any							)  ->   Optional[int]:
  return key % self.size_table
 def a (				self       :     Any				,	SCREAMING_SNAKE_CASE__       :     Any							)  ->   Any:
  print(f"""step {step_ord}"""							)
  print(list(range(len(self.values							)							)							)							)
  print(self.values							)
 def a (				self       :     Union[str, Any]				,	SCREAMING_SNAKE_CASE__       :     Tuple							)  ->   Dict:
  __lowerCAmelCase    							=						1
  __lowerCAmelCase    							=						values
  for value in values:
   self.insert_data(SCREAMING_SNAKE_CASE__							)
   self._step_by_step(SCREAMING_SNAKE_CASE__							)
   i += 1
 def a (				self       :     str				,	SCREAMING_SNAKE_CASE__       :     int				,	SCREAMING_SNAKE_CASE__       :     List[Any]							)  ->   List[str]:
  __lowerCAmelCase    							=						data
  __lowerCAmelCase    							=						data
 def a (				self       :     Optional[int]				,	SCREAMING_SNAKE_CASE__       :     Dict				,	SCREAMING_SNAKE_CASE__       :     Optional[int]=None							)  ->   Tuple:
  __lowerCAmelCase    							=						self.hash_function(key + 1							)

  while self.values[new_key] is not None and self.values[new_key] != key:
   if self.values.count(SCREAMING_SNAKE_CASE__							) > 0:
    __lowerCAmelCase    							=						self.hash_function(new_key + 1							)
   else:
    __lowerCAmelCase    							=						None
    break

  return new_key
 def a (				self       :     Optional[int]							)  ->   Dict:
  __lowerCAmelCase    							=						[value for value in self.values if value is not None]
  __lowerCAmelCase    							=						next_prime(self.size_table				,	factor=2							)
  self._keys.clear()
  __lowerCAmelCase    							=						[None] * self.size_table  # hell's pointers D: don't DRY ;/
  for value in survivor_values:
   self.insert_data(SCREAMING_SNAKE_CASE__							)





 def a (				self       :     List[str]				,	SCREAMING_SNAKE_CASE__       :     Dict							)  ->   Any:
  __lowerCAmelCase    							=						self.hash_function(SCREAMING_SNAKE_CASE__							)

  if self.values[key] is None:
   self._set_value(SCREAMING_SNAKE_CASE__				,	SCREAMING_SNAKE_CASE__							)

  elif self.values[key] == data:
   pass

  else:
   __lowerCAmelCase    							=						self._collision_resolution(SCREAMING_SNAKE_CASE__				,	SCREAMING_SNAKE_CASE__							)
   if collision_resolution is not None:
    self._set_value(SCREAMING_SNAKE_CASE__				,	SCREAMING_SNAKE_CASE__							)
   else:
    self.rehashing()
    self.insert_data(SCREAMING_SNAKE_CASE__							)







'''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






