
'''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  lowerCAmelCase__   (  lowerCamelCase_     ):
					lowerCAmelCase_        =     42







class  lowerCAmelCase__   (  lowerCamelCase_    ,						lowerCamelCase_     ):






					@register_to_config
					def __init__(   self				,							__SCREAMING_SNAKE_CASE = 32				,							__SCREAMING_SNAKE_CASE = 64				,							__SCREAMING_SNAKE_CASE = 20				,							__SCREAMING_SNAKE_CASE = 7_68				,							__SCREAMING_SNAKE_CASE=77				,							__SCREAMING_SNAKE_CASE=4				,							__SCREAMING_SNAKE_CASE = 0.0				,							__SCREAMING_SNAKE_CASE = "silu"				,							__SCREAMING_SNAKE_CASE = None				,							__SCREAMING_SNAKE_CASE = None				,							__SCREAMING_SNAKE_CASE = "linear"				,							__SCREAMING_SNAKE_CASE = "prd"				,							__SCREAMING_SNAKE_CASE = None				,							__SCREAMING_SNAKE_CASE = None				,							__SCREAMING_SNAKE_CASE = None				,							):


											"""simple docstring"""





											super().__init__()
											lowercase_	:     Any													=       num_attention_heads
											lowercase_	:     Optional[int]													=       attention_head_dim
											lowercase_	:     int													=       num_attention_heads * attention_head_dim
											lowercase_	:     Tuple													=       additional_embeddings

											lowercase_	:     Any													=       time_embed_dim or inner_dim
											lowercase_	:     Optional[Any]													=       embedding_proj_dim or embedding_dim
											lowercase_	:     Any													=       clip_embed_dim or embedding_dim

											lowercase_	:     Tuple													=       Timesteps(__snake_case				,							__snake_case				,							0		)
											lowercase_	:     List[Any]													=       TimestepEmbedding(__snake_case				,							__snake_case				,							out_dim=__snake_case				,							act_fn=__snake_case		)

											lowercase_	:     Optional[int]													=       nn.Linear(__snake_case				,							__snake_case		)

											if embedding_proj_norm_type is None:
																	lowercase_	:     Optional[int]													=       None
											elif embedding_proj_norm_type == "layer":
																	lowercase_	:     Optional[int]													=       nn.LayerNorm(__snake_case		)
											else:
																	raise ValueError(F'''unsupported embedding_proj_norm_type: {embedding_proj_norm_type}'''		)

											lowercase_	:     Dict													=       nn.Linear(__snake_case				,							__snake_case		)

											if encoder_hid_proj_type is None:
																	lowercase_	:     Dict													=       None
											elif encoder_hid_proj_type == "linear":
																	lowercase_	:     Any													=       nn.Linear(__snake_case				,							__snake_case		)
											else:
																	raise ValueError(F'''unsupported encoder_hid_proj_type: {encoder_hid_proj_type}'''		)

											lowercase_	:     Dict													=       nn.Parameter(torch.zeros(1				,							num_embeddings + additional_embeddings				,							__snake_case		)		)

											if added_emb_type == "prd":
																	lowercase_	:     Union[str, Any]													=       nn.Parameter(torch.zeros(1				,							1				,							__snake_case		)		)
											elif added_emb_type is None:
																	lowercase_	:     Optional[Any]													=       None
											else:
																	raise ValueError(
																	    F'''`added_emb_type`: {added_emb_type} is not supported. Make sure to choose one of `\'prd\'` or `None`.'''		)

											lowercase_	:     str													=       nn.ModuleList(
											    [
											        BasicTransformerBlock(
											            __snake_case				,							__snake_case				,							__snake_case				,							dropout=__snake_case				,							activation_fn='''gelu'''				,							attention_bias=__snake_case				,							)
											        for d in range(__snake_case		)
											    ]		)

											if norm_in_type == "layer":
																	lowercase_	:     Dict													=       nn.LayerNorm(__snake_case		)
											elif norm_in_type is None:
																	lowercase_	:     int													=       None
											else:
																	raise ValueError(F'''Unsupported norm_in_type: {norm_in_type}.'''		)

											lowercase_	:     int													=       nn.LayerNorm(__snake_case		)

											lowercase_	:     List[str]													=       nn.Linear(__snake_case				,							__snake_case		)

											lowercase_	:     List[str]													=       torch.full(
											    [num_embeddings + additional_embeddings, num_embeddings + additional_embeddings]				,							-1_00_00.0		)
											causal_attention_mask.triu_(1		)
											lowercase_	:     int													=       causal_attention_mask[None, ...]
											self.register_buffer('''causal_attention_mask'''				,							__snake_case				,							persistent=__snake_case		)

											lowercase_	:     Dict													=       nn.Parameter(torch.zeros(1				,							__snake_case		)		)
											lowercase_	:     Dict													=       nn.Parameter(torch.zeros(1				,							__snake_case		)		)






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


											"""simple docstring"""





											lowercase_	:     Optional[Any]													=       {}

											def fn_recursive_add_processors(__SCREAMING_SNAKE_CASE				,							__SCREAMING_SNAKE_CASE				,							__SCREAMING_SNAKE_CASE		):
																	if hasattr(__snake_case				,							'''set_processor'''		):
																							lowercase_	:     Any													=       module.processor

																	for sub_name, child in module.named_children():
																							fn_recursive_add_processors(F'''{name}.{sub_name}'''				,							__snake_case				,							__snake_case		)

																	return processors

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

											return processors






					def 	_snake_case    (   self				,							__SCREAMING_SNAKE_CASE		):


											"""simple docstring"""





											lowercase_	:     Tuple													=       len(self.attn_processors.keys()		)

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

											def fn_recursive_attn_processor(__SCREAMING_SNAKE_CASE				,							__SCREAMING_SNAKE_CASE				,							__SCREAMING_SNAKE_CASE		):
																	if hasattr(__snake_case				,							'''set_processor'''		):
																							if not isinstance(__snake_case				,							__snake_case		):
																													module.set_processor(__snake_case		)
																							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}'''				,							__snake_case				,							__snake_case		)

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






					def 	_snake_case    (   self		):


											"""simple docstring"""





											self.set_attn_processor(AttnProcessor()		)






					def 	_snake_case    (   self				,							__SCREAMING_SNAKE_CASE				,							__SCREAMING_SNAKE_CASE				,							__SCREAMING_SNAKE_CASE				,							__SCREAMING_SNAKE_CASE = None				,							__SCREAMING_SNAKE_CASE = None				,							__SCREAMING_SNAKE_CASE = True				,							):


											"""simple docstring"""





											lowercase_	:     str													=       hidden_states.shape[0]

											lowercase_	:     Optional[int]													=       timestep
											if not torch.is_tensor(__snake_case		):
																	lowercase_	:     int													=       torch.tensor([timesteps]				,							dtype=torch.long				,							device=hidden_states.device		)
											elif torch.is_tensor(__snake_case		) and len(timesteps.shape		) == 0:
																	lowercase_	:     List[str]													=       timesteps[None].to(hidden_states.device		)

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

											lowercase_	:     List[str]													=       self.time_proj(__snake_case		)

											# timesteps does not contain any weights and will always return f32 tensors
											# but time_embedding might be fp16, so we need to cast here.
											lowercase_	:     Any													=       timesteps_projected.to(dtype=self.dtype		)
											lowercase_	:     Optional[Any]													=       self.time_embedding(__snake_case		)

											if self.embedding_proj_norm is not None:
																	lowercase_	:     Union[str, Any]													=       self.embedding_proj_norm(__snake_case		)

											lowercase_	:     str													=       self.embedding_proj(__snake_case		)
											if self.encoder_hidden_states_proj is not None and encoder_hidden_states is not None:
																	lowercase_	:     Dict													=       self.encoder_hidden_states_proj(__snake_case		)
											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'''		)

											lowercase_	:     int													=       self.proj_in(__snake_case		)

											lowercase_	:     Any													=       self.positional_embedding.to(hidden_states.dtype		)

											lowercase_	:     Dict													=       []
											lowercase_	:     int													=       0

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

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

											if len(hidden_states.shape		) == 2:
																	lowercase_	:     Union[str, Any]													=       hidden_states[:, None, :]

											lowercase_	:     Any													=       additional_embeds + [
											    proj_embeddings,
											    time_embeddings[:, None, :],
											    hidden_states,
											]

											if self.prd_embedding is not None:
																	lowercase_	:     List[Any]													=       self.prd_embedding.to(hidden_states.dtype		).expand(__snake_case				,							-1				,							-1		)
																	additional_embeds.append(__snake_case		)

											lowercase_	:     Any													=       torch.cat(
											    __snake_case				,							dim=1				,							)

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

											lowercase_	:     int													=       hidden_states + positional_embeddings

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

											if self.norm_in is not None:
																	lowercase_	:     Any													=       self.norm_in(__snake_case		)

											for block in self.transformer_blocks:
																	lowercase_	:     Optional[Any]													=       block(__snake_case				,							attention_mask=__snake_case		)

											lowercase_	:     str													=       self.norm_out(__snake_case		)

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

											lowercase_	:     Optional[Any]													=       self.proj_to_clip_embeddings(__snake_case		)

											if not return_dict:
																	return (predicted_image_embedding,)

											return PriorTransformerOutput(predicted_image_embedding=__snake_case		)






					def 	_snake_case    (   self				,							__SCREAMING_SNAKE_CASE		):


											"""simple docstring"""





											lowercase_	:     Optional[int]													=       (prior_latents * self.clip_std) + self.clip_mean
											return prior_latents







from abc import ABC, abstractmethod
from argparse import ArgumentParser







class        snake_case_   (lowerCamelCase_      ):
					@staticmethod
					@abstractmethod
					def  lowerCamelCase__(      __snake_case   :ArgumentParser      )					->    Dict:
												raise NotImplementedError()



					@abstractmethod
					def  lowerCamelCase__(      self   :Union[str, Any]      )					->    Dict:
												raise NotImplementedError()




