
'''simple docstring'''





import types
from typing import List, Optional, Tuple, Union

import torch
from transformers import CLIPTextModelWithProjection, CLIPTokenizer
from transformers.models.clip.modeling_clip import CLIPTextModelOutput

from diffusers.models import PriorTransformer
from diffusers.pipelines import DiffusionPipeline, StableDiffusionImageVariationPipeline
from diffusers.schedulers import UnCLIPScheduler
from diffusers.utils import logging, randn_tensor


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







def snake_case_    (				self      ,					lowercase__      ,					lowercase__      ,					lowercase__      ,					lowercase__		):
  UpperCAmelCase__			:				List[str]												=       image.to(device=lowercase__		)
  UpperCAmelCase__			:				Dict												=       image  # take image as image_embeddings
  UpperCAmelCase__			:				Any												=       image_embeddings.unsqueeze(1		)

  # duplicate image embeddings for each generation per prompt, using mps friendly method
  UpperCAmelCase__					, UpperCAmelCase__					, UpperCAmelCase__			:				int												=       image_embeddings.shape
  UpperCAmelCase__			:				int												=       image_embeddings.repeat(1      ,					lowercase__      ,					1		)
  UpperCAmelCase__			:				List[Any]												=       image_embeddings.view(bs_embed * num_images_per_prompt      ,					lowercase__      ,					-1		)

  if do_classifier_free_guidance:
    UpperCAmelCase__			:				str												=       torch.zeros_like(lowercase__		)

    # 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__			:				List[Any]												=       torch.cat([uncond_embeddings, image_embeddings]		)

  return image_embeddings






