'''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(							_SCREAMING_SNAKE_CASE					):
						A_			:							torch.FloatTensor




class _SCREAMING_SNAKE_CASE(							_SCREAMING_SNAKE_CASE						,						_SCREAMING_SNAKE_CASE					):




						@register_to_config
						def __init__(    self :       List[Any]							,							UpperCamelCase_ :       int = 32							,							UpperCamelCase_ :       int = 64							,							UpperCamelCase_ :       int = 20							,							UpperCamelCase_ :       int = 7_68							,							UpperCamelCase_ :       Union[str, Any]=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							,							)     ->				Tuple:
													super().__init__()
													SCREAMING_SNAKE_CASE__     :Dict						    = num_attention_heads
													SCREAMING_SNAKE_CASE__     :List[Any]						    = attention_head_dim
													SCREAMING_SNAKE_CASE__     :Optional[Any]						    = num_attention_heads * attention_head_dim
													SCREAMING_SNAKE_CASE__     :Tuple						    = additional_embeddings

													SCREAMING_SNAKE_CASE__     :Any						    = time_embed_dim or inner_dim
													SCREAMING_SNAKE_CASE__     :str						    = embedding_proj_dim or embedding_dim
													SCREAMING_SNAKE_CASE__     :int						    = clip_embed_dim or embedding_dim

													SCREAMING_SNAKE_CASE__     :Optional[Any]						    = Timesteps(UpperCamelCase_							,							UpperCamelCase_							,							0      )
													SCREAMING_SNAKE_CASE__     :Optional[Any]						    = TimestepEmbedding(UpperCamelCase_							,							UpperCamelCase_							,							out_dim=UpperCamelCase_							,							act_fn=UpperCamelCase_      )

													SCREAMING_SNAKE_CASE__     :List[Any]						    = nn.Linear(UpperCamelCase_							,							UpperCamelCase_      )

													if embedding_proj_norm_type is None:
																				SCREAMING_SNAKE_CASE__     :Dict						    = None
													elif embedding_proj_norm_type == "layer":
																				SCREAMING_SNAKE_CASE__     :int						    = nn.LayerNorm(UpperCamelCase_      )
													else:
																				raise ValueError(f'''unsupported embedding_proj_norm_type: {embedding_proj_norm_type}'''      )

													SCREAMING_SNAKE_CASE__     :Dict						    = nn.Linear(UpperCamelCase_							,							UpperCamelCase_      )

													if encoder_hid_proj_type is None:
																				SCREAMING_SNAKE_CASE__     :List[Any]						    = None
													elif encoder_hid_proj_type == "linear":
																				SCREAMING_SNAKE_CASE__     :str						    = nn.Linear(UpperCamelCase_							,							UpperCamelCase_      )
													else:
																				raise ValueError(f'''unsupported encoder_hid_proj_type: {encoder_hid_proj_type}'''      )

													SCREAMING_SNAKE_CASE__     :Any						    = nn.Parameter(torch.zeros(1							,							num_embeddings + additional_embeddings							,							UpperCamelCase_      )      )

													if added_emb_type == "prd":
																				SCREAMING_SNAKE_CASE__     :List[str]						    = nn.Parameter(torch.zeros(1							,							1							,							UpperCamelCase_      )      )
													elif added_emb_type is None:
																				SCREAMING_SNAKE_CASE__     :Dict						    = 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__     :Union[str, Any]						    = nn.ModuleList(
													    [
													        BasicTransformerBlock(
													            UpperCamelCase_							,							UpperCamelCase_							,							UpperCamelCase_							,							dropout=UpperCamelCase_							,							activation_fn='gelu'							,							attention_bias=UpperCamelCase_							,							)
													        for d in range(UpperCamelCase_      )
													    ]      )

													if norm_in_type == "layer":
																				SCREAMING_SNAKE_CASE__     :Optional[Any]						    = nn.LayerNorm(UpperCamelCase_      )
													elif norm_in_type is None:
																				SCREAMING_SNAKE_CASE__     :List[str]						    = None
													else:
																				raise ValueError(f'''Unsupported norm_in_type: {norm_in_type}.'''      )

													SCREAMING_SNAKE_CASE__     :str						    = nn.LayerNorm(UpperCamelCase_      )

													SCREAMING_SNAKE_CASE__     :Union[str, Any]						    = nn.Linear(UpperCamelCase_							,							UpperCamelCase_      )

													SCREAMING_SNAKE_CASE__     :str						    = torch.full(
													    [num_embeddings + additional_embeddings, num_embeddings + additional_embeddings]							,							-1_0000.0      )
													causal_attention_mask.triu_(1      )
													SCREAMING_SNAKE_CASE__     :Optional[int]						    = causal_attention_mask[None, ...]
													self.register_buffer('causal_attention_mask'							,							UpperCamelCase_							,							persistent=UpperCamelCase_      )

													SCREAMING_SNAKE_CASE__     :Any						    = nn.Parameter(torch.zeros(1							,							UpperCamelCase_      )      )
													SCREAMING_SNAKE_CASE__     :List[str]						    = nn.Parameter(torch.zeros(1							,							UpperCamelCase_      )      )




						@property
						# Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.attn_processors
						def      __lowerCamelCase       (    self :       List[Any]      )     ->				Dict[str, AttentionProcessor]:
													SCREAMING_SNAKE_CASE__     :str						    = {}

													def fn_recursive_add_processors(UpperCamelCase_ :       str							,							UpperCamelCase_ :       torch.nn.Module							,							UpperCamelCase_ :       Dict[str, AttentionProcessor]      ):
																				if hasattr(UpperCamelCase_							,							'set_processor'      ):
																											SCREAMING_SNAKE_CASE__     :Tuple						    = 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      __lowerCamelCase       (    self :       List[str]							,							UpperCamelCase_ :       Union[AttentionProcessor, Dict[str, AttentionProcessor]]      )     ->				Optional[Any]:
													SCREAMING_SNAKE_CASE__     :int						    = 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_ :       Dict      ):
																				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      __lowerCamelCase       (    self :       Any      )     ->				str:
													self.set_attn_processor(AttnProcessor()      )




						def      __lowerCamelCase       (    self :       Dict							,							UpperCamelCase_ :       Tuple							,							UpperCamelCase_ :       Union[torch.Tensor, float, int]							,							UpperCamelCase_ :       torch.FloatTensor							,							UpperCamelCase_ :       Optional[torch.FloatTensor] = None							,							UpperCamelCase_ :       Optional[torch.BoolTensor] = None							,							UpperCamelCase_ :       bool = True							,							)     ->				List[Any]:
													SCREAMING_SNAKE_CASE__     :Optional[Any]						    = hidden_states.shape[0]

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

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

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

													if self.embedding_proj_norm is not None:
																				SCREAMING_SNAKE_CASE__     :Tuple						    = self.embedding_proj_norm(UpperCamelCase_      )

													SCREAMING_SNAKE_CASE__     :str						    = self.embedding_proj(UpperCamelCase_      )
													if self.encoder_hidden_states_proj is not None and encoder_hidden_states is not None:
																				SCREAMING_SNAKE_CASE__     :List[str]						    = 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'      )

													SCREAMING_SNAKE_CASE__     :List[str]						    = self.proj_in(UpperCamelCase_      )

													SCREAMING_SNAKE_CASE__     :Union[str, Any]						    = self.positional_embedding.to(hidden_states.dtype      )

													SCREAMING_SNAKE_CASE__     :List[Any]						    = []
													SCREAMING_SNAKE_CASE__     :Optional[Any]						    = 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:
																				SCREAMING_SNAKE_CASE__     :Optional[int]						    = proj_embeddings[:, None, :]

													if len(hidden_states.shape      ) == 2:
																				SCREAMING_SNAKE_CASE__     :List[str]						    = hidden_states[:, None, :]

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

													if self.prd_embedding is not None:
																				SCREAMING_SNAKE_CASE__     :Optional[int]						    = self.prd_embedding.to(hidden_states.dtype      ).expand(UpperCamelCase_							,							-1							,							-1      )
																				additional_embeds.append(UpperCamelCase_      )

													SCREAMING_SNAKE_CASE__     :Union[str, Any]						    = torch.cat(
													    UpperCamelCase_							,							dim=1							,							)

													# Allow positional_embedding to not include the `addtional_embeddings` and instead pad it with zeros for these additional tokens
													SCREAMING_SNAKE_CASE__     :List[str]						    = additional_embeddings_len + proj_embeddings.shape[1] + 1
													if positional_embeddings.shape[1] < hidden_states.shape[1]:
																				SCREAMING_SNAKE_CASE__     :List[Any]						    = 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							,							)

													SCREAMING_SNAKE_CASE__     :Tuple						    = hidden_states + positional_embeddings

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

													if self.norm_in is not None:
																				SCREAMING_SNAKE_CASE__     :List[Any]						    = self.norm_in(UpperCamelCase_      )

													for block in self.transformer_blocks:
																				SCREAMING_SNAKE_CASE__     :Union[str, Any]						    = block(UpperCamelCase_							,							attention_mask=UpperCamelCase_      )

													SCREAMING_SNAKE_CASE__     :int						    = self.norm_out(UpperCamelCase_      )

													if self.prd_embedding is not None:
																				SCREAMING_SNAKE_CASE__     :List[Any]						    = hidden_states[:, -1]
													else:
																				SCREAMING_SNAKE_CASE__     :int						    = hidden_states[:, additional_embeddings_len:]

													SCREAMING_SNAKE_CASE__     :List[Any]						    = self.proj_to_clip_embeddings(UpperCamelCase_      )

													if not return_dict:
																				return (predicted_image_embedding,)

													return PriorTransformerOutput(predicted_image_embedding=UpperCamelCase_      )




						def      __lowerCamelCase       (    self :       str							,							UpperCamelCase_ :       Dict      )     ->				Optional[int]:
													SCREAMING_SNAKE_CASE__     :Optional[Any]						    = (prior_latents * self.clip_std) + self.clip_mean
													return prior_latents







'''simple docstring'''







import os


# All paths are set with the intent you should run this script from the root of the repo with the command
# python utils/check_doctest_list.py
UpperCamelCase_      	=	'''.'''


if __name__ == "__main__":
		UpperCamelCase_      	=	os.path.join(REPO_PATH, '''utils/documentation_tests.txt''')
		UpperCamelCase_      	=	[]
		UpperCamelCase_      	=	[]
		with open(doctest_file_path) as fp:
				for line in fp:
						UpperCamelCase_      	=	line.strip()
						UpperCamelCase_      	=	os.path.join(REPO_PATH, line)
						if not (os.path.isfile(path) or os.path.isdir(path)):
								non_existent_paths.append(line)
						all_paths.append(path)
		if len(non_existent_paths) > 0:
				UpperCamelCase_      	=	'''\n'''.join(non_existent_paths)
				raise ValueError(f"`utils/documentation_tests.txt` contains non-existent paths:\n{non_existent_paths}")
		if all_paths != sorted(all_paths):
				raise ValueError('''Files in `utils/documentation_tests.txt` are not in alphabetical order.''')






