



'''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 		_UpperCamelCase						(							lowerCamelCase__					):


			'''simple docstring'''

			_A   :	torch.FloatTensor






class 		_UpperCamelCase						(							lowerCamelCase__					,      lowerCamelCase__					):


			'''simple docstring'''

			@register_to_config
			def __init__(							self  :				Optional[Any]							,  lowerCAmelCase__  :				int = 3_2							,  lowerCAmelCase__  :				int = 6_4							,  lowerCAmelCase__  :				int = 2_0							,  lowerCAmelCase__  :				int = 7_6_8							,  lowerCAmelCase__  :				Dict=7_7							,  lowerCAmelCase__  :				int=4							,  lowerCAmelCase__  :				float = 0.0							,  lowerCAmelCase__  :				str = "silu"							,  lowerCAmelCase__  :				Optional[str] = None							,  lowerCAmelCase__  :				Optional[str] = None							,  lowerCAmelCase__  :				Optional[str] = "linear"							,  lowerCAmelCase__  :				Optional[str] = "prd"							,  lowerCAmelCase__  :				Optional[int] = None							,  lowerCAmelCase__  :				Optional[int] = None							,  lowerCAmelCase__  :				Optional[int] = None							,  ):





					"""simple docstring"""






					super().__init__()
					__SCREAMING_SNAKE_CASE :	str					 =	num_attention_heads
					__SCREAMING_SNAKE_CASE :	List[str]					 =	attention_head_dim
					__SCREAMING_SNAKE_CASE :	List[str]					 =	num_attention_heads * attention_head_dim
					__SCREAMING_SNAKE_CASE :	int					 =	additional_embeddings

					__SCREAMING_SNAKE_CASE :	Dict					 =	time_embed_dim or inner_dim
					__SCREAMING_SNAKE_CASE :	Tuple					 =	embedding_proj_dim or embedding_dim
					__SCREAMING_SNAKE_CASE :	Dict					 =	clip_embed_dim or embedding_dim

					__SCREAMING_SNAKE_CASE :	str					 =	Timesteps(lowerCAmelCase__							,  lowerCAmelCase__							,  0		)
					__SCREAMING_SNAKE_CASE :	Union[str, Any]					 =	TimestepEmbedding(lowerCAmelCase__							,  lowerCAmelCase__							,  out_dim=lowerCAmelCase__							,  act_fn=lowerCAmelCase__		)

					__SCREAMING_SNAKE_CASE :	Optional[Any]					 =	nn.Linear(lowerCAmelCase__							,  lowerCAmelCase__		)

					if embedding_proj_norm_type is None:
							__SCREAMING_SNAKE_CASE :	Union[str, Any]					 =	None
					elif embedding_proj_norm_type == "layer":
							__SCREAMING_SNAKE_CASE :	Any					 =	nn.LayerNorm(lowerCAmelCase__		)
					else:
							raise ValueError(F"unsupported embedding_proj_norm_type: {embedding_proj_norm_type}"		)

					__SCREAMING_SNAKE_CASE :	str					 =	nn.Linear(lowerCAmelCase__							,  lowerCAmelCase__		)

					if encoder_hid_proj_type is None:
							__SCREAMING_SNAKE_CASE :	Optional[int]					 =	None
					elif encoder_hid_proj_type == "linear":
							__SCREAMING_SNAKE_CASE :	Union[str, Any]					 =	nn.Linear(lowerCAmelCase__							,  lowerCAmelCase__		)
					else:
							raise ValueError(F"unsupported encoder_hid_proj_type: {encoder_hid_proj_type}"		)

					__SCREAMING_SNAKE_CASE :	List[Any]					 =	nn.Parameter(torch.zeros(1							,  num_embeddings + additional_embeddings							,  lowerCAmelCase__		)		)

					if added_emb_type == "prd":
							__SCREAMING_SNAKE_CASE :	Optional[int]					 =	nn.Parameter(torch.zeros(1							,  1							,  lowerCAmelCase__		)		)
					elif added_emb_type is None:
							__SCREAMING_SNAKE_CASE :	List[Any]					 =	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 :	Tuple					 =	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 :	Any					 =	nn.LayerNorm(lowerCAmelCase__		)
					elif norm_in_type is None:
							__SCREAMING_SNAKE_CASE :	str					 =	None
					else:
							raise ValueError(F"Unsupported norm_in_type: {norm_in_type}."		)

					__SCREAMING_SNAKE_CASE :	Optional[Any]					 =	nn.LayerNorm(lowerCAmelCase__		)

					__SCREAMING_SNAKE_CASE :	Tuple					 =	nn.Linear(lowerCAmelCase__							,  lowerCAmelCase__		)

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

					__SCREAMING_SNAKE_CASE :	List[Any]					 =	nn.Parameter(torch.zeros(1							,  lowerCAmelCase__		)		)
					__SCREAMING_SNAKE_CASE :	int					 =	nn.Parameter(torch.zeros(1							,  lowerCAmelCase__		)		)

			@property
			# Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.attn_processors
			def UpperCamelCase__      (							self  :				Any		):





					"""simple docstring"""






					__SCREAMING_SNAKE_CASE :	Any					 =	{}

					def fn_recursive_add_processors(lowerCAmelCase__  :				str							,  lowerCAmelCase__  :				torch.nn.Module							,  lowerCAmelCase__  :				Dict[str, AttentionProcessor]		):
							if hasattr(lowerCAmelCase__							,  """set_processor"""		):
									__SCREAMING_SNAKE_CASE :	Dict					 =	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 UpperCamelCase__      (							self  :				Dict							,  lowerCAmelCase__  :				Union[AttentionProcessor, Dict[str, AttentionProcessor]]		):





					"""simple docstring"""






					__SCREAMING_SNAKE_CASE :	Optional[Any]					 =	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__  :				str							,  lowerCAmelCase__  :				torch.nn.Module							,  lowerCAmelCase__  :				List[str]		):
							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 UpperCamelCase__      (							self  :				Any		):





					"""simple docstring"""






					self.set_attn_processor(AttnProcessor()		)

			def UpperCamelCase__      (							self  :				List[Any]							,  lowerCAmelCase__  :				int							,  lowerCAmelCase__  :				Union[torch.Tensor, float, int]							,  lowerCAmelCase__  :				torch.FloatTensor							,  lowerCAmelCase__  :				Optional[torch.FloatTensor] = None							,  lowerCAmelCase__  :				Optional[torch.BoolTensor] = None							,  lowerCAmelCase__  :				bool = True							,  ):





					"""simple docstring"""






					__SCREAMING_SNAKE_CASE :	Tuple					 =	hidden_states.shape[0]

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

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

					__SCREAMING_SNAKE_CASE :	Union[str, Any]					 =	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 :	str					 =	timesteps_projected.to(dtype=self.dtype		)
					__SCREAMING_SNAKE_CASE :	List[Any]					 =	self.time_embedding(lowerCAmelCase__		)

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

					__SCREAMING_SNAKE_CASE :	Optional[Any]					 =	self.embedding_proj(lowerCAmelCase__		)
					if self.encoder_hidden_states_proj is not None and encoder_hidden_states is not None:
							__SCREAMING_SNAKE_CASE :	Optional[int]					 =	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 :	List[Any]					 =	self.proj_in(lowerCAmelCase__		)

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

					__SCREAMING_SNAKE_CASE :	Tuple					 =	[]
					__SCREAMING_SNAKE_CASE :	Any					 =	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 :	Tuple					 =	proj_embeddings[:, None, :]

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

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

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

					__SCREAMING_SNAKE_CASE :	List[Any]					 =	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 :	int					 =	additional_embeddings_len + proj_embeddings.shape[1] + 1
					if positional_embeddings.shape[1] < hidden_states.shape[1]:
							__SCREAMING_SNAKE_CASE :	Tuple					 =	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 :	Union[str, Any]					 =	hidden_states + positional_embeddings

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

					if self.norm_in is not None:
							__SCREAMING_SNAKE_CASE :	List[str]					 =	self.norm_in(lowerCAmelCase__		)

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

					__SCREAMING_SNAKE_CASE :	List[Any]					 =	self.norm_out(lowerCAmelCase__		)

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

					__SCREAMING_SNAKE_CASE :	List[str]					 =	self.proj_to_clip_embeddings(lowerCAmelCase__		)

					if not return_dict:
							return (predicted_image_embedding,)

					return PriorTransformerOutput(predicted_image_embedding=lowerCAmelCase__		)



			def UpperCamelCase__      (							self  :				int							,  lowerCAmelCase__  :				Optional[Any]		):





					"""simple docstring"""






					__SCREAMING_SNAKE_CASE :	List[Any]					 =	(prior_latents * self.clip_std) + self.clip_mean
					return prior_latents




'''simple docstring'''




from typing import Mapping

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxSeqaSeqConfigWithPast
from ...utils import logging


UpperCamelCase__ :			Tuple												=				logging.get_logger(__name__)

UpperCamelCase__ :			List[str]												=				{
    '''t5-small''': '''https://huggingface.co/t5-small/resolve/main/config.json''',
    '''t5-base''': '''https://huggingface.co/t5-base/resolve/main/config.json''',
    '''t5-large''': '''https://huggingface.co/t5-large/resolve/main/config.json''',
    '''t5-3b''': '''https://huggingface.co/t5-3b/resolve/main/config.json''',
    '''t5-11b''': '''https://huggingface.co/t5-11b/resolve/main/config.json''',
}






