

"""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 					a						(       _lowerCamelCase				):



				"""simple docstring"""



				UpperCAmelCase						 =					4_2



class 					a						(       _lowerCamelCase,	_lowerCamelCase				):



				"""simple docstring"""



				@register_to_config
				def __init__(     self: int    ,						UpperCamelCase: int = 32    ,						UpperCamelCase: int = 64    ,						UpperCamelCase: int = 20    ,						UpperCamelCase: int = 7_68    ,						UpperCamelCase: List[str]=77    ,						UpperCamelCase: str=4    ,						UpperCamelCase: float = 0.0    ,						UpperCamelCase: str = "silu"    ,						UpperCamelCase: Optional[str] = None    ,						UpperCamelCase: Optional[str] = None    ,						UpperCamelCase: Optional[str] = "linear"    ,						UpperCamelCase: Optional[str] = "prd"    ,						UpperCamelCase: Optional[int] = None    ,						UpperCamelCase: Optional[int] = None    ,						UpperCamelCase: Optional[int] = None    ,						):






									"""simple docstring"""


									super().__init__()
									A__										=  num_attention_heads
									A__										=  attention_head_dim
									A__										=  num_attention_heads * attention_head_dim
									A__										=  additional_embeddings

									A__										=  time_embed_dim or inner_dim
									A__										=  embedding_proj_dim or embedding_dim
									A__										=  clip_embed_dim or embedding_dim

									A__										=  Timesteps(UpperCamelCase    ,						UpperCamelCase    ,						0       )
									A__										=  TimestepEmbedding(UpperCamelCase    ,						UpperCamelCase    ,						out_dim=UpperCamelCase    ,						act_fn=UpperCamelCase       )

									A__										=  nn.Linear(UpperCamelCase    ,						UpperCamelCase       )

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

									A__										=  nn.Linear(UpperCamelCase    ,						UpperCamelCase       )

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

									A__										=  nn.Parameter(torch.zeros(1    ,						num_embeddings + additional_embeddings    ,						UpperCamelCase       )       )

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

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

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

									A__										=  nn.LayerNorm(UpperCamelCase       )

									A__										=  nn.Linear(UpperCamelCase    ,						UpperCamelCase       )

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

									A__										=  nn.Parameter(torch.zeros(1    ,						UpperCamelCase       )       )
									A__										=  nn.Parameter(torch.zeros(1    ,						UpperCamelCase       )       )

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






									"""simple docstring"""


									A__										=  {}

									def fn_recursive_add_processors(UpperCamelCase: str    ,						UpperCamelCase: torch.nn.Module    ,						UpperCamelCase: Dict[str, AttentionProcessor]       ):
														if hasattr(UpperCamelCase    ,						"""set_processor"""       ):
																			A__										=  module.processor

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

														return processors

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

									return processors

				def 				UpperCamelCase	(     self: Dict    ,						UpperCamelCase: Union[AttentionProcessor, Dict[str, AttentionProcessor]]       ):






									"""simple docstring"""


									A__										=  len(self.attn_processors.keys()       )

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

									def fn_recursive_attn_processor(UpperCamelCase: str    ,						UpperCamelCase: torch.nn.Module    ,						UpperCamelCase: List[Any]       ):
														if hasattr(UpperCamelCase    ,						"""set_processor"""       ):
																			if not isinstance(UpperCamelCase    ,						UpperCamelCase       ):
																								module.set_processor(UpperCamelCase       )
																			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}"""    ,						UpperCamelCase    ,						UpperCamelCase       )

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

				def 				UpperCamelCase	(     self: int       ):






									"""simple docstring"""


									self.set_attn_processor(AttnProcessor()       )

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






									"""simple docstring"""


									A__										=  hidden_states.shape[0]

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

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

									A__										=  self.time_proj(UpperCamelCase       )

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

									if self.embedding_proj_norm is not None:
														A__										=  self.embedding_proj_norm(UpperCamelCase       )

									A__										=  self.embedding_proj(UpperCamelCase       )
									if self.encoder_hidden_states_proj is not None and encoder_hidden_states is not None:
														A__										=  self.encoder_hidden_states_proj(UpperCamelCase       )
									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"""       )

									A__										=  self.proj_in(UpperCamelCase       )

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

									A__										=  []
									A__										=  0

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

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

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

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

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

									A__										=  torch.cat(
									    UpperCamelCase    ,						dim=1    ,						)

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

									A__										=  hidden_states + positional_embeddings

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

									if self.norm_in is not None:
														A__										=  self.norm_in(UpperCamelCase       )

									for block in self.transformer_blocks:
														A__										=  block(UpperCamelCase    ,						attention_mask=UpperCamelCase       )

									A__										=  self.norm_out(UpperCamelCase       )

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

									A__										=  self.proj_to_clip_embeddings(UpperCamelCase       )

									if not return_dict:
														return (predicted_image_embedding,)

									return PriorTransformerOutput(predicted_image_embedding=UpperCamelCase       )





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






									"""simple docstring"""


									A__										=  (prior_latents * self.clip_std) + self.clip_mean
									return prior_latents









"""simple docstring"""



import baseaa





def  _snake_case     (    UpperCAmelCase_  :					str			):
     return baseaa.aaaencode(string.encode("""utf-8"""			)			)





def  _snake_case     (    UpperCAmelCase_  :					bytes			):
     return baseaa.aaadecode(UpperCAmelCase_			).decode("""utf-8"""			)


if __name__ == "__main__":
 import doctest

 doctest.testmod()






