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


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






class 				a__(					lowerCAmelCase__ ,						lowerCAmelCase__	):


			'''simple docstring'''






			@register_to_config
			def __init__(   self       ,    __lowerCAmelCase       ,    __lowerCAmelCase = None       ,    __lowerCAmelCase = None):




					"""simple docstring"""


					super().__init__()

					lowerCAmelCase   					=  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"

							lowerCAmelCase   					=  torch.zeros(__lowerCAmelCase       ,    __lowerCAmelCase)
					else:
							lowerCAmelCase   					=  None

					lowerCAmelCase   					=  torch.nn.Parameter(__lowerCAmelCase)







class 				a__(					lowerCAmelCase__	):


			'''simple docstring'''






			UpperCAmelCase_			:     VQModel
			UpperCAmelCase_			:     CLIPTextModel
			UpperCAmelCase_			:     CLIPTokenizer
			UpperCAmelCase_			:     TransformeraDModel
			UpperCAmelCase_			:     LearnedClassifierFreeSamplingEmbeddings
			UpperCAmelCase_			:     VQDiffusionScheduler



			def __init__(   self       ,    __lowerCAmelCase       ,    __lowerCAmelCase       ,    __lowerCAmelCase       ,    __lowerCAmelCase       ,    __lowerCAmelCase       ,    __lowerCAmelCase       ,    ):




					"""simple docstring"""


					super().__init__()

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



			def 							a_       (   self       ,    __lowerCAmelCase       ,    __lowerCAmelCase       ,    __lowerCAmelCase):




					"""simple docstring"""


					lowerCAmelCase   					=  len(__lowerCAmelCase) if isinstance(__lowerCAmelCase       ,    __lowerCAmelCase) else 1

					# get prompt text embeddings
					lowerCAmelCase   					=  self.tokenizer(
					    __lowerCAmelCase       ,    padding="""max_length"""       ,    max_length=self.tokenizer.model_max_length       ,    return_tensors="""pt"""       ,    )
					lowerCAmelCase   					=  text_inputs.input_ids

					if text_input_ids.shape[-1] > self.tokenizer.model_max_length:
							lowerCAmelCase   					=  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}")
							lowerCAmelCase   					=  text_input_ids[:, : self.tokenizer.model_max_length]
					lowerCAmelCase   					=  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
					lowerCAmelCase   					=  prompt_embeds / prompt_embeds.norm(dim=-1       ,    keepdim=__lowerCAmelCase)

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

					if do_classifier_free_guidance:
							if self.learned_classifier_free_sampling_embeddings.learnable:
									lowerCAmelCase   					=  self.learned_classifier_free_sampling_embeddings.embeddings
									lowerCAmelCase   					=  negative_prompt_embeds.unsqueeze(0).repeat(__lowerCAmelCase       ,    1       ,    1)
							else:
									lowerCAmelCase   					=  [""""""] * batch_size

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

							# duplicate unconditional embeddings for each generation per prompt, using mps friendly method
							lowerCAmelCase   					=  negative_prompt_embeds.shape[1]
							lowerCAmelCase   					=  negative_prompt_embeds.repeat(1       ,    __lowerCAmelCase       ,    1)
							lowerCAmelCase   					=  negative_prompt_embeds.view(batch_size * num_images_per_prompt       ,    __lowerCAmelCase       ,    -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
							lowerCAmelCase   					=  torch.cat([negative_prompt_embeds, prompt_embeds])

					return prompt_embeds



			@torch.no_grad()
			def __call__(   self       ,    __lowerCAmelCase       ,    __lowerCAmelCase = 100       ,    __lowerCAmelCase = 5.0       ,    __lowerCAmelCase = 1.0       ,    __lowerCAmelCase = 1       ,    __lowerCAmelCase = None       ,    __lowerCAmelCase = None       ,    __lowerCAmelCase = "pil"       ,    __lowerCAmelCase = True       ,    __lowerCAmelCase = None       ,    __lowerCAmelCase = 1       ,    ):




					"""simple docstring"""


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

					lowerCAmelCase   					=  batch_size * num_images_per_prompt

					lowerCAmelCase   					=  guidance_scale > 1.0

					lowerCAmelCase   					=  self._encode_prompt(__lowerCAmelCase       ,    __lowerCAmelCase       ,    __lowerCAmelCase)

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

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

					lowerCAmelCase   					=  (batch_size, self.transformer.num_latent_pixels)
					if latents is None:
							lowerCAmelCase   					=  self.transformer.num_vector_embeds - 1
							lowerCAmelCase   					=  torch.full(__lowerCAmelCase       ,    __lowerCAmelCase).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).")
							lowerCAmelCase   					=  latents.to(self.device)

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

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

					lowerCAmelCase   					=  latents

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

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

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

							lowerCAmelCase   					=  self.truncate(__lowerCAmelCase       ,    __lowerCAmelCase)

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

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

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

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

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

					if output_type == "pil":
							lowerCAmelCase   					=  self.numpy_to_pil(__lowerCAmelCase)

					if not return_dict:
							return (image,)

					return ImagePipelineOutput(images=__lowerCAmelCase)







			def 							a_       (   self       ,    __lowerCAmelCase       ,    __lowerCAmelCase):




					"""simple docstring"""


					lowerCAmelCase					,     lowerCAmelCase   					=  torch.sort(__lowerCAmelCase       ,    1       ,    descending=__lowerCAmelCase)
					lowerCAmelCase   					=  torch.exp(__lowerCAmelCase)
					lowerCAmelCase   					=  sorted_p_x_0.cumsum(dim=1) < truncation_rate

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

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

					lowerCAmelCase   					=  log_p_x_0.clone()

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

					return rv