class 		_UpperCamelCase						(							lowerCamelCase__					):


			'''simple docstring'''

			_A   :	Union[str, Any]    					=	'''t5'''
			_A   :	Optional[Any]    					=	['''past_key_values''']
			_A   :	Any    					=	{'''hidden_size''': '''d_model''', '''num_attention_heads''': '''num_heads''', '''num_hidden_layers''': '''num_layers'''}

			def __init__(							self  :				Union[str, Any]							,  lowerCAmelCase__  :				List[str]=3_2_1_2_8							,  lowerCAmelCase__  :				Dict=5_1_2							,  lowerCAmelCase__  :				str=6_4							,  lowerCAmelCase__  :				Tuple=2_0_4_8							,  lowerCAmelCase__  :				Optional[Any]=6							,  lowerCAmelCase__  :				Any=None							,  lowerCAmelCase__  :				Any=8							,  lowerCAmelCase__  :				Dict=3_2							,  lowerCAmelCase__  :				Dict=1_2_8							,  lowerCAmelCase__  :				Any=0.1							,  lowerCAmelCase__  :				str=1E-6							,  lowerCAmelCase__  :				str=1.0							,  lowerCAmelCase__  :				Optional[Any]="relu"							,  lowerCAmelCase__  :				List[str]=True							,  lowerCAmelCase__  :				Union[str, Any]=True							,  lowerCAmelCase__  :				Optional[Any]=0							,  lowerCAmelCase__  :				List[Any]=1							,  **lowerCAmelCase__  :				Dict							,  ):





					"""simple docstring"""






					__SCREAMING_SNAKE_CASE :	List[str]					 =	vocab_size
					__SCREAMING_SNAKE_CASE :	str					 =	d_model
					__SCREAMING_SNAKE_CASE :	str					 =	d_kv
					__SCREAMING_SNAKE_CASE :	Optional[Any]					 =	d_ff
					__SCREAMING_SNAKE_CASE :	Optional[Any]					 =	num_layers
					__SCREAMING_SNAKE_CASE :	List[str]					 =	(
					    num_decoder_layers if num_decoder_layers is not None else self.num_layers
					)  # default = symmetry
					__SCREAMING_SNAKE_CASE :	Optional[int]					 =	num_heads
					__SCREAMING_SNAKE_CASE :	Any					 =	relative_attention_num_buckets
					__SCREAMING_SNAKE_CASE :	int					 =	relative_attention_max_distance
					__SCREAMING_SNAKE_CASE :	Optional[int]					 =	dropout_rate
					__SCREAMING_SNAKE_CASE :	Optional[int]					 =	layer_norm_epsilon
					__SCREAMING_SNAKE_CASE :	Optional[int]					 =	initializer_factor
					__SCREAMING_SNAKE_CASE :	Any					 =	feed_forward_proj
					__SCREAMING_SNAKE_CASE :	str					 =	use_cache

					__SCREAMING_SNAKE_CASE :	List[str]					 =	self.feed_forward_proj.split("""-"""		)
					__SCREAMING_SNAKE_CASE :	Tuple					 =	act_info[-1]
					__SCREAMING_SNAKE_CASE :	int					 =	act_info[0] == """gated"""

					if len(lowerCAmelCase__		) > 1 and act_info[0] != "gated" or len(lowerCAmelCase__		) > 2:
							raise ValueError(
							    F"`feed_forward_proj`: {feed_forward_proj} is not a valid activation function of the dense layer."
							    """Please make sure `feed_forward_proj` is of the format `gated-{ACT_FN}` or `{ACT_FN}`, e.g. """
							    """'gated-gelu' or 'relu'"""		)

					# for backwards compatibility
					if feed_forward_proj == "gated-gelu":
							__SCREAMING_SNAKE_CASE :	List[Any]					 =	"""gelu_new"""

					super().__init__(
					    pad_token_id=lowerCAmelCase__							,  eos_token_id=lowerCAmelCase__							,  is_encoder_decoder=lowerCAmelCase__							,  **lowerCAmelCase__							,  )






