

"""simple docstring"""




import json
import os
from functools import lru_cache
from typing import Dict, List, Optional, Tuple, Union

import regex as re

from ...tokenization_utils import AddedToken, PreTrainedTokenizer
from ...tokenization_utils_base import BatchEncoding, EncodedInput
from ...utils import PaddingStrategy, logging


__UpperCAmelCase =				logging.get_logger(__name__)


__UpperCAmelCase =				{'vocab_file': 'vocab.json', 'merges_file': 'merges.txt'}

# See all LED models at https://huggingface.co/models?filter=LED
__UpperCAmelCase =				{
    'vocab_file': {
        'allenai/led-base-16384': 'https://huggingface.co/allenai/led-base-16384/resolve/main/vocab.json',
    },
    'merges_file': {
        'allenai/led-base-16384': 'https://huggingface.co/allenai/led-base-16384/resolve/main/merges.txt',
    },
    'tokenizer_file': {
        'allenai/led-base-16384': 'https://huggingface.co/allenai/led-base-16384/resolve/main/tokenizer.json',
    },
}

__UpperCAmelCase =				{
    'allenai/led-base-16384': 1_6384,
}
@lru_cache()
# Copied from transformers.models.bart.tokenization_bart.bytes_to_unicode
def   lowerCAmelCase						(					):
 '''simple docstring'''





 UpperCAmelCase__					:  Tuple					   =					(
     list(range(ord("""!"""      )							,    ord("""~"""      ) + 1      )      ) + list(range(ord("""¡"""      )							,    ord("""¬"""      ) + 1      )      ) + list(range(ord("""®"""      )							,    ord("""ÿ"""      ) + 1      )      )
 )
 UpperCAmelCase__					:  int					   =					bs[:]
 UpperCAmelCase__					:  Union[str, Any]					   =					0
 for b in range(2**8      ):
  if b not in bs:
   bs.append(__UpperCamelCase      )
   cs.append(2**8 + n      )
   n += 1
 UpperCAmelCase__					:  Tuple					   =					[chr(__UpperCamelCase      ) for n in cs]
 return dict(zip(__UpperCamelCase							,    __UpperCamelCase      )      )
def   lowerCAmelCase						(					__UpperCamelCase      ):
 '''simple docstring'''





 UpperCAmelCase__					:  int					   =					set()
 UpperCAmelCase__					:  Tuple					   =					word[0]
 for char in word[1:]:
  pairs.add((prev_char, char)      )
  UpperCAmelCase__					:  Optional[Any]					   =					char
 return pairs