'''simple docstring'''




import enum
import warnings

from .. import MODEL_FOR_CAUSAL_LM_MAPPING, TF_MODEL_FOR_CAUSAL_LM_MAPPING
from ..utils import add_end_docstrings, is_tf_available
from .base import PIPELINE_INIT_ARGS, Pipeline


if is_tf_available():
						import tensorflow as tf






class 				a__(					enum.Enum	):


			'''simple docstring'''






			UpperCAmelCase_			:     Dict      =       0
			UpperCAmelCase_			:     Dict      =       1
			UpperCAmelCase_			:     Any      =       2







@add_end_docstrings(lowerCAmelCase__	)
class 				a__(					lowerCAmelCase__	):


			'''simple docstring'''






			UpperCAmelCase_			:     int      =       '''
    In 1991, the remains of Russian Tsar Nicholas II and his family (except for Alexei and Maria) are discovered. The
    voice of Nicholas\'s young son, Tsarevich Alexei Nikolaevich, narrates the remainder of the story. 1883 Western
    Siberia, a young Grigori Rasputin is asked by his father and a group of men to perform magic. Rasputin has a vision
    and denounces one of the men as a horse thief. Although his father initially slaps him for making such an
    accusation, Rasputin watches as the man is chased outside and beaten. Twenty years later, Rasputin sees a vision of
    the Virgin Mary, prompting him to become a priest. Rasputin quickly becomes famous, with people, even a bishop,
    begging for his blessing. <eod> </s> <eos>
    '''



			def __init__(   self       ,    *__lowerCAmelCase       ,    **__lowerCAmelCase):




					"""simple docstring"""


					super().__init__(*__lowerCAmelCase       ,    **__lowerCAmelCase)
					self.check_model_type(
					    TF_MODEL_FOR_CAUSAL_LM_MAPPING if self.framework == """tf""" else MODEL_FOR_CAUSAL_LM_MAPPING)
					if "prefix" not in self._preprocess_params:
							# This is very specific. The logic is quite complex and needs to be done
							# as a "default".
							# It also defines both some preprocess_kwargs and generate_kwargs
							# which is why we cannot put them in their respective methods.
							lowerCAmelCase   					=  None
							if self.model.config.prefix is not None:
									lowerCAmelCase   					=  self.model.config.prefix
							if prefix is None and self.model.__class__.__name__ in [
							    "XLNetLMHeadModel",
							    "TransfoXLLMHeadModel",
							    "TFXLNetLMHeadModel",
							    "TFTransfoXLLMHeadModel",
							]:
									# For XLNet and TransformerXL we add an article to the prompt to give more state to the model.
									lowerCAmelCase   					=  self.XL_PREFIX
							if prefix is not None:
									# Recalculate some generate_kwargs linked to prefix.
									lowerCAmelCase					,     lowerCAmelCase					,     lowerCAmelCase   					=  self._sanitize_parameters(prefix=__lowerCAmelCase       ,    **self._forward_params)
									lowerCAmelCase   					=  {**self._preprocess_params, **preprocess_params}
									lowerCAmelCase   					=  {**self._forward_params, **forward_params}



			def 							a_       (   self       ,    __lowerCAmelCase=None       ,    __lowerCAmelCase=None       ,    __lowerCAmelCase=None       ,    __lowerCAmelCase=None       ,    __lowerCAmelCase=None       ,    __lowerCAmelCase=None       ,    __lowerCAmelCase=None       ,    __lowerCAmelCase=None       ,    **__lowerCAmelCase       ,    ):




					"""simple docstring"""


					lowerCAmelCase   					=  {}
					if prefix is not None:
							lowerCAmelCase   					=  prefix
					if prefix:
							lowerCAmelCase   					=  self.tokenizer(
							    __lowerCAmelCase       ,    padding=__lowerCAmelCase       ,    add_special_tokens=__lowerCAmelCase       ,    return_tensors=self.framework)
							lowerCAmelCase   					=  prefix_inputs["""input_ids"""].shape[-1]

					if handle_long_generation is not None:
							if handle_long_generation not in {"hole"}:
									raise ValueError(
									    f"{handle_long_generation} is not a valid value for `handle_long_generation` parameter expected"
									    """ [None, 'hole']""")
							lowerCAmelCase   					=  handle_long_generation

					preprocess_params.update(__lowerCAmelCase)
					lowerCAmelCase   					=  generate_kwargs

					lowerCAmelCase   					=  {}
					if return_full_text is not None and return_type is None:
							if return_text is not None:
									raise ValueError("""`return_text` is mutually exclusive with `return_full_text`""")
							if return_tensors is not None:
									raise ValueError("""`return_full_text` is mutually exclusive with `return_tensors`""")
							lowerCAmelCase   					=  ReturnType.FULL_TEXT if return_full_text else ReturnType.NEW_TEXT
					if return_tensors is not None and return_type is None:
							if return_text is not None:
									raise ValueError("""`return_text` is mutually exclusive with `return_tensors`""")
							lowerCAmelCase   					=  ReturnType.TENSORS
					if return_type is not None:
							lowerCAmelCase   					=  return_type
					if clean_up_tokenization_spaces is not None:
							lowerCAmelCase   					=  clean_up_tokenization_spaces

					if stop_sequence is not None:
							lowerCAmelCase   					=  self.tokenizer.encode(__lowerCAmelCase       ,    add_special_tokens=__lowerCAmelCase)
							if len(__lowerCAmelCase) > 1:
									warnings.warn(
									    """Stopping on a multiple token sequence is not yet supported on transformers. The first token of"""
									    """ the stop sequence will be used as the stop sequence string in the interim.""")
							lowerCAmelCase   					=  stop_sequence_ids[0]

					return preprocess_params, forward_params, postprocess_params



			def 							a_       (   self       ,    *__lowerCAmelCase       ,    **__lowerCAmelCase):




					"""simple docstring"""


					if self.model.__class__.__name__ in ["TransfoXLLMHeadModel"]:
							kwargs.update({"""add_space_before_punct_symbol""": True})

					return super()._parse_and_tokenize(*__lowerCAmelCase       ,    **__lowerCAmelCase)



			def __call__(   self       ,    __lowerCAmelCase       ,    **__lowerCAmelCase):




					"""simple docstring"""


					return super().__call__(__lowerCAmelCase       ,    **__lowerCAmelCase)



			def 							a_       (   self       ,    __lowerCAmelCase       ,    __lowerCAmelCase=""       ,    __lowerCAmelCase=None       ,    **__lowerCAmelCase):




					"""simple docstring"""


					lowerCAmelCase   					=  self.tokenizer(
					    prefix + prompt_text       ,    padding=__lowerCAmelCase       ,    add_special_tokens=__lowerCAmelCase       ,    return_tensors=self.framework)
					lowerCAmelCase   					=  prompt_text

					if handle_long_generation == "hole":
							lowerCAmelCase   					=  inputs["""input_ids"""].shape[-1]
							if "max_new_tokens" in generate_kwargs:
									lowerCAmelCase   					=  generate_kwargs["""max_new_tokens"""]
							else:
									lowerCAmelCase   					=  generate_kwargs.get("""max_length"""       ,    self.model.config.max_length) - cur_len
									if new_tokens < 0:
											raise ValueError("""We cannot infer how many new tokens are expected""")
							if cur_len + new_tokens > self.tokenizer.model_max_length:
									lowerCAmelCase   					=  self.tokenizer.model_max_length - new_tokens
									if keep_length <= 0:
											raise ValueError(
											    """We cannot use `hole` to handle this generation the number of desired tokens exceeds the"""
											    """ models max length""")

									lowerCAmelCase   					=  inputs["""input_ids"""][:, -keep_length:]
									if "attention_mask" in inputs:
											lowerCAmelCase   					=  inputs["""attention_mask"""][:, -keep_length:]

					return inputs



			def 							a_       (   self       ,    __lowerCAmelCase       ,    **__lowerCAmelCase):




					"""simple docstring"""


					lowerCAmelCase   					=  model_inputs["""input_ids"""]
					lowerCAmelCase   					=  model_inputs.get("""attention_mask"""       ,    __lowerCAmelCase)
					# Allow empty prompts
					if input_ids.shape[1] == 0:
							lowerCAmelCase   					=  None
							lowerCAmelCase   					=  None
							lowerCAmelCase   					=  1
					else:
							lowerCAmelCase   					=  input_ids.shape[0]
					lowerCAmelCase   					=  model_inputs.pop("""prompt_text""")

					# If there is a prefix, we may need to adjust the generation length. Do so without permanently modifying
					# generate_kwargs, as some of the parameterization may come from the initialization of the pipeline.
					lowerCAmelCase   					=  generate_kwargs.pop("""prefix_length"""       ,    0)
					if prefix_length > 0:
							lowerCAmelCase   					=  """max_new_tokens""" in generate_kwargs or (
							    """generation_config""" in generate_kwargs
							    and generate_kwargs["""generation_config"""].max_new_tokens is not None
							)
							if not has_max_new_tokens:
									lowerCAmelCase   					=  generate_kwargs.get("""max_length""") or self.model.config.max_length
									generate_kwargs["max_length"] += prefix_length
							lowerCAmelCase   					=  """min_new_tokens""" in generate_kwargs or (
							    """generation_config""" in generate_kwargs
							    and generate_kwargs["""generation_config"""].min_new_tokens is not None
							)
							if not has_min_new_tokens and "min_length" in generate_kwargs:
									generate_kwargs["min_length"] += prefix_length

        # BS x SL
					lowerCAmelCase   					=  self.model.generate(input_ids=__lowerCAmelCase       ,    attention_mask=__lowerCAmelCase       ,    **__lowerCAmelCase)
					lowerCAmelCase   					=  generated_sequence.shape[0]
					if self.framework == "pt":
							lowerCAmelCase   					=  generated_sequence.reshape(__lowerCAmelCase       ,    out_b // in_b       ,    *generated_sequence.shape[1:])
					elif self.framework == "tf":
							lowerCAmelCase   					=  tf.reshape(__lowerCAmelCase       ,    (in_b, out_b // in_b, *generated_sequence.shape[1:]))
					return {"generated_sequence": generated_sequence, "input_ids": input_ids, "prompt_text": prompt_text}







			def 							a_       (   self       ,    __lowerCAmelCase       ,    __lowerCAmelCase=ReturnType.FULL_TEXT       ,    __lowerCAmelCase=True):




					"""simple docstring"""


					lowerCAmelCase   					=  model_outputs["""generated_sequence"""][0]
					lowerCAmelCase   					=  model_outputs["""input_ids"""]
					lowerCAmelCase   					=  model_outputs["""prompt_text"""]
					lowerCAmelCase   					=  generated_sequence.numpy().tolist()
					lowerCAmelCase   					=  []
					for sequence in generated_sequence:
							if return_type == ReturnType.TENSORS:
									lowerCAmelCase   					=  {"""generated_token_ids""": sequence}
							elif return_type in {ReturnType.NEW_TEXT, ReturnType.FULL_TEXT}:
									# Decode text
									lowerCAmelCase   					=  self.tokenizer.decode(
									    __lowerCAmelCase       ,    skip_special_tokens=__lowerCAmelCase       ,    clean_up_tokenization_spaces=__lowerCAmelCase       ,    )

									# Remove PADDING prompt of the sequence if XLNet or Transfo-XL model is used
									if input_ids is None:
											lowerCAmelCase   					=  0
									else:
											lowerCAmelCase   					=  len(
											    self.tokenizer.decode(
											        input_ids[0]       ,    skip_special_tokens=__lowerCAmelCase       ,    clean_up_tokenization_spaces=__lowerCAmelCase       ,    ))

									if return_type == ReturnType.FULL_TEXT:
											lowerCAmelCase   					=  prompt_text + text[prompt_length:]
									else:
											lowerCAmelCase   					=  text[prompt_length:]

									lowerCAmelCase   					=  {"""generated_text""": all_text}
							records.append(__lowerCAmelCase)

					return records