class 		_UpperCamelCase						(							lowerCamelCase__					):


			'''simple docstring'''

			@property
			def UpperCamelCase__      (							self  :				Tuple		):





					"""simple docstring"""






					__SCREAMING_SNAKE_CASE :	List[Any]					 =	{
					    """input_ids""": {0: """batch""", 1: """encoder_sequence"""},
					    """attention_mask""": {0: """batch""", 1: """encoder_sequence"""},
					}
					if self.use_past:
							__SCREAMING_SNAKE_CASE :	Optional[Any]					 =	"""past_encoder_sequence + sequence"""
							__SCREAMING_SNAKE_CASE :	Optional[Any]					 =	{0: """batch"""}
							__SCREAMING_SNAKE_CASE :	Optional[int]					 =	{0: """batch""", 1: """past_decoder_sequence + sequence"""}
					else:
							__SCREAMING_SNAKE_CASE :	List[Any]					 =	{0: """batch""", 1: """decoder_sequence"""}
							__SCREAMING_SNAKE_CASE :	Optional[Any]					 =	{0: """batch""", 1: """decoder_sequence"""}

					if self.use_past:
							self.fill_with_past_key_values_(lowerCAmelCase__							,  direction="""inputs"""		)

					return common_inputs



			@property
			def UpperCamelCase__      (							self  :				List[str]		):





					"""simple docstring"""






					return 1_3