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


A							     = logging.get_logger(__name__)  # pylint: disable=invalid-name
def 	snake_case_							(				self  :				List[str]			,       _a  :				str			,       _a  :				Optional[Any]			,       _a  :				Tuple			,       _a  :				str      ):
      snake_case_    							=				image.to(device=_a      )
      snake_case_    							=				image  # take image as image_embeddings
      snake_case_    							=				image_embeddings.unsqueeze(1      )

      # duplicate image embeddings for each generation per prompt, using mps friendly method
      snake_case_							,						snake_case_							,						snake_case_    							=				image_embeddings.shape
      snake_case_    							=				image_embeddings.repeat(1			,       _a			,       1      )
      snake_case_    							=				image_embeddings.view(bs_embed * num_images_per_prompt			,       _a			,       -1      )

      if do_classifier_free_guidance:
            snake_case_    							=				torch.zeros_like(_a      )

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

      return image_embeddings




class 			lowerCAmelCase__ (							UpperCamelCase							):



  '''simple docstring'''






  def __init__(self	:			Tuple						,			lowerCAmelCase_	:			PriorTransformer						,			lowerCAmelCase_	:			CLIPTokenizer						,			lowerCAmelCase_	:			CLIPTextModelWithProjection						,			lowerCAmelCase_	:			UnCLIPScheduler						,			lowerCAmelCase_	:			Optional[dict] = None						,			) ->							Dict:
        super().__init__()

        snake_case_    							=				{"image_encoder": None} if decoder_pipe_kwargs is None else decoder_pipe_kwargs

        snake_case_    							=				decoder_pipe_kwargs.get("torch_dtype"						,			lowerCAmelCase_     ) or prior.dtype

        snake_case_    							=				StableDiffusionImageVariationPipeline.from_pretrained(
            "lambdalabs/sd-image-variations-diffusers"						,			**lowerCAmelCase_     )

        # replace `_encode_image` method
        snake_case_    							=				types.MethodType(_encode_image						,			self.decoder_pipe     )

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

  def 		_lowerCamelCase						(self	:			Optional[int]						,			lowerCAmelCase_	:			Dict						,			lowerCAmelCase_	:			Union[str, Any]						,			lowerCAmelCase_	:			Optional[int]						,			lowerCAmelCase_	:			Any						,			lowerCAmelCase_	:			Optional[Union[CLIPTextModelOutput, Tuple]] = None						,			lowerCAmelCase_	:			Optional[torch.Tensor] = None						,			) ->							Union[str, Any]:
        if text_model_output is None:
              snake_case_    							=				len(lowerCAmelCase_     ) if isinstance(lowerCAmelCase_						,			lowerCAmelCase_     ) else 1
              # get prompt text embeddings
              snake_case_    							=				self.tokenizer(
                  lowerCAmelCase_						,			padding="max_length"						,			max_length=self.tokenizer.model_max_length						,			return_tensors="pt"						,			)
              snake_case_    							=				text_inputs.input_ids
              snake_case_    							=				text_inputs.attention_mask.bool().to(lowerCAmelCase_     )

              if text_input_ids.shape[-1] > self.tokenizer.model_max_length:
                    snake_case_    							=				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}'''     )
                    snake_case_    							=				text_input_ids[:, : self.tokenizer.model_max_length]

              snake_case_    							=				self.text_encoder(text_input_ids.to(lowerCAmelCase_     )     )

              snake_case_    							=				text_encoder_output.text_embeds
              snake_case_    							=				text_encoder_output.last_hidden_state

        else:
              snake_case_    							=				text_model_output[0].shape[0]
              snake_case_							,						snake_case_    							=				text_model_output[0], text_model_output[1]
              snake_case_    							=				text_attention_mask

        snake_case_    							=				text_embeddings.repeat_interleave(lowerCAmelCase_						,			dim=0     )
        snake_case_    							=				text_encoder_hidden_states.repeat_interleave(lowerCAmelCase_						,			dim=0     )
        snake_case_    							=				text_mask.repeat_interleave(lowerCAmelCase_						,			dim=0     )

        if do_classifier_free_guidance:
              snake_case_    							=				[""] * batch_size

              snake_case_    							=				self.tokenizer(
                  lowerCAmelCase_						,			padding="max_length"						,			max_length=self.tokenizer.model_max_length						,			truncation=lowerCAmelCase_						,			return_tensors="pt"						,			)
              snake_case_    							=				uncond_input.attention_mask.bool().to(lowerCAmelCase_     )
              snake_case_    							=				self.text_encoder(uncond_input.input_ids.to(lowerCAmelCase_     )     )

              snake_case_    							=				uncond_embeddings_text_encoder_output.text_embeds
              snake_case_    							=				uncond_embeddings_text_encoder_output.last_hidden_state

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

              snake_case_    							=				uncond_embeddings.shape[1]
              snake_case_    							=				uncond_embeddings.repeat(1						,			lowerCAmelCase_     )
              snake_case_    							=				uncond_embeddings.view(batch_size * num_images_per_prompt						,			lowerCAmelCase_     )

              snake_case_    							=				uncond_text_encoder_hidden_states.shape[1]
              snake_case_    							=				uncond_text_encoder_hidden_states.repeat(1						,			lowerCAmelCase_						,			1     )
              snake_case_    							=				uncond_text_encoder_hidden_states.view(
                  batch_size * num_images_per_prompt						,			lowerCAmelCase_						,			-1     )
              snake_case_    							=				uncond_text_mask.repeat_interleave(lowerCAmelCase_						,			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
              snake_case_    							=				torch.cat([uncond_embeddings, text_embeddings]     )
              snake_case_    							=				torch.cat([uncond_text_encoder_hidden_states, text_encoder_hidden_states]     )

              snake_case_    							=				torch.cat([uncond_text_mask, text_mask]     )

        return text_embeddings, text_encoder_hidden_states, text_mask

  @property
  def 		_lowerCamelCase						(self	:			Dict     ) ->							Any:
        if self.device != torch.device("meta"     ) or not hasattr(self.prior						,			"_hf_hook"     ):
              return self.device
        for module in self.prior.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

  def 		_lowerCamelCase						(self	:			List[str]						,			lowerCAmelCase_	:			Any						,			lowerCAmelCase_	:			Union[str, Any]						,			lowerCAmelCase_	:			Any						,			lowerCAmelCase_	:			int						,			lowerCAmelCase_	:			List[Any]						,			lowerCAmelCase_	:			List[str]     ) ->							str:
        if latents is None:
              snake_case_    							=				randn_tensor(lowerCAmelCase_						,			generator=lowerCAmelCase_						,			device=lowerCAmelCase_						,			dtype=lowerCAmelCase_     )
        else:
              if latents.shape != shape:
                    raise ValueError(f'''Unexpected latents shape, got {latents.shape}, expected {shape}'''     )
              snake_case_    							=				latents.to(lowerCAmelCase_     )

        snake_case_    							=				latents * scheduler.init_noise_sigma
        return latents

  def 		_lowerCamelCase						(self	:			Any						,			lowerCAmelCase_	:			Optional[Union[str, torch.device]] = None     ) ->							List[Any]:
        self.decoder_pipe.to(lowerCAmelCase_     )
        super().to(lowerCAmelCase_     )


  @torch.no_grad()
  def __call__(self	:			int						,			lowerCAmelCase_	:			Optional[Union[str, List[str]]] = None						,			lowerCAmelCase_	:			Optional[int] = None						,			lowerCAmelCase_	:			Optional[int] = None						,			lowerCAmelCase_	:			int = 1						,			lowerCAmelCase_	:			int = 25						,			lowerCAmelCase_	:			Optional[torch.Generator] = None						,			lowerCAmelCase_	:			Optional[torch.FloatTensor] = None						,			lowerCAmelCase_	:			Optional[Union[CLIPTextModelOutput, Tuple]] = None						,			lowerCAmelCase_	:			Optional[torch.Tensor] = None						,			lowerCAmelCase_	:			float = 4.0						,			lowerCAmelCase_	:			float = 8.0						,			lowerCAmelCase_	:			int = 50						,			lowerCAmelCase_	:			Optional[int] = 1						,			lowerCAmelCase_	:			float = 0.0						,			lowerCAmelCase_	:			Optional[str] = "pil"						,			lowerCAmelCase_	:			bool = True						,			) ->							Dict:
        if prompt is not None:
              if isinstance(lowerCAmelCase_						,			lowerCAmelCase_     ):
                    snake_case_    							=				1
              elif isinstance(lowerCAmelCase_						,			lowerCAmelCase_     ):
                    snake_case_    							=				len(lowerCAmelCase_     )
              else:
                    raise ValueError(f'''`prompt` has to be of type `str` or `list` but is {type(lowerCAmelCase_     )}'''     )
        else:
              snake_case_    							=				text_model_output[0].shape[0]

        snake_case_    							=				self._execution_device

        snake_case_    							=				batch_size * num_images_per_prompt

        snake_case_    							=				prior_guidance_scale > 1.0 or decoder_guidance_scale > 1.0

        snake_case_							,						snake_case_							,						snake_case_    							=				self._encode_prompt(
            lowerCAmelCase_						,			lowerCAmelCase_						,			lowerCAmelCase_						,			lowerCAmelCase_						,			lowerCAmelCase_						,			lowerCAmelCase_     )

        # prior

        self.prior_scheduler.set_timesteps(lowerCAmelCase_						,			device=lowerCAmelCase_     )
        snake_case_    							=				self.prior_scheduler.timesteps

        snake_case_    							=				self.prior.config.embedding_dim

        snake_case_    							=				self.prepare_latents(
            (batch_size, embedding_dim)						,			text_embeddings.dtype						,			lowerCAmelCase_						,			lowerCAmelCase_						,			lowerCAmelCase_						,			self.prior_scheduler						,			)

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

              snake_case_    							=				self.prior(
                  lowerCAmelCase_						,			timestep=lowerCAmelCase_						,			proj_embedding=lowerCAmelCase_						,			encoder_hidden_states=lowerCAmelCase_						,			attention_mask=lowerCAmelCase_						,			).predicted_image_embedding

              if do_classifier_free_guidance:
                    snake_case_							,						snake_case_    							=				predicted_image_embedding.chunk(2     )
                    snake_case_    							=				predicted_image_embedding_uncond + prior_guidance_scale * (
                        predicted_image_embedding_text - predicted_image_embedding_uncond
                    )

              if i + 1 == prior_timesteps_tensor.shape[0]:
                    snake_case_    							=				None
              else:
                    snake_case_    							=				prior_timesteps_tensor[i + 1]

              snake_case_    							=				self.prior_scheduler.step(
                  lowerCAmelCase_						,			timestep=lowerCAmelCase_						,			sample=lowerCAmelCase_						,			generator=lowerCAmelCase_						,			prev_timestep=lowerCAmelCase_						,			).prev_sample

        snake_case_    							=				self.prior.post_process_latents(lowerCAmelCase_     )

        snake_case_    							=				prior_latents

        snake_case_    							=				self.decoder_pipe(
            image=lowerCAmelCase_						,			height=lowerCAmelCase_						,			width=lowerCAmelCase_						,			num_inference_steps=lowerCAmelCase_						,			guidance_scale=lowerCAmelCase_						,			generator=lowerCAmelCase_						,			output_type=lowerCAmelCase_						,			return_dict=lowerCAmelCase_						,			num_images_per_prompt=lowerCAmelCase_						,			eta=lowerCAmelCase_						,			)
        return output






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

import flax
import jax.numpy as jnp
from scipy import integrate

from ..configuration_utils import ConfigMixin, register_to_config
from .scheduling_utils_flax import (
    CommonSchedulerState,
    FlaxKarrasDiffusionSchedulers,
    FlaxSchedulerMixin,
    FlaxSchedulerOutput,
    broadcast_to_shape_from_left,
)





@flax.struct.dataclass
class 							lowerCAmelCase_		:
		SCREAMING_SNAKE_CASE_       :			CommonSchedulerState

		# setable values
		SCREAMING_SNAKE_CASE_       :			jnp.ndarray
		SCREAMING_SNAKE_CASE_       :			jnp.ndarray
		SCREAMING_SNAKE_CASE_       :			jnp.ndarray
		SCREAMING_SNAKE_CASE_       :			Optional[int]					       =	None

		# running values
		SCREAMING_SNAKE_CASE_       :			Optional[jnp.ndarray]					       =	None







		@classmethod
		def 					a_  (    cls  :   List[Any]       ,		UpperCAmelCase_  :   CommonSchedulerState       ,		UpperCAmelCase_  :   jnp.ndarray       ,		UpperCAmelCase_  :   jnp.ndarray       ,		UpperCAmelCase_  :   jnp.ndarray					)       ->		Optional[Any]:


						'''simple docstring'''







						return cls(common=UpperCAmelCase_       ,		init_noise_sigma=UpperCAmelCase_       ,		timesteps=UpperCAmelCase_       ,		sigmas=UpperCAmelCase_					)





@dataclass
class 							lowerCAmelCase_		(		lowercase_     ):
		SCREAMING_SNAKE_CASE_       :			LMSDiscreteSchedulerState





class 							lowerCAmelCase_		(		lowercase_							,		lowercase_     ):
		SCREAMING_SNAKE_CASE_       :			Union[str, Any]					       =	[e.name for e in FlaxKarrasDiffusionSchedulers]

		SCREAMING_SNAKE_CASE_       :			jnp.dtype







		@property
		def 					a_  (    self  :   Union[str, Any]					)       ->		List[Any]:


						'''simple docstring'''







						return True







		@register_to_config
		def __init__(    self  :   Optional[Any]       ,		UpperCAmelCase_  :   int = 1000       ,		UpperCAmelCase_  :   float = 0.0_001       ,		UpperCAmelCase_  :   float = 0.02       ,		UpperCAmelCase_  :   str = "linear"       ,		UpperCAmelCase_  :   Optional[jnp.ndarray] = None       ,		UpperCAmelCase_  :   str = "epsilon"       ,		UpperCAmelCase_  :   jnp.dtype = jnp.floataa       ,		)       ->		List[str]:


						'''simple docstring'''







						_UpperCAmelCase						:  str     					=	dtype







		def 					a_  (    self  :   Tuple       ,		UpperCAmelCase_  :   Optional[CommonSchedulerState] = None					)       ->		LMSDiscreteSchedulerState:


						'''simple docstring'''







						if common is None:
										_UpperCAmelCase						:  int     					=	CommonSchedulerState.create(self					)

						_UpperCAmelCase						:  Any     					=	jnp.arange(0       ,		self.config.num_train_timesteps					).round()[::-1]
						_UpperCAmelCase						:  Any     					=	((1 - common.alphas_cumprod) / common.alphas_cumprod) ** 0.5

						# standard deviation of the initial noise distribution
						_UpperCAmelCase						:  Dict     					=	sigmas.max()

						return LMSDiscreteSchedulerState.create(
						    common=UpperCAmelCase_       ,		init_noise_sigma=UpperCAmelCase_       ,		timesteps=UpperCAmelCase_       ,		sigmas=UpperCAmelCase_       ,		)







		def 					a_  (    self  :   Optional[Any]       ,		UpperCAmelCase_  :   LMSDiscreteSchedulerState       ,		UpperCAmelCase_  :   jnp.ndarray       ,		UpperCAmelCase_  :   int					)       ->		jnp.ndarray:


						'''simple docstring'''







						((_UpperCAmelCase)					, )						:  Optional[Any]     					=	jnp.where(state.timesteps == timestep       ,		size=1					)
						_UpperCAmelCase						:  List[str]     					=	step_index[0]

						_UpperCAmelCase						:  List[Any]     					=	state.sigmas[step_index]
						_UpperCAmelCase						:  Union[str, Any]     					=	sample / ((sigma**2 + 1) ** 0.5)
						return sample







		def 					a_  (    self  :   List[Any]       ,		UpperCAmelCase_  :   LMSDiscreteSchedulerState       ,		UpperCAmelCase_  :   int       ,		UpperCAmelCase_  :   str       ,		UpperCAmelCase_  :   Union[str, Any]					)       ->		Union[str, Any]:


						'''simple docstring'''







						def lms_derivative(UpperCAmelCase_  :   Optional[int]					):
										_UpperCAmelCase						:  Optional[Any]     					=	1.0
										for k in range(UpperCAmelCase_					):
														if current_order == k:
																		continue
														prod *= (tau - state.sigmas[t - k]) / (state.sigmas[t - current_order] - state.sigmas[t - k])
										return prod

						_UpperCAmelCase						:  Optional[Any]     					=	integrate.quad(UpperCAmelCase_       ,		state.sigmas[t]       ,		state.sigmas[t + 1]       ,		epsrel=1E-4					)[0]

						return integrated_coeff







		def 					a_  (    self  :   Dict       ,		UpperCAmelCase_  :   LMSDiscreteSchedulerState       ,		UpperCAmelCase_  :   int       ,		UpperCAmelCase_  :   Tuple = ()					)       ->		LMSDiscreteSchedulerState:


						'''simple docstring'''







						_UpperCAmelCase						:  List[str]     					=	jnp.linspace(self.config.num_train_timesteps - 1       ,		0       ,		UpperCAmelCase_       ,		dtype=self.dtype					)

						_UpperCAmelCase						:  Any     					=	jnp.floor(UpperCAmelCase_					).astype(jnp.intaa					)
						_UpperCAmelCase						:  Optional[Any]     					=	jnp.ceil(UpperCAmelCase_					).astype(jnp.intaa					)

						_UpperCAmelCase						:  str     					=	jnp.mod(UpperCAmelCase_       ,		1.0					)

						_UpperCAmelCase						:  Optional[Any]     					=	((1 - state.common.alphas_cumprod) / state.common.alphas_cumprod) ** 0.5
						_UpperCAmelCase						:  Any     					=	(1 - frac) * sigmas[low_idx] + frac * sigmas[high_idx]
						_UpperCAmelCase						:  Tuple     					=	jnp.concatenate([sigmas, jnp.array([0.0]       ,		dtype=self.dtype					)]					)

						_UpperCAmelCase						:  int     					=	timesteps.astype(jnp.intaa					)

						# initial running values
						_UpperCAmelCase						:  List[str]     					=	jnp.zeros((0,) + shape       ,		dtype=self.dtype					)

						return state.replace(
						    timesteps=UpperCAmelCase_       ,		sigmas=UpperCAmelCase_       ,		num_inference_steps=UpperCAmelCase_       ,		derivatives=UpperCAmelCase_       ,		)







		def 					a_  (    self  :   Tuple       ,		UpperCAmelCase_  :   LMSDiscreteSchedulerState       ,		UpperCAmelCase_  :   jnp.ndarray       ,		UpperCAmelCase_  :   int       ,		UpperCAmelCase_  :   jnp.ndarray       ,		UpperCAmelCase_  :   int = 4       ,		UpperCAmelCase_  :   bool = True       ,		)       ->		Union[FlaxLMSSchedulerOutput, Tuple]:


						'''simple docstring'''







						if state.num_inference_steps is None:
										raise ValueError(
										    '''Number of inference steps is \'None\', you need to run \'set_timesteps\' after creating the scheduler'''					)

						_UpperCAmelCase						:  List[Any]     					=	state.sigmas[timestep]

						# 1. compute predicted original sample (x_0) from sigma-scaled predicted noise
						if self.config.prediction_type == "epsilon":
										_UpperCAmelCase						:  Optional[int]     					=	sample - sigma * model_output
						elif self.config.prediction_type == "v_prediction":
										# * c_out + input * c_skip
										_UpperCAmelCase						:  Tuple     					=	model_output * (-sigma / (sigma**2 + 1) ** 0.5) + (sample / (sigma**2 + 1))
						else:
										raise ValueError(
										    F'''prediction_type given as {self.config.prediction_type} must be one of `epsilon`, or `v_prediction`'''					)

						# 2. Convert to an ODE derivative
						_UpperCAmelCase						:  Tuple     					=	(sample - pred_original_sample) / sigma
						_UpperCAmelCase						:  Tuple     					=	state.replace(derivatives=jnp.append(state.derivatives       ,		UpperCAmelCase_					)					)
						if len(state.derivatives					) > order:
										_UpperCAmelCase						:  Union[str, Any]     					=	state.replace(derivatives=jnp.delete(state.derivatives       ,		0					)					)

						# 3. Compute linear multistep coefficients
						_UpperCAmelCase						:  int     					=	min(timestep + 1       ,		UpperCAmelCase_					)
						_UpperCAmelCase						:  Optional[int]     					=	[self.get_lms_coefficient(UpperCAmelCase_       ,		UpperCAmelCase_       ,		UpperCAmelCase_       ,		UpperCAmelCase_					) for curr_order in range(UpperCAmelCase_					)]

						# 4. Compute previous sample based on the derivatives path
						_UpperCAmelCase						:  int     					=	sample + sum(
						    coeff * derivative for coeff, derivative in zip(UpperCAmelCase_       ,		reversed(state.derivatives					)					)					)

						if not return_dict:
										return (prev_sample, state)

						return FlaxLMSSchedulerOutput(prev_sample=UpperCAmelCase_       ,		state=UpperCAmelCase_					)







		def 					a_  (    self  :   Union[str, Any]       ,		UpperCAmelCase_  :   LMSDiscreteSchedulerState       ,		UpperCAmelCase_  :   jnp.ndarray       ,		UpperCAmelCase_  :   jnp.ndarray       ,		UpperCAmelCase_  :   jnp.ndarray       ,		)       ->		jnp.ndarray:


						'''simple docstring'''







						_UpperCAmelCase						:  Union[str, Any]     					=	state.sigmas[timesteps].flatten()
						_UpperCAmelCase						:  Union[str, Any]     					=	broadcast_to_shape_from_left(UpperCAmelCase_       ,		noise.shape					)

						_UpperCAmelCase						:  Any     					=	original_samples + noise * sigma

						return noisy_samples







		def __len__(    self  :   Dict					)       ->		Tuple:


						'''simple docstring'''







						return self.config.num_train_timesteps