class        UpperCAmelCase_       (						A							):

 '''simple docstring'''







 def __init__(				self		:     List[str] ,							snake_case__		:     PriorTransformer ,							snake_case__		:     CLIPTokenizer ,							snake_case__		:     CLIPTextModelWithProjection ,							snake_case__		:     UnCLIPScheduler ,							snake_case__		:     Optional[dict] = None ,							):



   '''simple docstring'''




   super().__init__()

   UpperCAmelCase__			:				int												=       {"image_encoder": None} if decoder_pipe_kwargs is None else decoder_pipe_kwargs

   UpperCAmelCase__			:				str												=       decoder_pipe_kwargs.get("torch_dtype" ,							snake_case__   ) or prior.dtype

   UpperCAmelCase__			:				str												=       StableDiffusionImageVariationPipeline.from_pretrained(
       "lambdalabs/sd-image-variations-diffusers" ,							**snake_case__   )

   # replace `_encode_image` method
   UpperCAmelCase__			:				List[str]												=       types.MethodType(_encode_image ,							self.decoder_pipe   )

   self.register_modules(
       prior=snake_case__ ,							tokenizer=snake_case__ ,							text_encoder=snake_case__ ,							prior_scheduler=snake_case__ ,							)







 def        UpperCamelCase     (				self		:     Dict ,							snake_case__		:     int ,							snake_case__		:     int ,							snake_case__		:     Dict ,							snake_case__		:     int ,							snake_case__		:     Optional[Union[CLIPTextModelOutput, Tuple]] = None ,							snake_case__		:     Optional[torch.Tensor] = None ,							):



   '''simple docstring'''




   if text_model_output is None:
     UpperCAmelCase__			:				List[str]												=       len(snake_case__   ) if isinstance(snake_case__ ,							snake_case__   ) else 1
     # get prompt text embeddings
     UpperCAmelCase__			:				List[str]												=       self.tokenizer(
         snake_case__ ,							padding="max_length" ,							max_length=self.tokenizer.model_max_length ,							return_tensors="pt" ,							)
     UpperCAmelCase__			:				str												=       text_inputs.input_ids
     UpperCAmelCase__			:				Union[str, Any]												=       text_inputs.attention_mask.bool().to(snake_case__   )

     if text_input_ids.shape[-1] > self.tokenizer.model_max_length:
       UpperCAmelCase__			:				Dict												=       self.tokenizer.batch_decode(text_input_ids[:, self.tokenizer.model_max_length :]   )
       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__			:				Optional[int]												=       text_input_ids[:, : self.tokenizer.model_max_length]

     UpperCAmelCase__			:				Any												=       self.text_encoder(text_input_ids.to(snake_case__   )   )

     UpperCAmelCase__			:				Optional[int]												=       text_encoder_output.text_embeds
     UpperCAmelCase__			:				Any												=       text_encoder_output.last_hidden_state

   else:
     UpperCAmelCase__			:				Optional[int]												=       text_model_output[0].shape[0]
     UpperCAmelCase__					, UpperCAmelCase__			:				Optional[Any]												=       text_model_output[0], text_model_output[1]
     UpperCAmelCase__			:				List[str]												=       text_attention_mask

   UpperCAmelCase__			:				Dict												=       text_embeddings.repeat_interleave(snake_case__ ,							dim=0   )
   UpperCAmelCase__			:				Optional[int]												=       text_encoder_hidden_states.repeat_interleave(snake_case__ ,							dim=0   )
   UpperCAmelCase__			:				Tuple												=       text_mask.repeat_interleave(snake_case__ ,							dim=0   )

   if do_classifier_free_guidance:
     UpperCAmelCase__			:				Optional[Any]												=       [""] * batch_size

     UpperCAmelCase__			:				Union[str, Any]												=       self.tokenizer(
         snake_case__ ,							padding="max_length" ,							max_length=self.tokenizer.model_max_length ,							truncation=snake_case__ ,							return_tensors="pt" ,							)
     UpperCAmelCase__			:				Union[str, Any]												=       uncond_input.attention_mask.bool().to(snake_case__   )
     UpperCAmelCase__			:				List[str]												=       self.text_encoder(uncond_input.input_ids.to(snake_case__   )   )

     UpperCAmelCase__			:				Optional[int]												=       uncond_embeddings_text_encoder_output.text_embeds
     UpperCAmelCase__			:				List[Any]												=       uncond_embeddings_text_encoder_output.last_hidden_state

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

     UpperCAmelCase__			:				Tuple												=       uncond_embeddings.shape[1]
     UpperCAmelCase__			:				List[str]												=       uncond_embeddings.repeat(1 ,							snake_case__   )
     UpperCAmelCase__			:				Dict												=       uncond_embeddings.view(batch_size * num_images_per_prompt ,							snake_case__   )

     UpperCAmelCase__			:				int												=       uncond_text_encoder_hidden_states.shape[1]
     UpperCAmelCase__			:				int												=       uncond_text_encoder_hidden_states.repeat(1 ,							snake_case__ ,							1   )
     UpperCAmelCase__			:				Optional[int]												=       uncond_text_encoder_hidden_states.view(
         batch_size * num_images_per_prompt ,							snake_case__ ,							-1   )
     UpperCAmelCase__			:				Optional[int]												=       uncond_text_mask.repeat_interleave(snake_case__ ,							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__			:				List[str]												=       torch.cat([uncond_embeddings, text_embeddings]   )
     UpperCAmelCase__			:				List[Any]												=       torch.cat([uncond_text_encoder_hidden_states, text_encoder_hidden_states]   )

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

   return text_embeddings, text_encoder_hidden_states, text_mask







 @property
 def        UpperCamelCase     (				self		:     Any   ):



   '''simple docstring'''




   if self.device != torch.device("meta"   ) or not hasattr(self.prior ,							"_hf_hook"   ):
     return self.device
   for module in self.prior.modules():
     if (
         hasattr(snake_case__ ,							"_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







 def        UpperCamelCase     (				self		:     Dict ,							snake_case__		:     Any ,							snake_case__		:     Optional[Any] ,							snake_case__		:     Union[str, Any] ,							snake_case__		:     str ,							snake_case__		:     Union[str, Any] ,							snake_case__		:     Tuple   ):



   '''simple docstring'''




   if latents is None:
     UpperCAmelCase__			:				List[Any]												=       randn_tensor(snake_case__ ,							generator=snake_case__ ,							device=snake_case__ ,							dtype=snake_case__   )
   else:
     if latents.shape != shape:
       raise ValueError(F"""Unexpected latents shape, got {latents.shape}, expected {shape}"""   )
     UpperCAmelCase__			:				Tuple												=       latents.to(snake_case__   )

   UpperCAmelCase__			:				Tuple												=       latents * scheduler.init_noise_sigma
   return latents







 def        UpperCamelCase     (				self		:     Any ,							snake_case__		:     Optional[Union[str, torch.device]] = None   ):



   '''simple docstring'''




   self.decoder_pipe.to(snake_case__   )
   super().to(snake_case__   )







 @torch.no_grad()
 def __call__(				self		:     List[Any] ,							snake_case__		:     Optional[Union[str, List[str]]] = None ,							snake_case__		:     Optional[int] = None ,							snake_case__		:     Optional[int] = None ,							snake_case__		:     int = 1 ,							snake_case__		:     int = 25 ,							snake_case__		:     Optional[torch.Generator] = None ,							snake_case__		:     Optional[torch.FloatTensor] = None ,							snake_case__		:     Optional[Union[CLIPTextModelOutput, Tuple]] = None ,							snake_case__		:     Optional[torch.Tensor] = None ,							snake_case__		:     float = 4.0 ,							snake_case__		:     float = 8.0 ,							snake_case__		:     int = 50 ,							snake_case__		:     Optional[int] = 1 ,							snake_case__		:     float = 0.0 ,							snake_case__		:     Optional[str] = "pil" ,							snake_case__		:     bool = True ,							):



   '''simple docstring'''




   if prompt is not None:
     if isinstance(snake_case__ ,							snake_case__   ):
       UpperCAmelCase__			:				List[str]												=       1
     elif isinstance(snake_case__ ,							snake_case__   ):
       UpperCAmelCase__			:				Optional[Any]												=       len(snake_case__   )
     else:
       raise ValueError(F"""`prompt` has to be of type `str` or `list` but is {type(snake_case__   )}"""   )
   else:
     UpperCAmelCase__			:				Any												=       text_model_output[0].shape[0]

   UpperCAmelCase__			:				List[Any]												=       self._execution_device

   UpperCAmelCase__			:				Any												=       batch_size * num_images_per_prompt

   UpperCAmelCase__			:				Dict												=       prior_guidance_scale > 1.0 or decoder_guidance_scale > 1.0

   UpperCAmelCase__					, UpperCAmelCase__					, UpperCAmelCase__			:				str												=       self._encode_prompt(
       snake_case__ ,							snake_case__ ,							snake_case__ ,							snake_case__ ,							snake_case__ ,							snake_case__   )

   # prior

   self.prior_scheduler.set_timesteps(snake_case__ ,							device=snake_case__   )
   UpperCAmelCase__			:				str												=       self.prior_scheduler.timesteps

   UpperCAmelCase__			:				str												=       self.prior.config.embedding_dim

   UpperCAmelCase__			:				Any												=       self.prepare_latents(
       (batch_size, embedding_dim) ,							text_embeddings.dtype ,							snake_case__ ,							snake_case__ ,							snake_case__ ,							self.prior_scheduler ,							)

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

     UpperCAmelCase__			:				Optional[Any]												=       self.prior(
         snake_case__ ,							timestep=snake_case__ ,							proj_embedding=snake_case__ ,							encoder_hidden_states=snake_case__ ,							attention_mask=snake_case__ ,							).predicted_image_embedding

     if do_classifier_free_guidance:
       UpperCAmelCase__					, UpperCAmelCase__			:				Tuple												=       predicted_image_embedding.chunk(2   )
       UpperCAmelCase__			:				List[Any]												=       predicted_image_embedding_uncond + prior_guidance_scale * (
           predicted_image_embedding_text - predicted_image_embedding_uncond
       )

     if i + 1 == prior_timesteps_tensor.shape[0]:
       UpperCAmelCase__			:				Optional[Any]												=       None
     else:
       UpperCAmelCase__			:				Union[str, Any]												=       prior_timesteps_tensor[i + 1]

     UpperCAmelCase__			:				List[str]												=       self.prior_scheduler.step(
         snake_case__ ,							timestep=snake_case__ ,							sample=snake_case__ ,							generator=snake_case__ ,							prev_timestep=snake_case__ ,							).prev_sample

   UpperCAmelCase__			:				Optional[int]												=       self.prior.post_process_latents(snake_case__   )

   UpperCAmelCase__			:				List[str]												=       prior_latents

   UpperCAmelCase__			:				Optional[Any]												=       self.decoder_pipe(
       image=snake_case__ ,							height=snake_case__ ,							width=snake_case__ ,							num_inference_steps=snake_case__ ,							guidance_scale=snake_case__ ,							generator=snake_case__ ,							output_type=snake_case__ ,							return_dict=snake_case__ ,							num_images_per_prompt=snake_case__ ,							eta=snake_case__ ,							)
   return output





'''simple docstring'''





from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available


SCREAMING_SNAKE_CASE    =					{"""configuration_visual_bert""": ["""VISUAL_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """VisualBertConfig"""]}

try:
      if not is_torch_available():
            raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
      pass
else:
      SCREAMING_SNAKE_CASE    =					[
          """VISUAL_BERT_PRETRAINED_MODEL_ARCHIVE_LIST""",
          """VisualBertForMultipleChoice""",
          """VisualBertForPreTraining""",
          """VisualBertForQuestionAnswering""",
          """VisualBertForRegionToPhraseAlignment""",
          """VisualBertForVisualReasoning""",
          """VisualBertLayer""",
          """VisualBertModel""",
          """VisualBertPreTrainedModel""",
      ]


if TYPE_CHECKING:
      from .configuration_visual_bert import VISUAL_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, VisualBertConfig

      try:
            if not is_torch_available():
                  raise OptionalDependencyNotAvailable()
      except OptionalDependencyNotAvailable:
            pass
      else:
            from .modeling_visual_bert import (
                VISUAL_BERT_PRETRAINED_MODEL_ARCHIVE_LIST,
                VisualBertForMultipleChoice,
                VisualBertForPreTraining,
                VisualBertForQuestionAnswering,
                VisualBertForRegionToPhraseAlignment,
                VisualBertForVisualReasoning,
                VisualBertLayer,
                VisualBertModel,
                VisualBertPreTrainedModel,
            )


else:
      import sys

      SCREAMING_SNAKE_CASE    =					_LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)



