


'''simple docstring'''

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

import torch
from transformers import CLIPTextModel, CLIPTokenizer

from ...configuration_utils import ConfigMixin, register_to_config
from ...models import ModelMixin, TransformeraDModel, VQModel
from ...schedulers import VQDiffusionScheduler
from ...utils import logging
from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput


lowerCamelCase				:  Optional[Any]    		=      logging.get_logger(__name__)  # pylint: disable=invalid-name
class     __lowerCAmelCase		(lowercase_    ,	lowercase_	):





      '''simple docstring'''






      @register_to_config
      def __init__(self       :       str  ,		UpperCamelCase       :       bool  ,		UpperCamelCase       :       Optional[int] = None  ,		UpperCamelCase       :       Optional[int] = None					):

             '''simple docstring'''







             super().__init__()

             lowercase__      =					learnable

             if self.learnable:
                    assert hidden_size is not None, "learnable=True requires `hidden_size` to be set"
                    assert length is not None, "learnable=True requires `length` to be set"

                    lowercase__      =					torch.zeros(UpperCamelCase  ,		UpperCamelCase					)
             else:
                    lowercase__      =					None

             lowercase__      =					torch.nn.Parameter(UpperCamelCase					)






class     __lowerCAmelCase		(lowercase_	):





      '''simple docstring'''






      lowerCAmelCase__   :	VQModel
      lowerCAmelCase__   :	CLIPTextModel
      lowerCAmelCase__   :	CLIPTokenizer
      lowerCAmelCase__   :	TransformeraDModel
      lowerCAmelCase__   :	LearnedClassifierFreeSamplingEmbeddings
      lowerCAmelCase__   :	VQDiffusionScheduler



      def __init__(self       :       Tuple  ,		UpperCamelCase       :       VQModel  ,		UpperCamelCase       :       CLIPTextModel  ,		UpperCamelCase       :       CLIPTokenizer  ,		UpperCamelCase       :       TransformeraDModel  ,		UpperCamelCase       :       VQDiffusionScheduler  ,		UpperCamelCase       :       LearnedClassifierFreeSamplingEmbeddings  ,		):

             '''simple docstring'''







             super().__init__()

             self.register_modules(
                 vqvae=UpperCamelCase  ,		transformer=UpperCamelCase  ,		text_encoder=UpperCamelCase  ,		tokenizer=UpperCamelCase  ,		scheduler=UpperCamelCase  ,		learned_classifier_free_sampling_embeddings=UpperCamelCase  ,		)



      def  UpperCamelCase__						(self       :       Optional[int]  ,		UpperCamelCase       :       int  ,		UpperCamelCase       :       str  ,		UpperCamelCase       :       Optional[int]					):

             '''simple docstring'''







             lowercase__      =					len(UpperCamelCase					) if isinstance(UpperCamelCase  ,		UpperCamelCase					) else 1

             # get prompt text embeddings
             lowercase__      =					self.tokenizer(
                 UpperCamelCase  ,		padding='''max_length'''  ,		max_length=self.tokenizer.model_max_length  ,		return_tensors='''pt'''  ,		)
             lowercase__      =					text_inputs.input_ids

             if text_input_ids.shape[-1] > self.tokenizer.model_max_length:
                    lowercase__      =					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}"					)
                    lowercase__      =					text_input_ids[:, : self.tokenizer.model_max_length]
             lowercase__      =					self.text_encoder(text_input_ids.to(self.device					)					)[0]

             # NOTE: This additional step of normalizing the text embeddings is from VQ-Diffusion.
             # While CLIP does normalize the pooled output of the text transformer when combining
             # the image and text embeddings, CLIP does not directly normalize the last hidden state.
             #
             # CLIP normalizing the pooled output.
             # https://github.com/huggingface/transformers/blob/d92e22d1f28324f513f3080e5c47c071a3916721/src/transformers/models/clip/modeling_clip.py#L1052-L1053
             lowercase__      =					prompt_embeds / prompt_embeds.norm(dim=-1  ,		keepdim=UpperCamelCase					)

             # duplicate text embeddings for each generation per prompt
             lowercase__      =					prompt_embeds.repeat_interleave(UpperCamelCase  ,		dim=0					)

             if do_classifier_free_guidance:
                    if self.learned_classifier_free_sampling_embeddings.learnable:
                           lowercase__      =					self.learned_classifier_free_sampling_embeddings.embeddings
                           lowercase__      =					negative_prompt_embeds.unsqueeze(0					).repeat(UpperCamelCase  ,		1  ,		1					)
                    else:
                           lowercase__      =					[''''''] * batch_size

                           lowercase__      =					text_input_ids.shape[-1]
                           lowercase__      =					self.tokenizer(
                               UpperCamelCase  ,		padding='''max_length'''  ,		max_length=UpperCamelCase  ,		truncation=UpperCamelCase  ,		return_tensors='''pt'''  ,		)
                           lowercase__      =					self.text_encoder(uncond_input.input_ids.to(self.device					)					)[0]
                           # See comment for normalizing text embeddings
                           lowercase__      =					negative_prompt_embeds / negative_prompt_embeds.norm(dim=-1  ,		keepdim=UpperCamelCase					)

                    # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
                    lowercase__      =					negative_prompt_embeds.shape[1]
                    lowercase__      =					negative_prompt_embeds.repeat(1  ,		UpperCamelCase  ,		1					)
                    lowercase__      =					negative_prompt_embeds.view(batch_size * num_images_per_prompt  ,		UpperCamelCase  ,		-1					)

                    # 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
                    lowercase__      =					torch.cat([negative_prompt_embeds, prompt_embeds]					)

             return prompt_embeds



      @torch.no_grad()
      def __call__(self       :       Dict  ,		UpperCamelCase       :       Union[str, List[str]]  ,		UpperCamelCase       :       int = 100  ,		UpperCamelCase       :       float = 5.0  ,		UpperCamelCase       :       float = 1.0  ,		UpperCamelCase       :       int = 1  ,		UpperCamelCase       :       Optional[Union[torch.Generator, List[torch.Generator]]] = None  ,		UpperCamelCase       :       Optional[torch.FloatTensor] = None  ,		UpperCamelCase       :       Optional[str] = "pil"  ,		UpperCamelCase       :       bool = True  ,		UpperCamelCase       :       Optional[Callable[[int, int, torch.FloatTensor], None]] = None  ,		UpperCamelCase       :       int = 1  ,		):

             '''simple docstring'''







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

             lowercase__      =					batch_size * num_images_per_prompt

             lowercase__      =					guidance_scale > 1.0

             lowercase__      =					self._encode_prompt(UpperCamelCase  ,		UpperCamelCase  ,		UpperCamelCase					)

             if (callback_steps is None) or (
                 callback_steps is not None and (not isinstance(UpperCamelCase  ,		UpperCamelCase					) or callback_steps <= 0)
             ):
                    raise ValueError(
                        f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
                        f" {type(UpperCamelCase					)}."					)

             # get the initial completely masked latents unless the user supplied it

             lowercase__      =					(batch_size, self.transformer.num_latent_pixels)
             if latents is None:
                    lowercase__      =					self.transformer.num_vector_embeds - 1
                    lowercase__      =					torch.full(UpperCamelCase  ,		UpperCamelCase					).to(self.device					)
             else:
                    if latents.shape != latents_shape:
                           raise ValueError(f"Unexpected latents shape, got {latents.shape}, expected {latents_shape}"					)
                    if (latents < 0).any() or (latents >= self.transformer.num_vector_embeds).any():
                           raise ValueError(
                               '''Unexpected latents value(s). All latents be valid embedding indices i.e. in the range 0,'''
                               f" {self.transformer.num_vector_embeds - 1} (inclusive)."					)
                    lowercase__      =					latents.to(self.device					)

             # set timesteps
             self.scheduler.set_timesteps(UpperCamelCase  ,		device=self.device					)

             lowercase__      =					self.scheduler.timesteps.to(self.device					)

             lowercase__      =					latents

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

                    # predict the un-noised image
                    # model_output == `log_p_x_0`
                    lowercase__      =					self.transformer(UpperCamelCase  ,		encoder_hidden_states=UpperCamelCase  ,		timestep=UpperCamelCase					).sample

                    if do_classifier_free_guidance:
                           lowercase__     ,lowercase__      =					model_output.chunk(2					)
                           lowercase__      =					model_output_uncond + guidance_scale * (model_output_text - model_output_uncond)
                           model_output -= torch.logsumexp(UpperCamelCase  ,		dim=1  ,		keepdim=UpperCamelCase					)

                    lowercase__      =					self.truncate(UpperCamelCase  ,		UpperCamelCase					)

                    # remove `log(0)`'s (`-inf`s)
                    lowercase__      =					model_output.clamp(-70					)

                    # compute the previous noisy sample x_t -> x_t-1
                    lowercase__      =					self.scheduler.step(UpperCamelCase  ,		timestep=UpperCamelCase  ,		sample=UpperCamelCase  ,		generator=UpperCamelCase					).prev_sample

                    # call the callback, if provided
                    if callback is not None and i % callback_steps == 0:
                           callback(UpperCamelCase  ,		UpperCamelCase  ,		UpperCamelCase					)

             lowercase__      =					self.vqvae.config.vq_embed_dim
             lowercase__      =					(batch_size, self.transformer.height, self.transformer.width, embedding_channels)
             lowercase__      =					self.vqvae.quantize.get_codebook_entry(UpperCamelCase  ,		shape=UpperCamelCase					)
             lowercase__      =					self.vqvae.decode(UpperCamelCase  ,		force_not_quantize=UpperCamelCase					).sample

             lowercase__      =					(image / 2 + 0.5).clamp(0  ,		1					)
             lowercase__      =					image.cpu().permute(0  ,		2  ,		3  ,		1					).numpy()

             if output_type == "pil":
                    lowercase__      =					self.numpy_to_pil(UpperCamelCase					)

             if not return_dict:
                    return (image,)

             return ImagePipelineOutput(images=UpperCamelCase					)






      def  UpperCamelCase__						(self       :       List[Any]  ,		UpperCamelCase       :       torch.FloatTensor  ,		UpperCamelCase       :       float					):

             '''simple docstring'''







             lowercase__     ,lowercase__      =					torch.sort(UpperCamelCase  ,		1  ,		descending=UpperCamelCase					)
             lowercase__      =					torch.exp(UpperCamelCase					)
             lowercase__      =					sorted_p_x_0.cumsum(dim=1					) < truncation_rate

             # Ensure that at least the largest probability is not zeroed out
             lowercase__      =					torch.full_like(keep_mask[:, 0:1, :]  ,		UpperCamelCase					)
             lowercase__      =					torch.cat((all_true, keep_mask)  ,		dim=1					)
             lowercase__      =					keep_mask[:, :-1, :]

             lowercase__      =					keep_mask.gather(1  ,		indices.argsort(1					)					)

             lowercase__      =					log_p_x_0.clone()

             lowercase__      =					-torch.inf  # -inf = log(0)

             return rv








