
"""simple docstring"""





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

import torch
import torch.nn.functional as F
from torch import nn

from ..configuration_utils import ConfigMixin, register_to_config
from ..utils import BaseOutput
from .attention import BasicTransformerBlock
from .attention_processor import AttentionProcessor, AttnProcessor
from .embeddings import TimestepEmbedding, Timesteps
from .modeling_utils import ModelMixin
@dataclass
class 						SCREAMING_SNAKE_CASE_ (						__a ):




		"""simple docstring"""





		__lowercase							:  torch.FloatTensor



class 						SCREAMING_SNAKE_CASE_ (						__a     ,				__a ):




		"""simple docstring"""





		@register_to_config
		def __init__(     self							,  lowerCAmelCase__ = 3_2							,  lowerCAmelCase__ = 6_4							,  lowerCAmelCase__ = 2_0							,  lowerCAmelCase__ = 7_6_8							,  lowerCAmelCase__=7_7							,  lowerCAmelCase__=4							,  lowerCAmelCase__ = 0.0							,  lowerCAmelCase__ = "silu"							,  lowerCAmelCase__ = None							,  lowerCAmelCase__ = None							,  lowerCAmelCase__ = "linear"							,  lowerCAmelCase__ = "prd"							,  lowerCAmelCase__ = None							,  lowerCAmelCase__ = None							,  lowerCAmelCase__ = None							,  ):
				super().__init__()
				__SCREAMING_SNAKE_CASE            = num_attention_heads
				__SCREAMING_SNAKE_CASE            = attention_head_dim
				__SCREAMING_SNAKE_CASE            = num_attention_heads * attention_head_dim
				__SCREAMING_SNAKE_CASE            = additional_embeddings

				__SCREAMING_SNAKE_CASE            = time_embed_dim or inner_dim
				__SCREAMING_SNAKE_CASE            = embedding_proj_dim or embedding_dim
				__SCREAMING_SNAKE_CASE            = clip_embed_dim or embedding_dim

				__SCREAMING_SNAKE_CASE            = Timesteps(lowerCAmelCase__							,  lowerCAmelCase__							,  0)
				__SCREAMING_SNAKE_CASE            = TimestepEmbedding(lowerCAmelCase__							,  lowerCAmelCase__							,  out_dim=lowerCAmelCase__							,  act_fn=lowerCAmelCase__)

				__SCREAMING_SNAKE_CASE            = nn.Linear(lowerCAmelCase__							,  lowerCAmelCase__)

				if embedding_proj_norm_type is None:
						__SCREAMING_SNAKE_CASE            = None
				elif embedding_proj_norm_type == "layer":
						__SCREAMING_SNAKE_CASE            = nn.LayerNorm(lowerCAmelCase__)
				else:
						raise ValueError(f"unsupported embedding_proj_norm_type: {embedding_proj_norm_type}")

				__SCREAMING_SNAKE_CASE            = nn.Linear(lowerCAmelCase__							,  lowerCAmelCase__)

				if encoder_hid_proj_type is None:
						__SCREAMING_SNAKE_CASE            = None
				elif encoder_hid_proj_type == "linear":
						__SCREAMING_SNAKE_CASE            = nn.Linear(lowerCAmelCase__							,  lowerCAmelCase__)
				else:
						raise ValueError(f"unsupported encoder_hid_proj_type: {encoder_hid_proj_type}")

				__SCREAMING_SNAKE_CASE            = nn.Parameter(torch.zeros(1							,  num_embeddings + additional_embeddings							,  lowerCAmelCase__))

				if added_emb_type == "prd":
						__SCREAMING_SNAKE_CASE            = nn.Parameter(torch.zeros(1							,  1							,  lowerCAmelCase__))
				elif added_emb_type is None:
						__SCREAMING_SNAKE_CASE            = None
				else:
						raise ValueError(
						    f"`added_emb_type`: {added_emb_type} is not supported. Make sure to choose one of `'prd'` or `None`.")

				__SCREAMING_SNAKE_CASE            = nn.ModuleList(
				    [
				        BasicTransformerBlock(
				            lowerCAmelCase__							,  lowerCAmelCase__							,  lowerCAmelCase__							,  dropout=lowerCAmelCase__							,  activation_fn="""gelu"""							,  attention_bias=lowerCAmelCase__							,  )
				        for d in range(lowerCAmelCase__)
				    ])

				if norm_in_type == "layer":
						__SCREAMING_SNAKE_CASE            = nn.LayerNorm(lowerCAmelCase__)
				elif norm_in_type is None:
						__SCREAMING_SNAKE_CASE            = None
				else:
						raise ValueError(f"Unsupported norm_in_type: {norm_in_type}.")

				__SCREAMING_SNAKE_CASE            = nn.LayerNorm(lowerCAmelCase__)

				__SCREAMING_SNAKE_CASE            = nn.Linear(lowerCAmelCase__							,  lowerCAmelCase__)

				__SCREAMING_SNAKE_CASE            = torch.full(
				    [num_embeddings + additional_embeddings, num_embeddings + additional_embeddings]							,  -1_00_00.0)
				causal_attention_mask.triu_(1)
				__SCREAMING_SNAKE_CASE            = causal_attention_mask[None, ...]
				self.register_buffer("""causal_attention_mask"""							,  lowerCAmelCase__							,  persistent=lowerCAmelCase__)

				__SCREAMING_SNAKE_CASE            = nn.Parameter(torch.zeros(1							,  lowerCAmelCase__))
				__SCREAMING_SNAKE_CASE            = nn.Parameter(torch.zeros(1							,  lowerCAmelCase__))




		@property
		# Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.attn_processors
		def 	snake_case_     (     self):
				__SCREAMING_SNAKE_CASE            = {}

				def fn_recursive_add_processors(lowerCAmelCase__							,  lowerCAmelCase__							,  lowerCAmelCase__):
						if hasattr(lowerCAmelCase__							,  """set_processor"""):
								__SCREAMING_SNAKE_CASE            = module.processor

						for sub_name, child in module.named_children():
								fn_recursive_add_processors(f"{name}.{sub_name}"							,  lowerCAmelCase__							,  lowerCAmelCase__)

						return processors

				for name, module in self.named_children():
						fn_recursive_add_processors(lowerCAmelCase__							,  lowerCAmelCase__							,  lowerCAmelCase__)

				return processors




		def 	snake_case_     (     self							,  lowerCAmelCase__):
				__SCREAMING_SNAKE_CASE            = len(self.attn_processors.keys())

				if isinstance(lowerCAmelCase__							,  lowerCAmelCase__) and len(lowerCAmelCase__) != count:
						raise ValueError(
						    f"A dict of processors was passed, but the number of processors {len(lowerCAmelCase__)} does not match the"
						    f" number of attention layers: {count}. Please make sure to pass {count} processor classes.")

				def fn_recursive_attn_processor(lowerCAmelCase__							,  lowerCAmelCase__							,  lowerCAmelCase__):
						if hasattr(lowerCAmelCase__							,  """set_processor"""):
								if not isinstance(lowerCAmelCase__							,  lowerCAmelCase__):
										module.set_processor(lowerCAmelCase__)
								else:
										module.set_processor(processor.pop(f"{name}.processor"))

						for sub_name, child in module.named_children():
								fn_recursive_attn_processor(f"{name}.{sub_name}"							,  lowerCAmelCase__							,  lowerCAmelCase__)

				for name, module in self.named_children():
						fn_recursive_attn_processor(lowerCAmelCase__							,  lowerCAmelCase__							,  lowerCAmelCase__)




		def 	snake_case_     (     self):
				self.set_attn_processor(AttnProcessor())




		def 	snake_case_     (     self							,  lowerCAmelCase__							,  lowerCAmelCase__							,  lowerCAmelCase__							,  lowerCAmelCase__ = None							,  lowerCAmelCase__ = None							,  lowerCAmelCase__ = True							,  ):
				__SCREAMING_SNAKE_CASE            = hidden_states.shape[0]

				__SCREAMING_SNAKE_CASE            = timestep
				if not torch.is_tensor(lowerCAmelCase__):
						__SCREAMING_SNAKE_CASE            = torch.tensor([timesteps]							,  dtype=torch.long							,  device=hidden_states.device)
				elif torch.is_tensor(lowerCAmelCase__) and len(timesteps.shape) == 0:
						__SCREAMING_SNAKE_CASE            = timesteps[None].to(hidden_states.device)

				# broadcast to batch dimension in a way that's compatible with ONNX/Core ML
				__SCREAMING_SNAKE_CASE            = timesteps * torch.ones(lowerCAmelCase__							,  dtype=timesteps.dtype							,  device=timesteps.device)

				__SCREAMING_SNAKE_CASE            = self.time_proj(lowerCAmelCase__)

				# timesteps does not contain any weights and will always return f32 tensors
				# but time_embedding might be fp16, so we need to cast here.
				__SCREAMING_SNAKE_CASE            = timesteps_projected.to(dtype=self.dtype)
				__SCREAMING_SNAKE_CASE            = self.time_embedding(lowerCAmelCase__)

				if self.embedding_proj_norm is not None:
						__SCREAMING_SNAKE_CASE            = self.embedding_proj_norm(lowerCAmelCase__)

				__SCREAMING_SNAKE_CASE            = self.embedding_proj(lowerCAmelCase__)
				if self.encoder_hidden_states_proj is not None and encoder_hidden_states is not None:
						__SCREAMING_SNAKE_CASE            = self.encoder_hidden_states_proj(lowerCAmelCase__)
				elif self.encoder_hidden_states_proj is not None and encoder_hidden_states is None:
						raise ValueError("""`encoder_hidden_states_proj` requires `encoder_hidden_states` to be set""")

				__SCREAMING_SNAKE_CASE            = self.proj_in(lowerCAmelCase__)

				__SCREAMING_SNAKE_CASE            = self.positional_embedding.to(hidden_states.dtype)

				__SCREAMING_SNAKE_CASE            = []
				__SCREAMING_SNAKE_CASE            = 0

				if encoder_hidden_states is not None:
						additional_embeds.append(lowerCAmelCase__)
						additional_embeddings_len += encoder_hidden_states.shape[1]

				if len(proj_embeddings.shape) == 2:
						__SCREAMING_SNAKE_CASE            = proj_embeddings[:, None, :]

				if len(hidden_states.shape) == 2:
						__SCREAMING_SNAKE_CASE            = hidden_states[:, None, :]

				__SCREAMING_SNAKE_CASE            = additional_embeds + [
				    proj_embeddings,
				    time_embeddings[:, None, :],
				    hidden_states,
				]

				if self.prd_embedding is not None:
						__SCREAMING_SNAKE_CASE            = self.prd_embedding.to(hidden_states.dtype).expand(lowerCAmelCase__							,  -1							,  -1)
						additional_embeds.append(lowerCAmelCase__)

				__SCREAMING_SNAKE_CASE            = torch.cat(
				    lowerCAmelCase__							,  dim=1							,  )

				# Allow positional_embedding to not include the `addtional_embeddings` and instead pad it with zeros for these additional tokens
				__SCREAMING_SNAKE_CASE            = additional_embeddings_len + proj_embeddings.shape[1] + 1
				if positional_embeddings.shape[1] < hidden_states.shape[1]:
						__SCREAMING_SNAKE_CASE            = F.pad(
						    lowerCAmelCase__							,  (
						        0,
						        0,
						        additional_embeddings_len,
						        self.prd_embedding.shape[1] if self.prd_embedding is not None else 0,
						    )							,  value=0.0							,  )

				__SCREAMING_SNAKE_CASE            = hidden_states + positional_embeddings

				if attention_mask is not None:
						__SCREAMING_SNAKE_CASE            = (1 - attention_mask.to(hidden_states.dtype)) * -1_00_00.0
						__SCREAMING_SNAKE_CASE            = F.pad(lowerCAmelCase__							,  (0, self.additional_embeddings)							,  value=0.0)
						__SCREAMING_SNAKE_CASE            = (attention_mask[:, None, :] + self.causal_attention_mask).to(hidden_states.dtype)
						__SCREAMING_SNAKE_CASE            = attention_mask.repeat_interleave(self.config.num_attention_heads							,  dim=0)

				if self.norm_in is not None:
						__SCREAMING_SNAKE_CASE            = self.norm_in(lowerCAmelCase__)

				for block in self.transformer_blocks:
						__SCREAMING_SNAKE_CASE            = block(lowerCAmelCase__							,  attention_mask=lowerCAmelCase__)

				__SCREAMING_SNAKE_CASE            = self.norm_out(lowerCAmelCase__)

				if self.prd_embedding is not None:
						__SCREAMING_SNAKE_CASE            = hidden_states[:, -1]
				else:
						__SCREAMING_SNAKE_CASE            = hidden_states[:, additional_embeddings_len:]

				__SCREAMING_SNAKE_CASE            = self.proj_to_clip_embeddings(lowerCAmelCase__)

				if not return_dict:
						return (predicted_image_embedding,)

				return PriorTransformerOutput(predicted_image_embedding=lowerCAmelCase__)




		def 	snake_case_     (     self							,  lowerCAmelCase__):
				__SCREAMING_SNAKE_CASE            = (prior_latents * self.clip_std) + self.clip_mean
				return prior_latents






