
'''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_     :					List[str]													=	num_attention_heads
											lowercase_     :					int													=	attention_head_dim
											lowercase_     :					List[str]													=	num_attention_heads * attention_head_dim
											lowercase_     :					List[str]													=	additional_embeddings

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

											lowercase_     :					Optional[int]													=	Timesteps(__SCREAMING_SNAKE_CASE    ,							__SCREAMING_SNAKE_CASE    ,							0		)
											lowercase_     :					Optional[Any]													=	TimestepEmbedding(__SCREAMING_SNAKE_CASE    ,							__SCREAMING_SNAKE_CASE    ,							out_dim=__SCREAMING_SNAKE_CASE    ,							act_fn=__SCREAMING_SNAKE_CASE		)

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

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

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

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

											lowercase_     :					Union[str, Any]													=	nn.Parameter(torch.zeros(1    ,							num_embeddings + additional_embeddings    ,							__SCREAMING_SNAKE_CASE		)		)

											if added_emb_type == "prd":
																	lowercase_     :					str													=	nn.Parameter(torch.zeros(1    ,							1    ,							__SCREAMING_SNAKE_CASE		)		)
											elif added_emb_type is None:
																	lowercase_     :					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_     :					int													=	nn.ModuleList(
											    [
											        BasicTransformerBlock(
											            __SCREAMING_SNAKE_CASE    ,							__SCREAMING_SNAKE_CASE    ,							__SCREAMING_SNAKE_CASE    ,							dropout=__SCREAMING_SNAKE_CASE    ,							activation_fn='''gelu'''    ,							attention_bias=__SCREAMING_SNAKE_CASE    ,							)
											        for d in range(__SCREAMING_SNAKE_CASE		)
											    ]		)

											if norm_in_type == "layer":
																	lowercase_     :					Union[str, Any]													=	nn.LayerNorm(__SCREAMING_SNAKE_CASE		)
											elif norm_in_type is None:
																	lowercase_     :					int													=	None
											else:
																	raise ValueError(F'''Unsupported norm_in_type: {norm_in_type}.'''		)

											lowercase_     :					Union[str, Any]													=	nn.LayerNorm(__SCREAMING_SNAKE_CASE		)

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

											lowercase_     :					Dict													=	torch.full(
											    [num_embeddings + additional_embeddings, num_embeddings + additional_embeddings]    ,							-10_000.0		)
											causal_attention_mask.triu_(1		)
											lowercase_     :					Optional[Any]													=	causal_attention_mask[None, ...]
											self.register_buffer('''causal_attention_mask'''    ,							__SCREAMING_SNAKE_CASE    ,							persistent=__SCREAMING_SNAKE_CASE		)

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






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


											"""simple docstring"""





											lowercase_     :					int													=	{}

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

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

																	return processors

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

											return processors






					def      _snake_case   (       self    ,							__SCREAMING_SNAKE_CASE		):


											"""simple docstring"""





											lowercase_     :					List[str]													=	len(self.attn_processors.keys()		)

											if isinstance(__SCREAMING_SNAKE_CASE    ,							__SCREAMING_SNAKE_CASE		) and len(__SCREAMING_SNAKE_CASE		) != count:
																	raise ValueError(
																	    F'''A dict of processors was passed, but the number of processors {len(__SCREAMING_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(__SCREAMING_SNAKE_CASE    ,							'''set_processor'''		):
																							if not isinstance(__SCREAMING_SNAKE_CASE    ,							__SCREAMING_SNAKE_CASE		):
																													module.set_processor(__SCREAMING_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}'''    ,							__SCREAMING_SNAKE_CASE    ,							__SCREAMING_SNAKE_CASE		)

											for name, module in self.named_children():
																	fn_recursive_attn_processor(__SCREAMING_SNAKE_CASE    ,							__SCREAMING_SNAKE_CASE    ,							__SCREAMING_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_     :					Optional[int]													=	hidden_states.shape[0]

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

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

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

											if self.embedding_proj_norm is not None:
																	lowercase_     :					Any													=	self.embedding_proj_norm(__SCREAMING_SNAKE_CASE		)

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

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

											lowercase_     :					Union[str, Any]													=	[]
											lowercase_     :					Any													=	0

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

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

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

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

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

											lowercase_     :					Union[str, Any]													=	torch.cat(
											    __SCREAMING_SNAKE_CASE    ,							dim=1    ,							)

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

											if attention_mask is not None:
																	lowercase_     :					str													=	(1 - attention_mask.to(hidden_states.dtype		)) * -10_000.0
																	lowercase_     :					int													=	F.pad(__SCREAMING_SNAKE_CASE    ,							(0, self.additional_embeddings)    ,							value=0.0		)
																	lowercase_     :					Dict													=	(attention_mask[:, None, :] + self.causal_attention_mask).to(hidden_states.dtype		)
																	lowercase_     :					str													=	attention_mask.repeat_interleave(self.config.num_attention_heads    ,							dim=0		)

											if self.norm_in is not None:
																	lowercase_     :					Optional[int]													=	self.norm_in(__SCREAMING_SNAKE_CASE		)

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

											lowercase_     :					Tuple													=	self.norm_out(__SCREAMING_SNAKE_CASE		)

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

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

											if not return_dict:
																	return (predicted_image_embedding,)

											return PriorTransformerOutput(predicted_image_embedding=__SCREAMING_SNAKE_CASE		)






					def      _snake_case   (       self    ,							__SCREAMING_SNAKE_CASE		):


											"""simple docstring"""





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





'''simple docstring'''







from __future__ import annotations

from typing import Any






class 			lowerCAmelCase__       :






					def __init__(       self    ,							__SCREAMING_SNAKE_CASE		):


											"""simple docstring"""





											lowercase_     :					str													=	num_of_nodes
											lowercase_     :					list[list[int]]													=	[]
											lowercase_     :					dict[int, int]													=	{}






					def      _snake_case   (       self    ,							__SCREAMING_SNAKE_CASE    ,							__SCREAMING_SNAKE_CASE    ,							__SCREAMING_SNAKE_CASE		):


											"""simple docstring"""





											self.m_edges.append([u_node, v_node, weight]		)






					def      _snake_case   (       self    ,							__SCREAMING_SNAKE_CASE		):


											"""simple docstring"""





											if self.m_component[u_node] == u_node:
																	return u_node
											return self.find_component(self.m_component[u_node]		)






					def      _snake_case   (       self    ,							__SCREAMING_SNAKE_CASE		):


											"""simple docstring"""





											if self.m_component[u_node] != u_node:
																	for k in self.m_component:
																							lowercase_     :					Optional[int]													=	self.find_component(__SCREAMING_SNAKE_CASE		)






					def      _snake_case   (       self    ,							__SCREAMING_SNAKE_CASE    ,							__SCREAMING_SNAKE_CASE    ,							__SCREAMING_SNAKE_CASE		):


											"""simple docstring"""





											if component_size[u_node] <= component_size[v_node]:
																	lowercase_     :					Any													=	v_node
																	component_size[v_node] += component_size[u_node]
																	self.set_component(__SCREAMING_SNAKE_CASE		)

											elif component_size[u_node] >= component_size[v_node]:
																	lowercase_     :					int													=	self.find_component(__SCREAMING_SNAKE_CASE		)
																	component_size[u_node] += component_size[v_node]
																	self.set_component(__SCREAMING_SNAKE_CASE		)






					def      _snake_case   (       self		):


											"""simple docstring"""





											lowercase_     :					Dict													=	[]
											lowercase_     :					Optional[Any]													=	0

											lowercase_     :					list[Any]													=	[-1] * self.m_num_of_nodes

											# A list of components (initialized to all of the nodes)
											for node in range(self.m_num_of_nodes		):
																	self.m_component.update({node: node}		)
																	component_size.append(1		)

											lowercase_     :					Union[str, Any]													=	self.m_num_of_nodes

											while num_of_components > 1:
																	for edge in self.m_edges:
																							lowercase_						,			lowercase_						,			lowercase_     :					List[Any]													=	edge

																							lowercase_     :					Dict													=	self.m_component[u]
																							lowercase_     :					Any													=	self.m_component[v]

																							if u_component != v_component:

																													for component in (u_component, v_component):
																																			if (
																																			    minimum_weight_edge[component] == -1
																																			    or minimum_weight_edge[component][2] > w
																																			):
																																									lowercase_     :					Union[str, Any]													=	[u, v, w]

																	for edge in minimum_weight_edge:
																							if isinstance(__SCREAMING_SNAKE_CASE    ,							__SCREAMING_SNAKE_CASE		):
																													lowercase_						,			lowercase_						,			lowercase_     :					str													=	edge

																													lowercase_     :					Tuple													=	self.m_component[u]
																													lowercase_     :					Union[str, Any]													=	self.m_component[v]

																													if u_component != v_component:
																																			mst_weight += w
																																			self.union(__SCREAMING_SNAKE_CASE    ,							__SCREAMING_SNAKE_CASE    ,							__SCREAMING_SNAKE_CASE		)
																																			print(F'''Added edge [{u} - {v}]\nAdded weight: {w}\n'''		)
																																			num_of_components -= 1

																	lowercase_     :					str													=	[-1] * self.m_num_of_nodes
											print(F'''The total weight of the minimal spanning tree is: {mst_weight}'''		)







def  snake_case_		(    ):



						"""simple docstring"""







if __name__ == "__main__":
							import doctest

							doctest.testmod()