'''simple docstring'''

from __future__ import annotations

from typing import Any
class     __lowerCAmelCase		:





      '''simple docstring'''






      def __init__(self       :       Optional[Any]  ,		UpperCamelCase       :       int = 6					):

             '''simple docstring'''







             lowercase__      =					None
             lowercase__      =					None
             self.create_linked_list(UpperCamelCase					)



      def  UpperCamelCase__						(self       :       List[str]  ,		UpperCamelCase       :       int					):

             '''simple docstring'''







             lowercase__      =					Node()
             lowercase__      =					current_node
             lowercase__      =					current_node
             lowercase__      =					current_node
             for _ in range(1  ,		UpperCamelCase					):
                    lowercase__      =					Node()
                    lowercase__      =					current_node
                    lowercase__      =					previous_node
                    lowercase__      =					current_node
             lowercase__      =					self.front
             lowercase__      =					previous_node



      def  UpperCamelCase__						(self       :       Union[str, Any]					):

             '''simple docstring'''







             return (
                 self.front == self.rear
                 and self.front is not None
                 and self.front.data is None
             )



      def  UpperCamelCase__						(self       :       Dict					):

             '''simple docstring'''







             self.check_can_perform_operation()
             return self.front.data if self.front else None



      def  UpperCamelCase__						(self       :       Any  ,		UpperCamelCase       :       Any					):

             '''simple docstring'''







             if self.rear is None:
                    return

             self.check_is_full()
             if not self.is_empty():
                    lowercase__      =					self.rear.next
             if self.rear:
                    lowercase__      =					data



      def  UpperCamelCase__						(self       :       List[Any]					):

             '''simple docstring'''







             self.check_can_perform_operation()
             if self.rear is None or self.front is None:
                    return None
             if self.front == self.rear:
                    lowercase__      =					self.front.data
                    lowercase__      =					None
                    return data

             lowercase__      =					self.front
             lowercase__      =					old_front.next
             lowercase__      =					old_front.data
             lowercase__      =					None
             return data



      def  UpperCamelCase__						(self       :       Union[str, Any]					):

             '''simple docstring'''







             if self.is_empty():
                    raise Exception('''Empty Queue'''					)






      def  UpperCamelCase__						(self       :       int					):

             '''simple docstring'''







             if self.rear and self.rear.next == self.front:
                    raise Exception('''Full Queue'''					)






class     __lowerCAmelCase		:





      '''simple docstring'''






      def __init__(self       :       Any					):

             '''simple docstring'''







             lowercase__      =					None
             lowercase__      =					None
             lowercase__      =					None


if __name__ == "__main__":
 import doctest

 doctest.testmod()




