code: 
  from typing import List, Optional, Union
  
  import numpy as np
  import PIL
  import torch
  from PIL import Image
  
  from ...models import UNetaDConditionModel, VQModel
  from ...pipelines import DiffusionPipeline
  from ...pipelines.pipeline_utils import ImagePipelineOutput
  from ...schedulers import DDPMScheduler
  from ...utils import (
      is_accelerate_available,
      is_accelerate_version,
      logging,
      randn_tensor,
      replace_example_docstring,
  )
  
  
  UpperCamelCase_	:    Union[str, Any]  					=       logging.get_logger(__name__)  # pylint: disable=invalid-name
  
  UpperCamelCase_	:    Tuple  					=       """
      Examples:
          ```py
          >>> import torch
          >>> import numpy as np
  
          >>> from diffusers import KandinskyV22PriorEmb2EmbPipeline, KandinskyV22ControlnetImg2ImgPipeline
          >>> from transformers import pipeline
          >>> from diffusers.utils import load_image
  
  
          >>> def make_hint(image, depth_estimator):
          ...     image = depth_estimator(image)[\"depth\"]
          ...     image = np.array(image)
          ...     image = image[:, :, None]
          ...     image = np.concatenate([image, image, image], axis=2)
          ...     detected_map = torch.from_numpy(image).float() / 255.0
          ...     hint = detected_map.permute(2, 0, 1)
          ...     return hint
  
  
          >>> depth_estimator = pipeline(\"depth-estimation\")
  
          >>> pipe_prior = KandinskyV22PriorEmb2EmbPipeline.from_pretrained(
          ...     \"kandinsky-community/kandinsky-2-2-prior\", torch_dtype=torch.float16
          ... )
          >>> pipe_prior = pipe_prior.to(\"cuda\")
  
          >>> pipe = KandinskyV22ControlnetImg2ImgPipeline.from_pretrained(
          ...     \"kandinsky-community/kandinsky-2-2-controlnet-depth\", torch_dtype=torch.float16
          ... )
          >>> pipe = pipe.to(\"cuda\")
  
          >>> img = load_image(
          ...     \"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main\"
          ...     \"/kandinsky/cat.png\"
          ... ).resize((768, 768))
  
  
          >>> hint = make_hint(img, depth_estimator).unsqueeze(0).half().to(\"cuda\")
  
          >>> prompt = \"A robot, 4k photo\"
          >>> negative_prior_prompt = \"lowres, text, error, cropped, worst quality, low quality, jpeg artifacts, ugly, duplicate, morbid, mutilated, out of frame, extra fingers, mutated hands, poorly drawn hands, poorly drawn face, mutation, deformed, blurry, dehydrated, bad anatomy, bad proportions, extra limbs, cloned face, disfigured, gross proportions, malformed limbs, missing arms, missing legs, extra arms, extra legs, fused fingers, too many fingers, long neck, username, watermark, signature\"
  
          >>> generator = torch.Generator(device=\"cuda\").manual_seed(43)
  
          >>> img_emb = pipe_prior(prompt=prompt, image=img, strength=0.85, generator=generator)
          >>> negative_emb = pipe_prior(prompt=negative_prior_prompt, image=img, strength=1, generator=generator)
  
          >>> images = pipe(
          ...     image=img,
          ...     strength=0.5,
          ...     image_embeds=img_emb.image_embeds,
          ...     negative_image_embeds=negative_emb.image_embeds,
          ...     hint=hint,
          ...     num_inference_steps=50,
          ...     generator=generator,
          ...     height=768,
          ...     width=768,
          ... ).images
  
          >>> images[0].save(\"robot_cat.png\")
          ```
  """
  
  
  
  def 		UpperCamelCase    (					_UpperCAmelCase     :      List[Any]   , _UpperCAmelCase     :      List[Any]   , _UpperCAmelCase     :      Optional[Any]=8     )      -> Union[str, Any]:
  
  
  
  
  
  
  					'''simple docstring'''
  
  					_lowercase					:  Optional[Any]    			=      height // scale_factor**2
  					if height % scale_factor**2 != 0:
  										new_height += 1
  					_lowercase					:  Optional[int]    			=      width // scale_factor**2
  					if width % scale_factor**2 != 0:
  										new_width += 1
  					return new_height * scale_factor, new_width * scale_factor
  
  
  
  def 		UpperCamelCase    (					_UpperCAmelCase     :      int   , _UpperCAmelCase     :      List[str]=512   , _UpperCAmelCase     :      List[str]=512     )      -> Optional[Any]:
  
  
  
  
  
  
  					'''simple docstring'''
  
  					_lowercase					:  Union[str, Any]    			=      pil_image.resize((w, h)   , resample=Image.BICUBIC   , reducing_gap=1     )
  					_lowercase					:  List[Any]    			=      np.array(pil_image.convert("RGB"     )     )
  					_lowercase					:  Optional[int]    			=      arr.astype(np.floataa     ) / 127.5 - 1
  					_lowercase					:  Optional[int]    			=      np.transpose(_UpperCAmelCase   , [2, 0, 1]     )
  					_lowercase					:  List[str]    			=      torch.from_numpy(_UpperCAmelCase     ).unsqueeze(0     )
  					return image
  
  
  
  
  class      __lowercase	(	lowerCAmelCase__					):
  
  
  
  
  
  
  	def __init__(self							:   Dict			,  snake_case							:   Tuple			,  snake_case							:   Any			,  snake_case							:   Optional[Any]			,  )   -> Union[str, Any]:
  						super().__init__()
  
  						self.register_modules(
  						    unet=_lowerCamelCase			,  scheduler=_lowerCamelCase			,  movq=_lowerCamelCase			,  )
  						_lowercase					:  List[str]    			=      2 ** (len(self.movq.config.block_out_channels						) - 1)
  
  
  
  
  
  
  	def 			_a(self							:   Optional[int]			,  snake_case							:   Optional[int]			,  snake_case							:   Union[str, Any]			,  snake_case							:   Union[str, Any]						)   -> List[Any]:
  						_lowercase					:  Tuple    			=      min(int(num_inference_steps * strength						)			,  _lowerCamelCase						)
  
  						_lowercase					:  str    			=      max(num_inference_steps - init_timestep			,  0						)
  						_lowercase					:  str    			=      self.scheduler.timesteps[t_start:]
  
  						return timesteps, num_inference_steps - t_start
  
  
  
  
  
  
  	def 			_a(self							:   Union[str, Any]			,  snake_case							:   str			,  snake_case							:   Optional[int]			,  snake_case							:   Any			,  snake_case							:   Tuple			,  snake_case							:   Union[str, Any]			,  snake_case							:   Union[str, Any]			,  snake_case							:   int=None						)   -> Optional[int]:
  
  						if not isinstance(_lowerCamelCase			,  (torch.Tensor, PIL.Image.Image, list)						):
  											raise ValueError(
  											    F"""`image` has to be of type `torch.Tensor`, `PIL.Image.Image` or list but is {type(_lowerCamelCase						)}"""						)
  
  						_lowercase					:  Any    			=      image.to(device=_lowerCamelCase			,  dtype=_lowerCamelCase						)
  
  						_lowercase					:  Any    			=      batch_size * num_images_per_prompt
  
  						if image.shape[1] == 4:
  											_lowercase					:  Any    			=      image
  
  						else:
  											if isinstance(_lowerCamelCase			,  _lowerCamelCase						) and len(_lowerCamelCase						) != batch_size:
  																raise ValueError(
  																    F"""You have passed a list of generators of length {len(_lowerCamelCase						)}, but requested an effective batch"""
  																    F""" size of {batch_size}. Make sure the batch size matches the length of the generators."""						)
  
  											elif isinstance(_lowerCamelCase			,  _lowerCamelCase						):
  																_lowercase					:  int    			=      [
  																    self.movq.encode(image[i : i + 1]						).latent_dist.sample(generator[i]						) for i in range(_lowerCamelCase						)
  																]
  																_lowercase					:  List[str]    			=      torch.cat(_lowerCamelCase			,  dim=0						)
  											else:
  																_lowercase					:  Union[str, Any]    			=      self.movq.encode(_lowerCamelCase						).latent_dist.sample(_lowerCamelCase						)
  
  											_lowercase					:  Optional[int]    			=      self.movq.config.scaling_factor * init_latents
  
  						_lowercase					:  List[str]    			=      torch.cat([init_latents]			,  dim=0						)
  
  						_lowercase					:  List[str]    			=      init_latents.shape
  						_lowercase					:  Tuple    			=      randn_tensor(_lowerCamelCase			,  generator=_lowerCamelCase			,  device=_lowerCamelCase			,  dtype=_lowerCamelCase						)
  
  						# get latents
  						_lowercase					:  List[str]    			=      self.scheduler.add_noise(_lowerCamelCase			,  _lowerCamelCase			,  _lowerCamelCase						)
  
  						_lowercase					:  List[Any]    			=      init_latents
  
  						return latents
  
  
  
  
  
  
  	def 			_a(self							:   List[Any]			,  snake_case							:   int=0						)   -> List[str]:
  
  						if is_accelerate_available():
  											from accelerate import cpu_offload
  						else:
  											raise ImportError("Please install accelerate via `pip install accelerate`"						)
  
  						_lowercase					:  Optional[Any]    			=      torch.device(F"""cuda:{gpu_id}"""						)
  
  						_lowercase					:  Union[str, Any]    			=      [
  						    self.unet,
  						    self.movq,
  						]
  						for cpu_offloaded_model in models:
  											if cpu_offloaded_model is not None:
  																cpu_offload(_lowerCamelCase			,  _lowerCamelCase						)
  
  
  
  
  
  
  	def 			_a(self							:   Any			,  snake_case							:   Tuple=0						)   -> Dict:
  
  						if is_accelerate_available() and is_accelerate_version(">="			,  "0.17.0.dev0"						):
  											from accelerate import cpu_offload_with_hook
  						else:
  											raise ImportError("`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher."						)
  
  						_lowercase					:  str    			=      torch.device(F"""cuda:{gpu_id}"""						)
  
  						if self.device.type != "cpu":
  											self.to("cpu"			,  silence_dtype_warnings=_lowerCamelCase						)
  											torch.cuda.empty_cache()  # otherwise we don't see the memory savings (but they probably exist)
  
  						_lowercase					:  Union[str, Any]    			=      None
  						for cpu_offloaded_model in [self.unet, self.movq]:
  											_lowercase					:  Union[str, Any]    			=      cpu_offload_with_hook(_lowerCamelCase			,  _lowerCamelCase			,  prev_module_hook=_lowerCamelCase						)
  
  						# We'll offload the last model manually.
  						_lowercase					:  List[str]    			=      hook
  
  
  
  
  
  
  	@property
  	# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device
  	def 			_a(self							:   Union[str, Any]						)   -> Any:
  
  						if not hasattr(self.unet			,  "_hf_hook"						):
  											return self.device
  						for module in self.unet.modules():
  											if (
  											    hasattr(_lowerCamelCase			,  "_hf_hook"						)
  											    and hasattr(module._hf_hook			,  "execution_device"						)
  											    and module._hf_hook.execution_device is not None
  											):
  																return torch.device(module._hf_hook.execution_device						)
  						return self.device
  
  
  
  
  
  
  	@torch.no_grad()
  	@replace_example_docstring(_lowerCamelCase						)
  	def __call__(self							:   int			,  snake_case							:   List[Any]			,  snake_case							:   Tuple			,  snake_case							:   Optional[Any]			,  snake_case							:   int			,  snake_case							:   List[str] = 512			,  snake_case							:   str = 512			,  snake_case							:   List[str] = 100			,  snake_case							:   Dict = 4.0			,  snake_case							:   Union[str, Any] = 0.3			,  snake_case							:   Optional[Any] = 1			,  snake_case							:   Dict = None			,  snake_case							:   Optional[Any] = "pil"			,  snake_case							:   Tuple = True			,  )   -> Any:
  						_lowercase					:  Any    			=      self._execution_device
  
  						_lowercase					:  Dict    			=      guidance_scale > 1.0
  
  						if isinstance(_lowerCamelCase			,  _lowerCamelCase						):
  											_lowercase					:  Optional[int]    			=      torch.cat(_lowerCamelCase			,  dim=0						)
  						if isinstance(_lowerCamelCase			,  _lowerCamelCase						):
  											_lowercase					:  Union[str, Any]    			=      torch.cat(_lowerCamelCase			,  dim=0						)
  						if isinstance(_lowerCamelCase			,  _lowerCamelCase						):
  											_lowercase					:  Any    			=      torch.cat(_lowerCamelCase			,  dim=0						)
  
  						_lowercase					:  Tuple    			=      image_embeds.shape[0]
  
  						if do_classifier_free_guidance:
  											_lowercase					:  Union[str, Any]    			=      image_embeds.repeat_interleave(_lowerCamelCase			,  dim=0						)
  											_lowercase					:  int    			=      negative_image_embeds.repeat_interleave(_lowerCamelCase			,  dim=0						)
  											_lowercase					:  str    			=      hint.repeat_interleave(_lowerCamelCase			,  dim=0						)
  
  						_lowercase					:  Union[str, Any]    			=      torch.cat([negative_image_embeds, image_embeds]			,  dim=0						).to(dtype=self.unet.dtype			,  device=_lowerCamelCase						)
  						_lowercase					:  Optional[int]    			=      torch.cat([hint, hint]			,  dim=0						).to(dtype=self.unet.dtype			,  device=_lowerCamelCase						)
  
  						if not isinstance(_lowerCamelCase			,  _lowerCamelCase						):
  											_lowercase					:  Optional[int]    			=      [image]
  						if not all(isinstance(_lowerCamelCase			,  (PIL.Image.Image, torch.Tensor)						) for i in image						):
  											raise ValueError(
  											    F"""Input is in incorrect format: {[type(_lowerCamelCase						) for i in image]}. Currently, we only support  PIL image and pytorch tensor"""						)
  
  						_lowercase					:  Any    			=      torch.cat([prepare_image(_lowerCamelCase			,  _lowerCamelCase			,  _lowerCamelCase						) for i in image]			,  dim=0						)
  						_lowercase					:  Tuple    			=      image.to(dtype=image_embeds.dtype			,  device=_lowerCamelCase						)
  
  						_lowercase					:  Dict    			=      self.movq.encode(_lowerCamelCase						)["""latents"""]
  						_lowercase					:  List[str]    			=      latents.repeat_interleave(_lowerCamelCase			,  dim=0						)
  						self.scheduler.set_timesteps(_lowerCamelCase			,  device=_lowerCamelCase						)
  						_lowercase					:  Dict    			=      self.get_timesteps(_lowerCamelCase			,  _lowerCamelCase			,  _lowerCamelCase						)
  						_lowercase					:  Optional[Any]    			=      timesteps[:1].repeat(batch_size * num_images_per_prompt						)
  						_lowercase					:  List[str]    			=      downscale_height_and_width(_lowerCamelCase			,  _lowerCamelCase			,  self.movq_scale_factor						)
  						_lowercase					:  List[Any]    			=      self.prepare_latents(
  						    _lowerCamelCase			,  _lowerCamelCase			,  _lowerCamelCase			,  _lowerCamelCase			,  image_embeds.dtype			,  _lowerCamelCase			,  _lowerCamelCase						)
  						for i, t in enumerate(self.progress_bar(_lowerCamelCase						)						):
  											# expand the latents if we are doing classifier free guidance
  											_lowercase					:  str    			=      torch.cat([latents] * 2						) if do_classifier_free_guidance else latents
  
  											_lowercase					:  List[Any]    			=      {"""image_embeds""": image_embeds, """hint""": hint}
  											_lowercase					:  Optional[int]    			=      self.unet(
  											    sample=_lowerCamelCase			,  timestep=_lowerCamelCase			,  encoder_hidden_states=_lowerCamelCase			,  added_cond_kwargs=_lowerCamelCase			,  return_dict=_lowerCamelCase			,  )[0]
  
  											if do_classifier_free_guidance:
  																_lowercase					:  List[str]    			=      noise_pred.split(latents.shape[1]			,  dim=1						)
  																_lowercase					:  int    			=      noise_pred.chunk(2						)
  																_lowercase					:  Union[str, Any]    			=      variance_pred.chunk(2						)
  																_lowercase					:  Dict    			=      noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
  																_lowercase					:  int    			=      torch.cat([noise_pred, variance_pred_text]			,  dim=1						)
  
  											if not (
  											    hasattr(self.scheduler.config			,  "variance_type"						)
  											    and self.scheduler.config.variance_type in ["learned", "learned_range"]
  											):
  																_lowercase					:  Optional[Any]    			=      noise_pred.split(latents.shape[1]			,  dim=1						)
  
  											# compute the previous noisy sample x_t -> x_t-1
  
  											_lowercase					:  Dict    			=      self.scheduler.step(
  											    _lowerCamelCase			,  _lowerCamelCase			,  _lowerCamelCase			,  generator=_lowerCamelCase			,  )[0]
  
  						# post-processing
  						_lowercase					:  Dict    			=      self.movq.decode(_lowerCamelCase			,  force_not_quantize=_lowerCamelCase						)["""sample"""]
  
  						if output_type not in ["pt", "np", "pil"]:
  											raise ValueError(F"""Only the output types `pt`, `pil` and `np` are supported not output_type={output_type}"""						)
  
  						if output_type in ["np", "pil"]:
  											_lowercase					:  int    			=      image * 0.5 + 0.5
  											_lowercase					:  List[str]    			=      image.clamp(0			,  1						)
  											_lowercase					:  Dict    			=      image.cpu().permute(0			,  2			,  3			,  1						).float().numpy()
  
  						if output_type == "pil":
  											_lowercase					:  int    			=      self.numpy_to_pil(_lowerCamelCase						)
  
  						if not return_dict:
  											return (image,)
  
  						return ImagePipelineOutput(images=_lowerCamelCase						)
  
  
  
  
  