"""simple docstring"""





from typing import Dict

import numpy as np

from ..utils import add_end_docstrings, is_tf_available, is_torch_available, logging
from .base import PIPELINE_INIT_ARGS, GenericTensor, Pipeline, PipelineException


if is_tf_available():
							import tensorflow as tf

							from ..tf_utils import stable_softmax


if is_torch_available():
							import torch


__magic_name__       =			logging.get_logger(__name__)
@add_end_docstrings(
    __a     ,				R'''
        top_k (`int`, defaults to 5):
            The number of predictions to return.
        targets (`str` or `List[str]`, *optional*):
            When passed, the model will limit the scores to the passed targets instead of looking up in the whole
            vocab. If the provided targets are not in the model vocab, they will be tokenized and the first resulting
            token will be used (with a warning, and that might be slower).

    '''     ,				)
class 						SCREAMING_SNAKE_CASE_ (						__a ):




		"""simple docstring"""





		def 	snake_case_     (     self							,  lowerCAmelCase__):
				if self.framework == "tf":
						__SCREAMING_SNAKE_CASE            = tf.where(input_ids == self.tokenizer.mask_token_id).numpy()
				elif self.framework == "pt":
						__SCREAMING_SNAKE_CASE            = torch.nonzero(input_ids == self.tokenizer.mask_token_id							,  as_tuple=lowerCAmelCase__)
				else:
						raise ValueError("""Unsupported framework""")
				return masked_index




		def 	snake_case_     (     self							,  lowerCAmelCase__):
				__SCREAMING_SNAKE_CASE            = self.get_masked_index(lowerCAmelCase__)
				__SCREAMING_SNAKE_CASE            = np.prod(masked_index.shape)
				if numel < 1:
						raise PipelineException(
						    """fill-mask"""							,  self.model.base_model_prefix							,  f"No mask_token ({self.tokenizer.mask_token}) found on the input"							,  )




		def 	snake_case_     (     self							,  lowerCAmelCase__):
				if isinstance(lowerCAmelCase__							,  lowerCAmelCase__):
						for model_input in model_inputs:
								self._ensure_exactly_one_mask_token(model_input["""input_ids"""][0])
				else:
						for input_ids in model_inputs["input_ids"]:
								self._ensure_exactly_one_mask_token(lowerCAmelCase__)




		def 	snake_case_     (     self							,  lowerCAmelCase__							,  lowerCAmelCase__=None							,  **lowerCAmelCase__):
				if return_tensors is None:
						__SCREAMING_SNAKE_CASE            = self.framework
				__SCREAMING_SNAKE_CASE            = self.tokenizer(lowerCAmelCase__							,  return_tensors=lowerCAmelCase__)
				self.ensure_exactly_one_mask_token(lowerCAmelCase__)
				return model_inputs




		def 	snake_case_     (     self							,  lowerCAmelCase__):
				__SCREAMING_SNAKE_CASE            = self.model(**lowerCAmelCase__)
				__SCREAMING_SNAKE_CASE            = model_inputs["""input_ids"""]
				return model_outputs




		def 	snake_case_     (     self							,  lowerCAmelCase__							,  lowerCAmelCase__=5							,  lowerCAmelCase__=None):
				# Cap top_k if there are targets
				if target_ids is not None and target_ids.shape[0] < top_k:
						__SCREAMING_SNAKE_CASE            = target_ids.shape[0]
				__SCREAMING_SNAKE_CASE            = model_outputs["""input_ids"""][0]
				__SCREAMING_SNAKE_CASE            = model_outputs["""logits"""]

				if self.framework == "tf":
						__SCREAMING_SNAKE_CASE            = tf.where(input_ids == self.tokenizer.mask_token_id).numpy()[:, 0]

						__SCREAMING_SNAKE_CASE            = outputs.numpy()

						__SCREAMING_SNAKE_CASE            = outputs[0, masked_index, :]
						__SCREAMING_SNAKE_CASE            = stable_softmax(lowerCAmelCase__							,  axis=-1)
						if target_ids is not None:
								__SCREAMING_SNAKE_CASE            = tf.gather_nd(tf.squeeze(lowerCAmelCase__							,  0)							,  target_ids.reshape(-1							,  1))
								__SCREAMING_SNAKE_CASE            = tf.expand_dims(lowerCAmelCase__							,  0)

						__SCREAMING_SNAKE_CASE            = tf.math.top_k(lowerCAmelCase__							,  k=lowerCAmelCase__)
						__SCREAMING_SNAKE_CASE       ,__SCREAMING_SNAKE_CASE            = topk.values.numpy(), topk.indices.numpy()
				else:
						__SCREAMING_SNAKE_CASE            = torch.nonzero(input_ids == self.tokenizer.mask_token_id							,  as_tuple=lowerCAmelCase__).squeeze(-1)
						# Fill mask pipeline supports only one ${mask_token} per sample

						__SCREAMING_SNAKE_CASE            = outputs[0, masked_index, :]
						__SCREAMING_SNAKE_CASE            = logits.softmax(dim=-1)
						if target_ids is not None:
								__SCREAMING_SNAKE_CASE            = probs[..., target_ids]

						__SCREAMING_SNAKE_CASE       ,__SCREAMING_SNAKE_CASE            = probs.topk(lowerCAmelCase__)

				__SCREAMING_SNAKE_CASE            = []
				__SCREAMING_SNAKE_CASE            = values.shape[0] == 1
				for i, (_values, _predictions) in enumerate(zip(values.tolist()							,  predictions.tolist())):
						__SCREAMING_SNAKE_CASE            = []
						for v, p in zip(_values							,  _predictions):
								# Copy is important since we're going to modify this array in place
								__SCREAMING_SNAKE_CASE            = input_ids.numpy().copy()
								if target_ids is not None:
										__SCREAMING_SNAKE_CASE            = target_ids[p].tolist()

								__SCREAMING_SNAKE_CASE            = p
								# Filter padding out:
								__SCREAMING_SNAKE_CASE            = tokens[np.where(tokens != self.tokenizer.pad_token_id)]
								# Originally we skip special tokens to give readable output.
								# For multi masks though, the other [MASK] would be removed otherwise
								# making the output look odd, so we add them back
								__SCREAMING_SNAKE_CASE            = self.tokenizer.decode(lowerCAmelCase__							,  skip_special_tokens=lowerCAmelCase__)
								__SCREAMING_SNAKE_CASE            = {"""score""": v, """token""": p, """token_str""": self.tokenizer.decode([p]), """sequence""": sequence}
								row.append(lowerCAmelCase__)
						result.append(lowerCAmelCase__)
				if single_mask:
						return result[0]
				return result




		def 	snake_case_     (     self							,  lowerCAmelCase__							,  lowerCAmelCase__=None):
				if isinstance(lowerCAmelCase__							,  lowerCAmelCase__):
						__SCREAMING_SNAKE_CASE            = [targets]
				try:
						__SCREAMING_SNAKE_CASE            = self.tokenizer.get_vocab()
				except Exception:
						__SCREAMING_SNAKE_CASE            = {}
				__SCREAMING_SNAKE_CASE            = []
				for target in targets:
						__SCREAMING_SNAKE_CASE            = vocab.get(lowerCAmelCase__							,  lowerCAmelCase__)
						if id_ is None:
								__SCREAMING_SNAKE_CASE            = self.tokenizer(
								    lowerCAmelCase__							,  add_special_tokens=lowerCAmelCase__							,  return_attention_mask=lowerCAmelCase__							,  return_token_type_ids=lowerCAmelCase__							,  max_length=1							,  truncation=lowerCAmelCase__							,  )["""input_ids"""]
								if len(lowerCAmelCase__) == 0:
										logger.warning(
										    f"The specified target token `{target}` does not exist in the model vocabulary. "
										    """We cannot replace it with anything meaningful, ignoring it""")
										continue
								__SCREAMING_SNAKE_CASE            = input_ids[0]
								# XXX: If users encounter this pass
								# it becomes pretty slow, so let's make sure
								# The warning enables them to fix the input to
								# get faster performance.
								logger.warning(
								    f"The specified target token `{target}` does not exist in the model vocabulary. "
								    f"Replacing with `{self.tokenizer.convert_ids_to_tokens(id_)}`.")
						target_ids.append(id_)
				__SCREAMING_SNAKE_CASE            = list(set(lowerCAmelCase__))
				if len(lowerCAmelCase__) == 0:
						raise ValueError("""At least one target must be provided when passed.""")
				__SCREAMING_SNAKE_CASE            = np.array(lowerCAmelCase__)
				return target_ids




		def 	snake_case_     (     self							,  lowerCAmelCase__=None							,  lowerCAmelCase__=None):
				__SCREAMING_SNAKE_CASE            = {}

				if targets is not None:
						__SCREAMING_SNAKE_CASE            = self.get_target_ids(lowerCAmelCase__							,  lowerCAmelCase__)
						__SCREAMING_SNAKE_CASE            = target_ids

				if top_k is not None:
						__SCREAMING_SNAKE_CASE            = top_k

				if self.tokenizer.mask_token_id is None:
						raise PipelineException(
						    """fill-mask"""							,  self.model.base_model_prefix							,  """The tokenizer does not define a `mask_token`.""")
				return {}, {}, postprocess_params




		def __call__(     self							,  lowerCAmelCase__							,  *lowerCAmelCase__							,  **lowerCAmelCase__):
				__SCREAMING_SNAKE_CASE            = super().__call__(lowerCAmelCase__							,  **lowerCAmelCase__)
				if isinstance(lowerCAmelCase__							,  lowerCAmelCase__) and len(lowerCAmelCase__) == 1:
						return outputs[0]
				return outputs




