
'''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 (				__UpperCAmelCase			):
		a							:					torch.FloatTensor


class 			lowerCAmelCase (				__UpperCAmelCase		,     __UpperCAmelCase			):




		@register_to_config
		def __init__(				self					,						UpperCamelCase = 32					,						UpperCamelCase = 64					,						UpperCamelCase = 20					,						UpperCamelCase = 768					,						UpperCamelCase=77					,						UpperCamelCase=4					,						UpperCamelCase = 0.0					,						UpperCamelCase = "silu"					,						UpperCamelCase = None					,						UpperCamelCase = None					,						UpperCamelCase = "linear"					,						UpperCamelCase = "prd"					,						UpperCamelCase = None					,						UpperCamelCase = None					,						UpperCamelCase = 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(UpperCamelCase					,						UpperCamelCase					,						0      )
								_SCREAMING_SNAKE_CASE				= TimestepEmbedding(UpperCamelCase					,						UpperCamelCase					,						out_dim=UpperCamelCase					,						act_fn=UpperCamelCase      )

								_SCREAMING_SNAKE_CASE				= nn.Linear(UpperCamelCase					,						UpperCamelCase      )

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

								_SCREAMING_SNAKE_CASE				= nn.Linear(UpperCamelCase					,						UpperCamelCase      )

								if encoder_hid_proj_type is None:
														_SCREAMING_SNAKE_CASE				= None
								elif encoder_hid_proj_type == "linear":
														_SCREAMING_SNAKE_CASE				= nn.Linear(UpperCamelCase					,						UpperCamelCase      )
								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					,						UpperCamelCase      )      )

								if added_emb_type == "prd":
														_SCREAMING_SNAKE_CASE				= nn.Parameter(torch.zeros(1					,						1					,						UpperCamelCase      )      )
								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(
								            UpperCamelCase					,						UpperCamelCase					,						UpperCamelCase					,						dropout=UpperCamelCase					,						activation_fn="gelu"					,						attention_bias=UpperCamelCase					,						)
								        for d in range(UpperCamelCase      )
								    ]      )

								if norm_in_type == "layer":
														_SCREAMING_SNAKE_CASE				= nn.LayerNorm(UpperCamelCase      )
								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(UpperCamelCase      )

								_SCREAMING_SNAKE_CASE				= nn.Linear(UpperCamelCase					,						UpperCamelCase      )

								_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"					,						UpperCamelCase					,						persistent=UpperCamelCase      )

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




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

								def fn_recursive_add_processors(UpperCamelCase					,						UpperCamelCase					,						UpperCamelCase      ):
														if hasattr(UpperCamelCase					,						"set_processor"      ):
																				_SCREAMING_SNAKE_CASE				= 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     lowercase       (				self					,						UpperCamelCase      ):
								_SCREAMING_SNAKE_CASE				= 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					,						UpperCamelCase					,						UpperCamelCase      ):
														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     lowercase       (				self      ):
								self.set_attn_processor(AttnProcessor()      )




		def     lowercase       (				self					,						UpperCamelCase					,						UpperCamelCase					,						UpperCamelCase					,						UpperCamelCase = None					,						UpperCamelCase = None					,						UpperCamelCase = True					,						):
								_SCREAMING_SNAKE_CASE				= hidden_states.shape[0]

								_SCREAMING_SNAKE_CASE				= timestep
								if not torch.is_tensor(UpperCamelCase      ):
														_SCREAMING_SNAKE_CASE				= torch.tensor([timesteps]					,						dtype=torch.long					,						device=hidden_states.device      )
								elif torch.is_tensor(UpperCamelCase      ) 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(UpperCamelCase					,						dtype=timesteps.dtype					,						device=timesteps.device      )

								_SCREAMING_SNAKE_CASE				= 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				= timesteps_projected.to(dtype=self.dtype      )
								_SCREAMING_SNAKE_CASE				= self.time_embedding(UpperCamelCase      )

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

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

								_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(UpperCamelCase      )
														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(UpperCamelCase					,						-1					,						-1      )
														additional_embeds.append(UpperCamelCase      )

								_SCREAMING_SNAKE_CASE				= 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				= additional_embeddings_len + proj_embeddings.shape[1] + 1
								if positional_embeddings.shape[1] < hidden_states.shape[1]:
														_SCREAMING_SNAKE_CASE				= 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				= 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(UpperCamelCase					,						(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(UpperCamelCase      )

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

								_SCREAMING_SNAKE_CASE				= self.norm_out(UpperCamelCase      )

								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(UpperCamelCase      )

								if not return_dict:
														return (predicted_image_embedding,)

								return PriorTransformerOutput(predicted_image_embedding=UpperCamelCase      )




		def     lowercase       (				self					,						UpperCamelCase      ):
								_SCREAMING_SNAKE_CASE				= (prior_latents * self.clip_std) + self.clip_mean
								return prior_latents

'''simple docstring'''







# tests directory-specific settings - this file is run automatically
# by pytest before any tests are run

import sys
import warnings
from os.path import abspath, dirname, join


# allow having multiple repository checkouts and not needing to remember to rerun
# 'pip install -e .[dev]' when switching between checkouts and running tests.
_snake_case				:   Optional[Any]     =				abspath(join(dirname(dirname(dirname(__file__))), """src"""))
sys.path.insert(1, git_repo_path)


# silence FutureWarning warnings in tests since often we can't act on them until
# they become normal warnings - i.e. the tests still need to test the current functionality
warnings.simplefilter(action="""ignore""", category=FutureWarning)



def 			_a		(	_SCREAMING_SNAKE_CASE		:   Tuple  ):
						from transformers.testing_utils import pytest_addoption_shared

						pytest_addoption_shared(_SCREAMING_SNAKE_CASE  )




def 			_a		(	_SCREAMING_SNAKE_CASE		:   Union[str, Any]  ):
						from transformers.testing_utils import pytest_terminal_summary_main

						_SCREAMING_SNAKE_CASE				= terminalreporter.config.getoption("--make-reports"  )
						if make_reports:
												pytest_terminal_summary_main(_SCREAMING_SNAKE_CASE	,			id=_SCREAMING_SNAKE_CASE  )