class      __lowercase			(    __lowerCamelCase					):
  snake_case_				       =       VOCAB_FILES_NAMES
  snake_case_				       =       PRETRAINED_VOCAB_FILES_MAP
  snake_case_				       =       PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
  snake_case_				       =       ["""input_ids""", """attention_mask"""]

  def __init__(  self		:			Union[str, Any]					,A		:			Any					,A		:			Dict					,A		:			Optional[Any]="replace"					,A		:			Dict="<s>"					,A		:			str="</s>"					,A		:			str="</s>"					,A		:			Dict="<s>"					,A		:			List[str]="<unk>"					,A		:			Union[str, Any]="<pad>"					,A		:			Any="<mask>"					,A		:			str=False					,**A		:			Optional[Any]					,):






   '''simple docstring'''
   UpperCAmelCase__					:  List[str]					   =					AddedToken(A					,lstrip=A					,rstrip=A    ) if isinstance(A					,A    ) else bos_token
   UpperCAmelCase__					:  Any					   =					AddedToken(A					,lstrip=A					,rstrip=A    ) if isinstance(A					,A    ) else eos_token
   UpperCAmelCase__					:  List[str]					   =					AddedToken(A					,lstrip=A					,rstrip=A    ) if isinstance(A					,A    ) else sep_token
   UpperCAmelCase__					:  Tuple					   =					AddedToken(A					,lstrip=A					,rstrip=A    ) if isinstance(A					,A    ) else cls_token
   UpperCAmelCase__					:  Tuple					   =					AddedToken(A					,lstrip=A					,rstrip=A    ) if isinstance(A					,A    ) else unk_token
   UpperCAmelCase__					:  List[str]					   =					AddedToken(A					,lstrip=A					,rstrip=A    ) if isinstance(A					,A    ) else pad_token

   # Mask token behave like a normal word, i.e. include the space before it
   UpperCAmelCase__					:  Union[str, Any]					   =					AddedToken(A					,lstrip=A					,rstrip=A    ) if isinstance(A					,A    ) else mask_token

   super().__init__(
       errors=A					,bos_token=A					,eos_token=A					,unk_token=A					,sep_token=A					,cls_token=A					,pad_token=A					,mask_token=A					,add_prefix_space=A					,**A					,)

   with open(A					,encoding="""utf-8"""    ) as vocab_handle:
    UpperCAmelCase__					:  Tuple					   =					json.load(A    )
   UpperCAmelCase__					:  Any					   =					{v: k for k, v in self.encoder.items()}
   UpperCAmelCase__					:  List[Any]					   =					errors  # how to handle errors in decoding
   UpperCAmelCase__					:  List[str]					   =					bytes_to_unicode()
   UpperCAmelCase__					:  int					   =					{v: k for k, v in self.byte_encoder.items()}
   with open(A					,encoding="""utf-8"""    ) as merges_handle:
    UpperCAmelCase__					:  List[Any]					   =					merges_handle.read().split("""\n"""    )[1:-1]
   UpperCAmelCase__					:  Tuple					   =					[tuple(merge.split()    ) for merge in bpe_merges]
   UpperCAmelCase__					:  Any					   =					dict(zip(A					,range(len(A    )    )    )    )
   UpperCAmelCase__					:  Optional[Any]					   =					{}
   UpperCAmelCase__					:  Optional[int]					   =					add_prefix_space

   # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions
   UpperCAmelCase__					:  Union[str, Any]					   =					re.compile(R"""'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+"""    )

  @property
  # Copied from transformers.models.bart.tokenization_bart.BartTokenizer.vocab_size
  def    __lowercase       (  self		:			List[Any]    ):






   '''simple docstring'''
   return len(self.encoder    )

  def    __lowercase       (  self		:			Optional[Any]    ):






   '''simple docstring'''
   return dict(self.encoder					,**self.added_tokens_encoder    )

  def    __lowercase       (  self		:			Optional[int]					,A		:			Union[str, Any]    ):






   '''simple docstring'''
   if token in self.cache:
    return self.cache[token]
   UpperCAmelCase__					:  Optional[Any]					   =					tuple(A    )
   UpperCAmelCase__					:  int					   =					get_pairs(A    )

   if not pairs:
    return token

   while True:
    UpperCAmelCase__					:  str					   =					min(A					,key=lambda A    : self.bpe_ranks.get(A					,float("""inf"""    )    )    )
    if bigram not in self.bpe_ranks:
     break
    UpperCAmelCase__   ,      UpperCAmelCase__					:  Tuple					   =					bigram
    UpperCAmelCase__					:  Optional[Any]					   =					[]
    UpperCAmelCase__					:  Any					   =					0
    while i < len(A    ):
     try:
      UpperCAmelCase__					:  Optional[Any]					   =					word.index(A					,A    )
     except ValueError:
      new_word.extend(word[i:]    )
      break
     else:
      new_word.extend(word[i:j]    )
      UpperCAmelCase__					:  int					   =					j

     if word[i] == first and i < len(A    ) - 1 and word[i + 1] == second:
      new_word.append(first + second    )
      i += 2
     else:
      new_word.append(word[i]    )
      i += 1
    UpperCAmelCase__					:  List[str]					   =					tuple(A    )
    UpperCAmelCase__					:  str					   =					new_word
    if len(A    ) == 1:
     break
    else:
     UpperCAmelCase__					:  str					   =					get_pairs(A    )
   UpperCAmelCase__					:  int					   =					""" """.join(A    )
   UpperCAmelCase__					:  List[str]					   =					word
   return word

  def    __lowercase       (  self		:			Optional[Any]					,A		:			Any    ):






   '''simple docstring'''
   UpperCAmelCase__					:  Any					   =					[]
   for token in re.findall(self.pat					,A    ):
    UpperCAmelCase__					:  Any					   =					"""""".join(
        self.byte_encoder[b] for b in token.encode("""utf-8"""    )    )  # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case)
    bpe_tokens.extend(bpe_token for bpe_token in self.bpe(A    ).split(""" """    )    )
   return bpe_tokens

  def    __lowercase       (  self		:			Dict					,A		:			int    ):






   '''simple docstring'''
   return self.encoder.get(A					,self.encoder.get(self.unk_token    )    )

  def    __lowercase       (  self		:			Dict					,A		:			Optional[Any]    ):






   '''simple docstring'''
   return self.decoder.get(A    )

  def    __lowercase       (  self		:			Optional[Any]					,A		:			int    ):






   '''simple docstring'''
   UpperCAmelCase__					:  int					   =					"""""".join(A    )
   UpperCAmelCase__					:  Dict					   =					bytearray([self.byte_decoder[c] for c in text]    ).decode("""utf-8"""					,errors=self.errors    )
   return text

  def    __lowercase       (  self		:			Optional[int]					,A		:			str					,A		:			Optional[str] = None    ):






   '''simple docstring'''
   if not os.path.isdir(A    ):
    logger.error(f"Vocabulary path ({save_directory}) should be a directory"    )
    return
   UpperCAmelCase__					:  Any					   =					os.path.join(
       A					,(filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""]    )
   UpperCAmelCase__					:  List[str]					   =					os.path.join(
       A					,(filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""merges_file"""]    )

   with open(A					,"""w"""					,encoding="""utf-8"""    ) as f:
    f.write(json.dumps(self.encoder					,indent=2					,sort_keys=A					,ensure_ascii=A    ) + """\n"""    )

   UpperCAmelCase__					:  Any					   =					0
   with open(A					,"""w"""					,encoding="""utf-8"""    ) as writer:
    writer.write("""#version: 0.2\n"""    )
    for bpe_tokens, token_index in sorted(self.bpe_ranks.items()					,key=lambda A    : kv[1]    ):
     if index != token_index:
      logger.warning(
          f"Saving vocabulary to {merge_file}: BPE merge indices are not consecutive."
          """ Please check that the tokenizer is not corrupted!"""    )
      UpperCAmelCase__					:  Optional[int]					   =					token_index
     writer.write(""" """.join(A    ) + """\n"""    )
     index += 1

   return vocab_file, merge_file

  def    __lowercase       (  self		:			Union[str, Any]					,A		:			List[int]					,A		:			Optional[List[int]] = None    ):






   '''simple docstring'''
   if token_ids_a is None:
    return [self.cls_token_id] + token_ids_a + [self.sep_token_id]
   UpperCAmelCase__					:  Dict					   =					[self.cls_token_id]
   UpperCAmelCase__					:  Optional[Any]					   =					[self.sep_token_id]
   return cls + token_ids_a + sep + sep + token_ids_a + sep

  def    __lowercase       (  self		:			int					,A		:			List[int]					,A		:			Optional[List[int]] = None					,A		:			bool = False    ):






   '''simple docstring'''
   if already_has_special_tokens:
    return super().get_special_tokens_mask(
        token_ids_a=A					,token_ids_a=A					,already_has_special_tokens=A    )

   if token_ids_a is None:
    return [1] + ([0] * len(A    )) + [1]
   return [1] + ([0] * len(A    )) + [1, 1] + ([0] * len(A    )) + [1]

  def    __lowercase       (  self		:			Tuple					,A		:			List[int]					,A		:			Optional[List[int]] = None    ):






   '''simple docstring'''
   UpperCAmelCase__					:  str					   =					[self.sep_token_id]
   UpperCAmelCase__					:  List[str]					   =					[self.cls_token_id]

   if token_ids_a is None:
    return len(cls + token_ids_a + sep    ) * [0]
   return len(cls + token_ids_a + sep + sep + token_ids_a + sep    ) * [0]

  def    __lowercase       (  self		:			Any					,A		:			str					,A		:			List[Any]=False					,**A		:			Tuple    ):






   '''simple docstring'''
   UpperCAmelCase__					:  Any					   =					kwargs.pop("""add_prefix_space"""					,self.add_prefix_space    )
   if (is_split_into_words or add_prefix_space) and (len(A    ) > 0 and not text[0].isspace()):
    UpperCAmelCase__					:  Dict					   =					""" """ + text
   return (text, kwargs)




  def    __lowercase       (  self		:			Dict					,A		:			Union[Dict[str, EncodedInput], BatchEncoding]					,A		:			Optional[int] = None					,A		:			PaddingStrategy = PaddingStrategy.DO_NOT_PAD					,A		:			Optional[int] = None					,A		:			Optional[bool] = None					,):






   '''simple docstring'''
   UpperCAmelCase__					:  Union[str, Any]					   =					super()._pad(
       encoded_inputs=A					,max_length=A					,padding_strategy=A					,pad_to_multiple_of=A					,return_attention_mask=A					,)

   # Load from model defaults
   if return_attention_mask is None:
    UpperCAmelCase__					:  str					   =					"""attention_mask""" in self.model_input_names

   if return_attention_mask and "global_attention_mask" in encoded_inputs:
    UpperCAmelCase__					:  Optional[int]					   =					encoded_inputs[self.model_input_names[0]]
    # `global_attention_mask` need to have the same length as other (sequential) inputs.
    UpperCAmelCase__					:  Tuple					   =					len(encoded_inputs["""global_attention_mask"""]    ) != len(A    )

    if needs_to_be_padded:
     UpperCAmelCase__					:  List[Any]					   =					len(A    ) - len(encoded_inputs["""global_attention_mask"""]    )

     if self.padding_side == "right":
      # Use `-1` since `0` in `global_attention_mask` means `local attention` instead of `not to attend`
      UpperCAmelCase__					:  Tuple					   =					(
          encoded_inputs["""global_attention_mask"""] + [-1] * difference
      )
     elif self.padding_side == "left":
      UpperCAmelCase__					:  Dict					   =					[-1] * difference + encoded_inputs[
          """global_attention_mask"""
      ]
     else:
      raise ValueError("""Invalid padding strategy:""" + str(self.padding_side    )    )

   return encoded_inputs








"""simple docstring"""




from typing import List, Optional, Union

import torch
from transformers import (
    XLMRobertaTokenizer,
)

from ...models import UNetaDConditionModel, VQModel
from ...pipelines import DiffusionPipeline
from ...pipelines.pipeline_utils import ImagePipelineOutput
from ...schedulers import DDIMScheduler, DDPMScheduler
from ...utils import (
    is_accelerate_available,
    is_accelerate_version,
    logging,
    randn_tensor,
    replace_example_docstring,
)
from .text_encoder import MultilingualCLIP


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

__UpperCAmelCase =				'\n    Examples:\n        ```py\n        >>> from diffusers import KandinskyPipeline, KandinskyPriorPipeline\n        >>> import torch\n\n        >>> pipe_prior = KandinskyPriorPipeline.from_pretrained("kandinsky-community/Kandinsky-2-1-prior")\n        >>> pipe_prior.to("cuda")\n\n        >>> prompt = "red cat, 4k photo"\n        >>> out = pipe_prior(prompt)\n        >>> image_emb = out.image_embeds\n        >>> negative_image_emb = out.negative_image_embeds\n\n        >>> pipe = KandinskyPipeline.from_pretrained("kandinsky-community/kandinsky-2-1")\n        >>> pipe.to("cuda")\n\n        >>> image = pipe(\n        ...     prompt,\n        ...     image_embeds=image_emb,\n        ...     negative_image_embeds=negative_image_emb,\n        ...     height=768,\n        ...     width=768,\n        ...     num_inference_steps=100,\n        ... ).images\n\n        >>> image[0].save("cat.png")\n        ```\n'
def   lowerCAmelCase						(					__UpperCamelCase							,    __UpperCamelCase							,    __UpperCamelCase=8      ):
 '''simple docstring'''





 UpperCAmelCase__					:  Tuple					   =					h // scale_factor**2
 if h % scale_factor**2 != 0:
  new_h += 1
 UpperCAmelCase__					:  Any					   =					w // scale_factor**2
 if w % scale_factor**2 != 0:
  new_w += 1
 return new_h * scale_factor, new_w * scale_factor







class      __lowercase			(    __lowerCamelCase					):

  def __init__(  self		:			str					,A		:			MultilingualCLIP					,A		:			XLMRobertaTokenizer					,A		:			UNetaDConditionModel					,A		:			Union[DDIMScheduler, DDPMScheduler]					,A		:			VQModel					,):






   '''simple docstring'''
   super().__init__()

   self.register_modules(
       text_encoder=A					,tokenizer=A					,unet=A					,scheduler=A					,movq=A					,)
   UpperCAmelCase__					:  Optional[Any]					   =					2 ** (len(self.movq.config.block_out_channels    ) - 1)

  def    __lowercase       (  self		:			Dict					,A		:			Any					,A		:			Tuple					,A		:			Dict					,A		:			int					,A		:			str					,A		:			List[str]    ):






   '''simple docstring'''
   if latents is None:
    UpperCAmelCase__					:  Any					   =					randn_tensor(A					,generator=A					,device=A					,dtype=A    )
   else:
    if latents.shape != shape:
     raise ValueError(f"Unexpected latents shape, got {latents.shape}, expected {shape}"    )
    UpperCAmelCase__					:  int					   =					latents.to(A    )

   UpperCAmelCase__					:  Any					   =					latents * scheduler.init_noise_sigma
   return latents

  def    __lowercase       (  self		:			Optional[int]					,A		:			List[Any]					,A		:			Optional[Any]					,A		:			str					,A		:			Optional[Any]					,A		:			str=None					,):






   '''simple docstring'''
   UpperCAmelCase__					:  List[Any]					   =					len(A    ) if isinstance(A					,A    ) else 1
   # get prompt text embeddings
   UpperCAmelCase__					:  List[Any]					   =					self.tokenizer(
       A					,padding="""max_length"""					,truncation=A					,max_length=77					,return_attention_mask=A					,add_special_tokens=A					,return_tensors="""pt"""					,)

   UpperCAmelCase__					:  List[str]					   =					text_inputs.input_ids
   UpperCAmelCase__					:  Any					   =					self.tokenizer(A					,padding="""longest"""					,return_tensors="""pt"""    ).input_ids

   if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(A					,A    ):
    UpperCAmelCase__					:  List[str]					   =					self.tokenizer.batch_decode(untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1]    )
    logger.warning(
        """The following part of your input was truncated because CLIP can only handle sequences up to"""
        f" {self.tokenizer.model_max_length} tokens: {removed_text}"    )

   UpperCAmelCase__					:  str					   =					text_input_ids.to(A    )
   UpperCAmelCase__					:  Optional[Any]					   =					text_inputs.attention_mask.to(A    )

   UpperCAmelCase__   ,      UpperCAmelCase__					:  Tuple					   =					self.text_encoder(
       input_ids=A					,attention_mask=A    )

   UpperCAmelCase__					:  Optional[int]					   =					prompt_embeds.repeat_interleave(A					,dim=0    )
   UpperCAmelCase__					:  Optional[int]					   =					text_encoder_hidden_states.repeat_interleave(A					,dim=0    )
   UpperCAmelCase__					:  List[str]					   =					text_mask.repeat_interleave(A					,dim=0    )

   if do_classifier_free_guidance:
    UpperCAmelCase__					:  List[str]
    if negative_prompt is None:
     UpperCAmelCase__					:  List[Any]					   =					[""""""] * batch_size
    elif type(A    ) is not type(A    ):
     raise TypeError(
         f"`negative_prompt` should be the same type to `prompt`, but got {type(A    )} !="
         f" {type(A    )}."    )
    elif isinstance(A					,A    ):
     UpperCAmelCase__					:  Any					   =					[negative_prompt]
    elif batch_size != len(A    ):
     raise ValueError(
         f"`negative_prompt`: {negative_prompt} has batch size {len(A    )}, but `prompt`:"
         f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
         """ the batch size of `prompt`."""    )
    else:
     UpperCAmelCase__					:  List[Any]					   =					negative_prompt

    UpperCAmelCase__					:  Any					   =					self.tokenizer(
        A					,padding="""max_length"""					,max_length=77					,truncation=A					,return_attention_mask=A					,add_special_tokens=A					,return_tensors="""pt"""					,)
    UpperCAmelCase__					:  Optional[int]					   =					uncond_input.input_ids.to(A    )
    UpperCAmelCase__					:  str					   =					uncond_input.attention_mask.to(A    )

    UpperCAmelCase__   ,      UpperCAmelCase__					:  Dict					   =					self.text_encoder(
        input_ids=A					,attention_mask=A    )

    # duplicate unconditional embeddings for each generation per prompt, using mps friendly method

    UpperCAmelCase__					:  Any					   =					negative_prompt_embeds.shape[1]
    UpperCAmelCase__					:  Any					   =					negative_prompt_embeds.repeat(1					,A    )
    UpperCAmelCase__					:  str					   =					negative_prompt_embeds.view(batch_size * num_images_per_prompt					,A    )

    UpperCAmelCase__					:  Dict					   =					uncond_text_encoder_hidden_states.shape[1]
    UpperCAmelCase__					:  Any					   =					uncond_text_encoder_hidden_states.repeat(1					,A					,1    )
    UpperCAmelCase__					:  Any					   =					uncond_text_encoder_hidden_states.view(
        batch_size * num_images_per_prompt					,A					,-1    )
    UpperCAmelCase__					:  List[Any]					   =					uncond_text_mask.repeat_interleave(A					,dim=0    )

    # done duplicates

    # For classifier free guidance, we need to do two forward passes.
    # Here we concatenate the unconditional and text embeddings into a single batch
    # to avoid doing two forward passes
    UpperCAmelCase__					:  Any					   =					torch.cat([negative_prompt_embeds, prompt_embeds]    )
    UpperCAmelCase__					:  int					   =					torch.cat([uncond_text_encoder_hidden_states, text_encoder_hidden_states]    )

    UpperCAmelCase__					:  str					   =					torch.cat([uncond_text_mask, text_mask]    )

   return prompt_embeds, text_encoder_hidden_states, text_mask

  def    __lowercase       (  self		:			Tuple					,A		:			Dict=0    ):






   '''simple docstring'''
   if is_accelerate_available():
    from accelerate import cpu_offload
   else:
    raise ImportError("""Please install accelerate via `pip install accelerate`"""    )

   UpperCAmelCase__					:  str					   =					torch.device(f"cuda:{gpu_id}"    )

   UpperCAmelCase__					:  Tuple					   =					[
       self.unet,
       self.text_encoder,
       self.movq,
   ]
   for cpu_offloaded_model in models:
    if cpu_offloaded_model is not None:
     cpu_offload(A					,A    )

  def    __lowercase       (  self		:			int					,A		:			Optional[Any]=0    ):






   '''simple docstring'''
   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."""    )

   UpperCAmelCase__					:  List[str]					   =					torch.device(f"cuda:{gpu_id}"    )

   if self.device.type != "cpu":
    self.to("""cpu"""					,silence_dtype_warnings=A    )
    torch.cuda.empty_cache()  # otherwise we don't see the memory savings (but they probably exist)

   UpperCAmelCase__					:  List[str]					   =					None
   for cpu_offloaded_model in [self.text_encoder, self.unet, self.movq]:
    UpperCAmelCase__   ,      UpperCAmelCase__					:  Union[str, Any]					   =					cpu_offload_with_hook(A					,A					,prev_module_hook=A    )

   if self.safety_checker is not None:
    UpperCAmelCase__   ,      UpperCAmelCase__					:  Optional[int]					   =					cpu_offload_with_hook(self.safety_checker					,A					,prev_module_hook=A    )

   # We'll offload the last model manually.
   UpperCAmelCase__					:  Any					   =					hook

  @property
  # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device
  def    __lowercase       (  self		:			List[Any]    ):






   '''simple docstring'''
   if not hasattr(self.unet					,"""_hf_hook"""    ):
    return self.device
   for module in self.unet.modules():
    if (
        hasattr(A					,"""_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(A    )
  def __call__(  self		:			Union[str, Any]					,A		:			Union[str, List[str]]					,A		:			Union[torch.FloatTensor, List[torch.FloatTensor]]					,A		:			Union[torch.FloatTensor, List[torch.FloatTensor]]					,A		:			Optional[Union[str, List[str]]] = None					,A		:			int = 512					,A		:			int = 512					,A		:			int = 100					,A		:			float = 4.0					,A		:			int = 1					,A		:			Optional[Union[torch.Generator, List[torch.Generator]]] = None					,A		:			Optional[torch.FloatTensor] = None					,A		:			Optional[str] = "pil"					,A		:			bool = True					,):






   '''simple docstring'''

   if isinstance(A					,A    ):
    UpperCAmelCase__					:  str					   =					1
   elif isinstance(A					,A    ):
    UpperCAmelCase__					:  Tuple					   =					len(A    )
   else:
    raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(A    )}"    )

   UpperCAmelCase__					:  Optional[int]					   =					self._execution_device

   UpperCAmelCase__					:  Dict					   =					batch_size * num_images_per_prompt
   UpperCAmelCase__					:  Union[str, Any]					   =					guidance_scale > 1.0

   UpperCAmelCase__   ,      UpperCAmelCase__   ,      UpperCAmelCase__					:  Optional[int]					   =					self._encode_prompt(
       A					,A					,A					,A					,A    )

   if isinstance(A					,A    ):
    UpperCAmelCase__					:  Dict					   =					torch.cat(A					,dim=0    )
   if isinstance(A					,A    ):
    UpperCAmelCase__					:  Dict					   =					torch.cat(A					,dim=0    )

   if do_classifier_free_guidance:
    UpperCAmelCase__					:  Optional[int]					   =					image_embeds.repeat_interleave(A					,dim=0    )
    UpperCAmelCase__					:  Tuple					   =					negative_image_embeds.repeat_interleave(A					,dim=0    )

   UpperCAmelCase__					:  List[str]					   =					torch.cat([negative_image_embeds, image_embeds]					,dim=0    ).to(
       dtype=prompt_embeds.dtype					,device=A    )

   self.scheduler.set_timesteps(A					,device=A    )
   UpperCAmelCase__					:  int					   =					self.scheduler.timesteps

   UpperCAmelCase__					:  Union[str, Any]					   =					self.unet.config.in_channels

   UpperCAmelCase__   ,      UpperCAmelCase__					:  Dict					   =					get_new_h_w(A					,A					,self.movq_scale_factor    )

   # create initial latent
   UpperCAmelCase__					:  Dict					   =					self.prepare_latents(
       (batch_size, num_channels_latents, height, width)					,text_encoder_hidden_states.dtype					,A					,A					,A					,self.scheduler					,)

   for i, t in enumerate(self.progress_bar(A    )    ):
    # expand the latents if we are doing classifier free guidance
    UpperCAmelCase__					:  Optional[Any]					   =					torch.cat([latents] * 2    ) if do_classifier_free_guidance else latents

    UpperCAmelCase__					:  Optional[Any]					   =					{"""text_embeds""": prompt_embeds, """image_embeds""": image_embeds}
    UpperCAmelCase__					:  Any					   =					self.unet(
        sample=A					,timestep=A					,encoder_hidden_states=A					,added_cond_kwargs=A					,return_dict=A					,)[0]

    if do_classifier_free_guidance:
     UpperCAmelCase__   ,      UpperCAmelCase__					:  List[str]					   =					noise_pred.split(latents.shape[1]					,dim=1    )
     UpperCAmelCase__   ,      UpperCAmelCase__					:  Any					   =					noise_pred.chunk(2    )
     UpperCAmelCase__   ,      UpperCAmelCase__					:  str					   =					variance_pred.chunk(2    )
     UpperCAmelCase__					:  int					   =					noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
     UpperCAmelCase__					:  List[Any]					   =					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"]
    ):
     UpperCAmelCase__   ,      UpperCAmelCase__					:  List[Any]					   =					noise_pred.split(latents.shape[1]					,dim=1    )

    # compute the previous noisy sample x_t -> x_t-1
    UpperCAmelCase__					:  Optional[Any]					   =					self.scheduler.step(
        A					,A					,A					,generator=A					,).prev_sample
   # post-processing
   UpperCAmelCase__					:  List[Any]					   =					self.movq.decode(A					,force_not_quantize=A    )["""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"]:
    UpperCAmelCase__					:  Union[str, Any]					   =					image * 0.5 + 0.5
    UpperCAmelCase__					:  Optional[Any]					   =					image.clamp(0					,1    )
    UpperCAmelCase__					:  Dict					   =					image.cpu().permute(0					,2					,3					,1    ).float().numpy()

   if output_type == "pil":
    UpperCAmelCase__					:  List[str]					   =					self.numpy_to_pil(A    )

   if not return_dict:
    return (image,)

   return ImagePipelineOutput(images=A    )