style_context: 
  import gc
  import os
  import tempfile
  import unittest
  
  import torch
  import torch.nn as nn
  import torch.nn.functional as F
  from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer
  
  from diffusers import AutoencoderKL, DDIMScheduler, StableDiffusionPipeline, UNetaDConditionModel
  from diffusers.loaders import AttnProcsLayers, LoraLoaderMixin
  from diffusers.models.attention_processor import (
      Attention,
      AttnProcessor,
      AttnProcessor2_0,
      LoRAAttnProcessor,
      LoRAAttnProcessor2_0,
      LoRAXFormersAttnProcessor,
      XFormersAttnProcessor,
  )
  from diffusers.utils import TEXT_ENCODER_ATTN_MODULE, floats_tensor, torch_device
  
  
  
  def 		UpperCamelCase    (					_UpperCAmelCase     :      nn.Module     )      -> Any:
  
  
  
  
  
  
  						'''simple docstring'''
  
  						_lowercase					:  Optional[int]    			=      {}
  						for name in unet.attn_processors.keys():
  												_lowercase					:  Any    			=      None if name.endswith("attn1.processor"     ) else unet.config.cross_attention_dim
  												if name.startswith("mid_block"     ):
  																		_lowercase					:  Any    			=      unet.config.block_out_channels[-1]
  												elif name.startswith("up_blocks"     ):
  																		_lowercase					:  List[Any]    			=      int(name[len("up_blocks."     )]     )
  																		_lowercase					:  Any    			=      list(reversed(unet.config.block_out_channels     )     )[block_id]
  												elif name.startswith("down_blocks"     ):
  																		_lowercase					:  Union[str, Any]    			=      int(name[len("down_blocks."     )]     )
  																		_lowercase					:  Dict    			=      unet.config.block_out_channels[block_id]
  												_lowercase					:  List[str]    			=      (
  												    LoRAAttnProcessor2_0 if hasattr(_UpperCAmelCase   , "scaled_dot_product_attention"     ) else LoRAAttnProcessor
  												)
  												_lowercase					:  Optional[Any]    			=      lora_attn_processor_class(
  												    hidden_size=_UpperCAmelCase   , cross_attention_dim=_UpperCAmelCase     )
  						_lowercase					:  Dict    			=      AttnProcsLayers(_UpperCAmelCase     )
  						return lora_attn_procs, unet_lora_layers
  
  
  
  def 		UpperCamelCase    (					_UpperCAmelCase     :      nn.Module     )      -> Any:
  
  
  
  
  
  
  						'''simple docstring'''
  
  						_lowercase					:  List[str]    			=      {}
  						_lowercase					:  Dict    			=      (
  						    LoRAAttnProcessor2_0 if hasattr(_UpperCAmelCase   , "scaled_dot_product_attention"     ) else LoRAAttnProcessor
  						)
  						for name, module in text_encoder.named_modules():
  												if name.endswith(_UpperCAmelCase     ):
  																		_lowercase					:  Tuple    			=      lora_attn_processor_class(
  																		    hidden_size=module.out_proj.out_features   , cross_attention_dim=_UpperCAmelCase     )
  						return text_lora_attn_procs
  
  
  
  def 		UpperCamelCase    (					_UpperCAmelCase     :      nn.Module     )      -> Union[str, Any]:
  
  
  
  
  
  
  						'''simple docstring'''
  
  						_lowercase					:  Union[str, Any]    			=      create_text_encoder_lora_attn_procs(_UpperCAmelCase     )
  						_lowercase					:  str    			=      AttnProcsLayers(_UpperCAmelCase     )
  						return text_encoder_lora_layers
  
  
  
  def 		UpperCamelCase    (					_UpperCAmelCase     :      str   , _UpperCAmelCase     :      int=False     )      -> List[Any]:
  
  
  
  
  
  
  						'''simple docstring'''
  
  						for _, attn_proc in text_lora_attn_procs.items():
  												# set up.weights
  												for layer_name, layer_module in attn_proc.named_modules():
  																		if layer_name.endswith("_lora"     ):
  																								_lowercase					:  Tuple    			=      (
  																								    torch.randn_like(layer_module.up.weight     )
  																								    if randn_weight
  																								    else torch.zeros_like(layer_module.up.weight     )
  																								)
  																								_lowercase					:  Dict    			=      torch.nn.Parameter(_UpperCAmelCase     )
  
  
  
  
  class      __lowercase	(	unittest.TestCase					):
  
  
  
  
  
  
  	def 			_a(self							:   str						)   -> Tuple:
  							torch.manual_seed(0						)
  							_lowercase					:  int    			=      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			,  )
  							_lowercase					:  Union[str, Any]    			=      DDIMScheduler(
  							    beta_start=0.0_00_85			,  beta_end=0.0_12			,  beta_schedule="scaled_linear"			,  clip_sample=snake_case			,  set_alpha_to_one=snake_case			,  steps_offset=1			,  )
  							torch.manual_seed(0						)
  							_lowercase					:  int    			=      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			,  )
  							_lowercase					:  Optional[int]    			=      CLIPTextConfig(
  							    bos_token_id=0			,  eos_token_id=2			,  hidden_size=32			,  intermediate_size=37			,  layer_norm_eps=1e-05			,  num_attention_heads=4			,  num_hidden_layers=5			,  pad_token_id=1			,  vocab_size=1000			,  )
  							_lowercase					:  List[Any]    			=      CLIPTextModel(snake_case						)
  							_lowercase					:  Dict    			=      CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip"						)
  
  							_lowercase			,						_lowercase					:  List[Any]    			=      create_unet_lora_layers(snake_case						)
  							_lowercase					:  Union[str, Any]    			=      create_text_encoder_lora_layers(snake_case						)
  
  							_lowercase					:  List[Any]    			=      {
  							    "unet": unet,
  							    "scheduler": scheduler,
  							    "vae": vae,
  							    "text_encoder": text_encoder,
  							    "tokenizer": tokenizer,
  							    "safety_checker": None,
  							    "feature_extractor": None,
  							}
  							_lowercase					:  Union[str, Any]    			=      {
  							    "unet_lora_layers": unet_lora_layers,
  							    "text_encoder_lora_layers": text_encoder_lora_layers,
  							    "unet_lora_attn_procs": unet_lora_attn_procs,
  							}
  							return pipeline_components, lora_components
  
  
  
  
  
  
  	def 			_a(self							:   List[Any]						)   -> Optional[Any]:
  							_lowercase					:  str    			=      1
  							_lowercase					:  str    			=      10
  							_lowercase					:  Any    			=      4
  							_lowercase					:  List[str]    			=      (32, 32)
  
  							_lowercase					:  Union[str, Any]    			=      torch.manual_seed(0						)
  							_lowercase					:  List[str]    			=      floats_tensor((batch_size, num_channels) + sizes						)
  							_lowercase					:  Dict    			=      torch.randint(1			,  snake_case			,  size=(batch_size, sequence_length)			,  generator=snake_case						)
  
  							_lowercase					:  Tuple    			=      {
  							    "prompt": "A painting of a squirrel eating a burger",
  							    "generator": generator,
  							    "num_inference_steps": 2,
  							    "guidance_scale": 6.0,
  							    "output_type": "numpy",
  							}
  
  							return noise, input_ids, pipeline_inputs
  
  							# copied from: https://colab.research.google.com/gist/sayakpaul/df2ef6e1ae6d8c10a49d859883b10860/scratchpad.ipynb
  
  
  
  
  
  
  	def 			_a(self							:   Union[str, Any]						)   -> int:
  							_lowercase					:  Any    			=      77
  
  							_lowercase					:  Any    			=      torch.randint(2			,  56			,  size=(1, max_seq_length)			,  generator=torch.manual_seed(0						)						)
  
  							_lowercase					:  int    			=      {}
  							_lowercase					:  int    			=      inputs
  							return prepared_inputs
  
  
  
  
  
  
  	def 			_a(self							:   Union[str, Any]			,  snake_case							:   Dict						)   -> List[Any]:
  							_lowercase			,						_lowercase					:  List[Any]    			=      self.get_dummy_components()
  							LoraLoaderMixin.save_lora_weights(
  							    save_directory=snake_case			,  unet_lora_layers=lora_components["unet_lora_layers"]			,  text_encoder_lora_layers=lora_components["text_encoder_lora_layers"]			,  )
  							self.assertTrue(os.path.isfile(os.path.join(snake_case			,  "pytorch_lora_weights.bin"						)						)						)
  
  
  
  
  
  
  	def 			_a(self							:   Any						)   -> Union[str, Any]:
  							_lowercase			,						_lowercase					:  int    			=      self.get_dummy_components()
  							_lowercase					:  List[str]    			=      StableDiffusionPipeline(**snake_case						)
  							_lowercase					:  Dict    			=      sd_pipe.to(snake_case						)
  							sd_pipe.set_progress_bar_config(disable=snake_case						)
  
  							_lowercase			,						_lowercase			,						_lowercase					:  Optional[int]    			=      self.get_dummy_inputs()
  
  							_lowercase					:  Any    			=      sd_pipe(**snake_case						).images
  							_lowercase					:  int    			=      original_images[0, -3:, -3:, -1]
  
  							with tempfile.TemporaryDirectory() as tmpdirname:
  													LoraLoaderMixin.save_lora_weights(
  													    save_directory=snake_case			,  unet_lora_layers=lora_components["unet_lora_layers"]			,  text_encoder_lora_layers=lora_components["text_encoder_lora_layers"]			,  )
  													self.assertTrue(os.path.isfile(os.path.join(snake_case			,  "pytorch_lora_weights.bin"						)						)						)
  													sd_pipe.load_lora_weights(snake_case						)
  
  							_lowercase					:  Dict    			=      sd_pipe(**snake_case						).images
  							_lowercase					:  List[Any]    			=      lora_images[0, -3:, -3:, -1]
  
  							# Outputs shouldn't match.
  							self.assertFalse(torch.allclose(torch.from_numpy(snake_case						)			,  torch.from_numpy(snake_case						)						)						)
  
  
  
  
  
  
  	def 			_a(self							:   Optional[int]						)   -> List[Any]:
  							_lowercase			,						_lowercase					:  str    			=      self.get_dummy_components()
  							_lowercase					:  Any    			=      StableDiffusionPipeline(**snake_case						)
  							_lowercase					:  Any    			=      sd_pipe.to(snake_case						)
  							sd_pipe.set_progress_bar_config(disable=snake_case						)
  
  							_lowercase			,						_lowercase			,						_lowercase					:  Optional[int]    			=      self.get_dummy_inputs()
  
  							_lowercase					:  Optional[int]    			=      sd_pipe(**snake_case						).images
  							_lowercase					:  Any    			=      original_images[0, -3:, -3:, -1]
  
  							with tempfile.TemporaryDirectory() as tmpdirname:
  													LoraLoaderMixin.save_lora_weights(
  													    save_directory=snake_case			,  unet_lora_layers=lora_components["unet_lora_layers"]			,  text_encoder_lora_layers=lora_components["text_encoder_lora_layers"]			,  safe_serialization=snake_case			,  )
  													self.assertTrue(os.path.isfile(os.path.join(snake_case			,  "pytorch_lora_weights.safetensors"						)						)						)
  													sd_pipe.load_lora_weights(snake_case						)
  
  							_lowercase					:  Any    			=      sd_pipe(**snake_case						).images
  							_lowercase					:  Optional[int]    			=      lora_images[0, -3:, -3:, -1]
  
  							# Outputs shouldn't match.
  							self.assertFalse(torch.allclose(torch.from_numpy(snake_case						)			,  torch.from_numpy(snake_case						)						)						)
  
  
  
  
  
  
  	def 			_a(self							:   str						)   -> Union[str, Any]:
  							_lowercase			,						_lowercase					:  Optional[Any]    			=      self.get_dummy_components()
  							_lowercase					:  int    			=      lora_components["unet_lora_attn_procs"]
  							_lowercase					:  str    			=      StableDiffusionPipeline(**snake_case						)
  							_lowercase					:  List[str]    			=      sd_pipe.to(snake_case						)
  							sd_pipe.set_progress_bar_config(disable=snake_case						)
  
  							_lowercase			,						_lowercase			,						_lowercase					:  Any    			=      self.get_dummy_inputs()
  
  							_lowercase					:  int    			=      sd_pipe(**snake_case						).images
  							_lowercase					:  List[str]    			=      original_images[0, -3:, -3:, -1]
  
  							with tempfile.TemporaryDirectory() as tmpdirname:
  													_lowercase					:  Optional[Any]    			=      sd_pipe.unet
  													unet.set_attn_processor(snake_case						)
  													unet.save_attn_procs(snake_case						)
  													self.assertTrue(os.path.isfile(os.path.join(snake_case			,  "pytorch_lora_weights.bin"						)						)						)
  													sd_pipe.load_lora_weights(snake_case						)
  
  							_lowercase					:  int    			=      sd_pipe(**snake_case						).images
  							_lowercase					:  int    			=      lora_images[0, -3:, -3:, -1]
  
  							# Outputs shouldn't match.
  							self.assertFalse(torch.allclose(torch.from_numpy(snake_case						)			,  torch.from_numpy(snake_case						)						)						)
  
  
  
  
  
  
  	def 			_a(self							:   Dict						)   -> List[str]:
  							_lowercase			,						_lowercase					:  Optional[Any]    			=      self.get_dummy_components()
  							_lowercase					:  List[Any]    			=      StableDiffusionPipeline(**snake_case						)
  
  							_lowercase					:  Tuple    			=      self.get_dummy_tokens()
  
  							# inference without lora
  							_lowercase					:  int    			=      pipe.text_encoder(**snake_case						)[0]
  							assert outputs_without_lora.shape == (1, 77, 32)
  
  							# create lora_attn_procs with zeroed out up.weights
  							_lowercase					:  str    			=      create_text_encoder_lora_attn_procs(pipe.text_encoder						)
  							set_lora_up_weights(snake_case			,  randn_weight=snake_case						)
  
  							# monkey patch
  							pipe._modify_text_encoder(snake_case						)
  
  							# verify that it's okay to release the text_attn_procs which holds the LoRAAttnProcessor.
  							del text_attn_procs
  							gc.collect()
  
  							# inference with lora
  							_lowercase					:  Dict    			=      pipe.text_encoder(**snake_case						)[0]
  							assert outputs_with_lora.shape == (1, 77, 32)
  
  							assert torch.allclose(
  							    snake_case			,  snake_case						), "lora_up_weight are all zero, so the lora outputs should be the same to without lora outputs"
  
  							# create lora_attn_procs with randn up.weights
  							_lowercase					:  Any    			=      create_text_encoder_lora_attn_procs(pipe.text_encoder						)
  							set_lora_up_weights(snake_case			,  randn_weight=snake_case						)
  
  							# monkey patch
  							pipe._modify_text_encoder(snake_case						)
  
  							# verify that it's okay to release the text_attn_procs which holds the LoRAAttnProcessor.
  							del text_attn_procs
  							gc.collect()
  
  							# inference with lora
  							_lowercase					:  Any    			=      pipe.text_encoder(**snake_case						)[0]
  							assert outputs_with_lora.shape == (1, 77, 32)
  
  							assert not torch.allclose(
  							    snake_case			,  snake_case						), "lora_up_weight are not zero, so the lora outputs should be different to without lora outputs"
  
  
  
  
  
  
  	def 			_a(self							:   str						)   -> Tuple:
  							_lowercase			,						_lowercase					:  List[Any]    			=      self.get_dummy_components()
  							_lowercase					:  str    			=      StableDiffusionPipeline(**snake_case						)
  
  							_lowercase					:  Dict    			=      self.get_dummy_tokens()
  
  							# inference without lora
  							_lowercase					:  Tuple    			=      pipe.text_encoder(**snake_case						)[0]
  							assert outputs_without_lora.shape == (1, 77, 32)
  
  							# create lora_attn_procs with randn up.weights
  							_lowercase					:  Optional[int]    			=      create_text_encoder_lora_attn_procs(pipe.text_encoder						)
  							set_lora_up_weights(snake_case			,  randn_weight=snake_case						)
  
  							# monkey patch
  							pipe._modify_text_encoder(snake_case						)
  
  							# verify that it's okay to release the text_attn_procs which holds the LoRAAttnProcessor.
  							del text_attn_procs
  							gc.collect()
  
  							# inference with lora
  							_lowercase					:  Union[str, Any]    			=      pipe.text_encoder(**snake_case						)[0]
  							assert outputs_with_lora.shape == (1, 77, 32)
  
  							assert not torch.allclose(
  							    snake_case			,  snake_case						), "lora outputs should be different to without lora outputs"
  
  							# remove monkey patch
  							pipe._remove_text_encoder_monkey_patch()
  
  							# inference with removed lora
  							_lowercase					:  Union[str, Any]    			=      pipe.text_encoder(**snake_case						)[0]
  							assert outputs_without_lora_removed.shape == (1, 77, 32)
  
  							assert torch.allclose(
  							    snake_case			,  snake_case						), "remove lora monkey patch should restore the original outputs"
  
  
  
  
  
  
  	def 			_a(self							:   Optional[int]						)   -> Dict:
  							_lowercase			,						_lowercase					:  Dict    			=      self.get_dummy_components()
  							_lowercase					:  Optional[Any]    			=      StableDiffusionPipeline(**snake_case						)
  							_lowercase					:  Union[str, Any]    			=      sd_pipe.to(snake_case						)
  							sd_pipe.set_progress_bar_config(disable=snake_case						)
  
  							_lowercase			,						_lowercase			,						_lowercase					:  str    			=      self.get_dummy_inputs()
  
  							with tempfile.TemporaryDirectory() as tmpdirname:
  													LoraLoaderMixin.save_lora_weights(
  													    save_directory=snake_case			,  unet_lora_layers=lora_components["unet_lora_layers"]			,  text_encoder_lora_layers=lora_components["text_encoder_lora_layers"]			,  )
  													self.assertTrue(os.path.isfile(os.path.join(snake_case			,  "pytorch_lora_weights.bin"						)						)						)
  													sd_pipe.load_lora_weights(snake_case						)
  
  							_lowercase					:  Dict    			=      sd_pipe(**snake_case						).images
  							_lowercase					:  int    			=      lora_images[0, -3:, -3:, -1]
  
  							_lowercase					:  List[str]    			=      sd_pipe(**snake_case			,  cross_attention_kwargs={"scale": 0.5}						).images
  							_lowercase					:  int    			=      lora_images_with_scale[0, -3:, -3:, -1]
  
  							# Outputs shouldn't match.
  							self.assertFalse(
  							    torch.allclose(torch.from_numpy(snake_case						)			,  torch.from_numpy(snake_case						)						)						)
  
  
  
  
  
  
  	def 			_a(self							:   Tuple						)   -> str:
  							with tempfile.TemporaryDirectory() as tmpdirname:
  													self.create_lora_weight_file(snake_case						)
  
  													_lowercase			,						_lowercase					:  str    			=      self.get_dummy_components()
  													_lowercase					:  str    			=      StableDiffusionPipeline(**snake_case						)
  													_lowercase					:  List[Any]    			=      sd_pipe.to(snake_case						)
  													sd_pipe.set_progress_bar_config(disable=snake_case						)
  
  													# check if vanilla attention processors are used
  													for _, module in sd_pipe.unet.named_modules():
  																			if isinstance(snake_case			,  snake_case						):
  																									self.assertIsInstance(module.processor			,  (AttnProcessor, AttnProcessor2_0)						)
  
              # load LoRA weight file
  													sd_pipe.load_lora_weights(snake_case						)
  
  													# check if lora attention processors are used
  													for _, module in sd_pipe.unet.named_modules():
  																			if isinstance(snake_case			,  snake_case						):
  																									_lowercase					:  Tuple    			=      (
  																									    LoRAAttnProcessor2_0 if hasattr(snake_case			,  "scaled_dot_product_attention"						) else LoRAAttnProcessor
  																									)
  																									self.assertIsInstance(module.processor			,  snake_case						)
  
  
  
  
  
  
  	@unittest.skipIf(torch_device != "cuda"			,  "This test is supposed to run on GPU"						)
  	def 			_a(self							:   List[str]						)   -> Union[str, Any]:
  							with tempfile.TemporaryDirectory() as tmpdirname:
  													self.create_lora_weight_file(snake_case						)
  
  													_lowercase			,						_lowercase					:  List[str]    			=      self.get_dummy_components()
  													_lowercase					:  str    			=      StableDiffusionPipeline(**snake_case						)
  													_lowercase					:  Tuple    			=      sd_pipe.to(snake_case						)
  													sd_pipe.set_progress_bar_config(disable=snake_case						)
  
  													# enable XFormers
  													sd_pipe.enable_xformers_memory_efficient_attention()
  
  													# check if xFormers attention processors are used
  													for _, module in sd_pipe.unet.named_modules():
  																			if isinstance(snake_case			,  snake_case						):
  																									self.assertIsInstance(module.processor			,  snake_case						)
  
              # load LoRA weight file
  													sd_pipe.load_lora_weights(snake_case						)
  
  													# check if lora attention processors are used
  													for _, module in sd_pipe.unet.named_modules():
  																			if isinstance(snake_case			,  snake_case						):
  																									self.assertIsInstance(module.processor			,  snake_case						)
  
  
  
  
  
  
  	@unittest.skipIf(torch_device != "cuda"			,  "This test is supposed to run on GPU"						)
  	def 			_a(self							:   List[str]						)   -> Any:
  							_lowercase			,						_lowercase					:  Tuple    			=      self.get_dummy_components()
  							_lowercase					:  List[Any]    			=      StableDiffusionPipeline(**snake_case						)
  							_lowercase					:  Union[str, Any]    			=      sd_pipe.to(snake_case						)
  							sd_pipe.set_progress_bar_config(disable=snake_case						)
  
  							_lowercase			,						_lowercase			,						_lowercase					:  List[Any]    			=      self.get_dummy_inputs()
  
  							# enable XFormers
  							sd_pipe.enable_xformers_memory_efficient_attention()
  
  							_lowercase					:  Tuple    			=      sd_pipe(**snake_case						).images
  							_lowercase					:  Any    			=      original_images[0, -3:, -3:, -1]
  
  							with tempfile.TemporaryDirectory() as tmpdirname:
  													LoraLoaderMixin.save_lora_weights(
  													    save_directory=snake_case			,  unet_lora_layers=lora_components["unet_lora_layers"]			,  text_encoder_lora_layers=lora_components["text_encoder_lora_layers"]			,  )
  													self.assertTrue(os.path.isfile(os.path.join(snake_case			,  "pytorch_lora_weights.bin"						)						)						)
  													sd_pipe.load_lora_weights(snake_case						)
  
  							_lowercase					:  Optional[int]    			=      sd_pipe(**snake_case						).images
  							_lowercase					:  Tuple    			=      lora_images[0, -3:, -3:, -1]
  
  							# Outputs shouldn't match.
  							self.assertFalse(torch.allclose(torch.from_numpy(snake_case						)			,  torch.from_numpy(snake_case						)						)						)
  
  
  
  
  