



from typing import Any, Dict, Optional

import torch
import torch.nn.functional as F
from torch import nn

from ..utils import maybe_allow_in_graph
from .activations import get_activation
from .attention_processor import Attention
from .embeddings import CombinedTimestepLabelEmbeddings






@maybe_allow_in_graph
class 						__a (     nn.Module				):



	def __init__(						self							:    List[str]				,	snake_case_							:    Dict				,	snake_case_							:    int				,	snake_case_							:    int				,	snake_case_							:    List[Any]=0.0				,	snake_case_							:    Any = None				,	snake_case_							:    Union[str, Any] = "geglu"				,	snake_case_							:    str = None				,	snake_case_							:    Optional[Any] = False				,	snake_case_							:    Optional[int] = False				,	snake_case_							:    Tuple = False				,	snake_case_							:    Optional[Any] = False				,	snake_case_							:    str = True				,	snake_case_							:    List[str] = "layer_norm"				,	snake_case_							:    List[str] = False				,	)->							int:
						super().__init__()
						__lowerCAmelCase	   =only_cross_attention

						__lowerCAmelCase	   =(num_embeds_ada_norm is not None) and norm_type == """ada_norm_zero"""
						__lowerCAmelCase	   =(num_embeds_ada_norm is not None) and norm_type == """ada_norm"""

						if norm_type in ("ada_norm", "ada_norm_zero") and num_embeds_ada_norm is None:
											raise ValueError(
											    F"""`norm_type` is set to {norm_type}, but `num_embeds_ada_norm` is not defined. Please make sure to"""
											    F""" define `num_embeds_ada_norm` if setting `norm_type` to {norm_type}.""")

						# Define 3 blocks. Each block has its own normalization layer.
						# 1. Self-Attn
						if self.use_ada_layer_norm:
											__lowerCAmelCase	   =AdaLayerNorm(snake_case_				,	snake_case_)
						elif self.use_ada_layer_norm_zero:
											__lowerCAmelCase	   =AdaLayerNormZero(snake_case_				,	snake_case_)
						else:
											__lowerCAmelCase	   =nn.LayerNorm(snake_case_				,	elementwise_affine=snake_case_)
						__lowerCAmelCase	   =Attention(
						    query_dim=snake_case_				,	heads=snake_case_				,	dim_head=snake_case_				,	dropout=snake_case_				,	bias=snake_case_				,	cross_attention_dim=cross_attention_dim if only_cross_attention else None				,	upcast_attention=snake_case_				,	)

						# 2. Cross-Attn
						if cross_attention_dim is not None or double_self_attention:
											# We currently only use AdaLayerNormZero for self attention where there will only be one attention block.
											# I.e. the number of returned modulation chunks from AdaLayerZero would not make sense if returned during
											# the second cross attention block.
											__lowerCAmelCase	   =(
											    AdaLayerNorm(snake_case_				,	snake_case_)
											    if self.use_ada_layer_norm
											    else nn.LayerNorm(snake_case_				,	elementwise_affine=snake_case_)
											)
											__lowerCAmelCase	   =Attention(
											    query_dim=snake_case_				,	cross_attention_dim=cross_attention_dim if not double_self_attention else None				,	heads=snake_case_				,	dim_head=snake_case_				,	dropout=snake_case_				,	bias=snake_case_				,	upcast_attention=snake_case_				,	)  # is self-attn if encoder_hidden_states is none
						else:
											__lowerCAmelCase	   =None
											__lowerCAmelCase	   =None

						# 3. Feed-forward
						__lowerCAmelCase	   =nn.LayerNorm(snake_case_				,	elementwise_affine=snake_case_)
						__lowerCAmelCase	   =FeedForward(snake_case_				,	dropout=snake_case_				,	activation_fn=snake_case_				,	final_dropout=snake_case_)

						# let chunk size default to None
						__lowerCAmelCase	   =None
						__lowerCAmelCase	   =0



	def 		UpperCamelCase							(						self							:    Union[str, Any]				,	snake_case_							:    str				,	snake_case_							:    str)->							Tuple:
						# Sets chunk feed-forward
						__lowerCAmelCase	   =chunk_size
						__lowerCAmelCase	   =dim



	def 		UpperCamelCase							(						self							:    Tuple				,	snake_case_							:    int				,	snake_case_							:    Any = None				,	snake_case_							:    Optional[int] = None				,	snake_case_							:    List[str] = None				,	snake_case_							:    List[Any] = None				,	snake_case_							:    List[str] = None				,	snake_case_							:    str = None				,	)->							Any:
						# Notice that normalization is always applied before the real computation in the following blocks.
						# 1. Self-Attention
						if self.use_ada_layer_norm:
											__lowerCAmelCase	   =self.norma(snake_case_				,	snake_case_)
						elif self.use_ada_layer_norm_zero:
											__lowerCAmelCase   ,	__lowerCAmelCase   ,	__lowerCAmelCase   ,	__lowerCAmelCase   ,	__lowerCAmelCase	   =self.norma(
											    snake_case_				,	snake_case_				,	snake_case_				,	hidden_dtype=hidden_states.dtype)
						else:
											__lowerCAmelCase	   =self.norma(snake_case_)

						__lowerCAmelCase	   =cross_attention_kwargs if cross_attention_kwargs is not None else {}

						__lowerCAmelCase	   =self.attna(
						    snake_case_				,	encoder_hidden_states=encoder_hidden_states if self.only_cross_attention else None				,	attention_mask=snake_case_				,	**snake_case_				,	)
						if self.use_ada_layer_norm_zero:
											__lowerCAmelCase	   =gate_msa.unsqueeze(1) * attn_output
						__lowerCAmelCase	   =attn_output + hidden_states

						# 2. Cross-Attention
						if self.attna is not None:
											__lowerCAmelCase	   =(
											    self.norma(snake_case_				,	snake_case_) if self.use_ada_layer_norm else self.norma(snake_case_)
											)

											__lowerCAmelCase	   =self.attna(
											    snake_case_				,	encoder_hidden_states=snake_case_				,	attention_mask=snake_case_				,	**snake_case_				,	)
											__lowerCAmelCase	   =attn_output + hidden_states

						# 3. Feed-forward
						__lowerCAmelCase	   =self.norma(snake_case_)

						if self.use_ada_layer_norm_zero:
											__lowerCAmelCase	   =norm_hidden_states * (1 + scale_mlp[:, None]) + shift_mlp[:, None]

						if self._chunk_size is not None:
											# "feed_forward_chunk_size" can be used to save memory
											if norm_hidden_states.shape[self._chunk_dim] % self._chunk_size != 0:
																raise ValueError(
																    F"""`hidden_states` dimension to be chunked: {norm_hidden_states.shape[self._chunk_dim]} has to be divisible by chunk size: {self._chunk_size}. Make sure to set an appropriate `chunk_size` when calling `unet.enable_forward_chunking`.""")

											__lowerCAmelCase	   =norm_hidden_states.shape[self._chunk_dim] // self._chunk_size
											__lowerCAmelCase	   =torch.cat(
											    [self.ff(snake_case_) for hid_slice in norm_hidden_states.chunk(snake_case_				,	dim=self._chunk_dim)]				,	dim=self._chunk_dim				,	)
						else:
											__lowerCAmelCase	   =self.ff(snake_case_)

						if self.use_ada_layer_norm_zero:
											__lowerCAmelCase	   =gate_mlp.unsqueeze(1) * ff_output

						__lowerCAmelCase	   =ff_output + hidden_states

						return hidden_states






class 						__a (     nn.Module				):



	def __init__(						self							:    List[Any]				,	snake_case_							:    Optional[int]				,	snake_case_							:    Optional[int] = None				,	snake_case_							:    str = 4				,	snake_case_							:    Union[str, Any] = 0.0				,	snake_case_							:    Tuple = "geglu"				,	snake_case_							:    Dict = False				,	)->							Union[str, Any]:
						super().__init__()
						__lowerCAmelCase	   =int(dim * mult)
						__lowerCAmelCase	   =dim_out if dim_out is not None else dim

						if activation_fn == "gelu":
											__lowerCAmelCase	   =GELU(snake_case_				,	snake_case_)
						if activation_fn == "gelu-approximate":
											__lowerCAmelCase	   =GELU(snake_case_				,	snake_case_				,	approximate="""tanh""")
						elif activation_fn == "geglu":
											__lowerCAmelCase	   =GEGLU(snake_case_				,	snake_case_)
						elif activation_fn == "geglu-approximate":
											__lowerCAmelCase	   =ApproximateGELU(snake_case_				,	snake_case_)

						__lowerCAmelCase	   =nn.ModuleList([])
						# project in
						self.net.append(snake_case_)
						# project dropout
						self.net.append(nn.Dropout(snake_case_))
						# project out
						self.net.append(nn.Linear(snake_case_				,	snake_case_))
						# FF as used in Vision Transformer, MLP-Mixer, etc. have a final dropout
						if final_dropout:
											self.net.append(nn.Dropout(snake_case_))



	def 		UpperCamelCase							(						self							:    str				,	snake_case_							:    int)->							str:
						for module in self.net:
											__lowerCAmelCase	   =module(snake_case_)
						return hidden_states






class 						__a (     nn.Module				):



	def __init__(						self							:    List[Any]				,	snake_case_							:    str				,	snake_case_							:    Union[str, Any]				,	snake_case_							:    int = "none")->							Dict:
						super().__init__()
						__lowerCAmelCase	   =nn.Linear(snake_case_				,	snake_case_)
						__lowerCAmelCase	   =approximate



	def 		UpperCamelCase							(						self							:    Tuple				,	snake_case_							:    int)->							Dict:
						if gate.device.type != "mps":
											return F.gelu(snake_case_				,	approximate=self.approximate)
						# mps: gelu is not implemented for float16
						return F.gelu(gate.to(dtype=torch.floataa)				,	approximate=self.approximate).to(dtype=gate.dtype)



	def 		UpperCamelCase							(						self							:    Union[str, Any]				,	snake_case_							:    Tuple)->							Union[str, Any]:
						__lowerCAmelCase	   =self.proj(snake_case_)
						__lowerCAmelCase	   =self.gelu(snake_case_)
						return hidden_states






class 						__a (     nn.Module				):



	def __init__(						self							:    List[str]				,	snake_case_							:    List[str]				,	snake_case_							:    Dict)->							int:
						super().__init__()
						__lowerCAmelCase	   =nn.Linear(snake_case_				,	dim_out * 2)



	def 		UpperCamelCase							(						self							:    Optional[int]				,	snake_case_							:    str)->							List[str]:
						if gate.device.type != "mps":
											return F.gelu(snake_case_)
						# mps: gelu is not implemented for float16
						return F.gelu(gate.to(dtype=torch.floataa)).to(dtype=gate.dtype)



	def 		UpperCamelCase							(						self							:    List[Any]				,	snake_case_							:    Tuple)->							Dict:
						__lowerCAmelCase   ,	__lowerCAmelCase	   =self.proj(snake_case_).chunk(2				,	dim=-1)
						return hidden_states * self.gelu(snake_case_)






class 						__a (     nn.Module				):



	def __init__(						self							:    Optional[int]				,	snake_case_							:    Optional[int]				,	snake_case_							:    Any)->							Dict:
						super().__init__()
						__lowerCAmelCase	   =nn.Linear(snake_case_				,	snake_case_)



	def 		UpperCamelCase							(						self							:    Optional[int]				,	snake_case_							:    List[str])->							int:
						__lowerCAmelCase	   =self.proj(snake_case_)
						return x * torch.sigmoid(1.7_0_2 * x)






class 						__a (     nn.Module				):



	def __init__(						self							:    Union[str, Any]				,	snake_case_							:    Dict				,	snake_case_							:    Union[str, Any])->							Tuple:
						super().__init__()
						__lowerCAmelCase	   =nn.Embedding(snake_case_				,	snake_case_)
						__lowerCAmelCase	   =nn.SiLU()
						__lowerCAmelCase	   =nn.Linear(snake_case_				,	embedding_dim * 2)
						__lowerCAmelCase	   =nn.LayerNorm(snake_case_				,	elementwise_affine=snake_case_)



	def 		UpperCamelCase							(						self							:    str				,	snake_case_							:    Union[str, Any]				,	snake_case_							:    Tuple)->							Any:
						__lowerCAmelCase	   =self.linear(self.silu(self.emb(snake_case_)))
						__lowerCAmelCase   ,	__lowerCAmelCase	   =torch.chunk(snake_case_				,	2)
						__lowerCAmelCase	   =self.norm(snake_case_) * (1 + scale) + shift
						return x






class 						__a (     nn.Module				):



	def __init__(						self							:    Any				,	snake_case_							:    int				,	snake_case_							:    Optional[Any])->							List[str]:
						super().__init__()

						__lowerCAmelCase	   =CombinedTimestepLabelEmbeddings(snake_case_				,	snake_case_)

						__lowerCAmelCase	   =nn.SiLU()
						__lowerCAmelCase	   =nn.Linear(snake_case_				,	6 * embedding_dim				,	bias=snake_case_)
						__lowerCAmelCase	   =nn.LayerNorm(snake_case_				,	elementwise_affine=snake_case_				,	eps=1e-6)



	def 		UpperCamelCase							(						self							:    Optional[int]				,	snake_case_							:    List[Any]				,	snake_case_							:    int				,	snake_case_							:    Optional[Any]				,	snake_case_							:    Any=None)->							List[Any]:
						__lowerCAmelCase	   =self.linear(self.silu(self.emb(snake_case_				,	snake_case_				,	hidden_dtype=snake_case_)))
						__lowerCAmelCase   ,	__lowerCAmelCase   ,	__lowerCAmelCase   ,	__lowerCAmelCase   ,	__lowerCAmelCase   ,	__lowerCAmelCase	   =emb.chunk(6				,	dim=1)
						__lowerCAmelCase	   =self.norm(snake_case_) * (1 + scale_msa[:, None]) + shift_msa[:, None]
						return x, gate_msa, shift_mlp, scale_mlp, gate_mlp






class 						__a (     nn.Module				):



	def __init__(						self							:    str				,	snake_case_							:    List[str]				,	snake_case_							:    int				,	snake_case_							:    List[Any]				,	snake_case_							:    Dict = None				,	snake_case_							:    List[str] = 1e-5)->							List[str]:
						super().__init__()
						__lowerCAmelCase	   =num_groups
						__lowerCAmelCase	   =eps

						if act_fn is None:
											__lowerCAmelCase	   =None
						else:
											__lowerCAmelCase	   =get_activation(snake_case_)

						__lowerCAmelCase	   =nn.Linear(snake_case_				,	out_dim * 2)



	def 		UpperCamelCase							(						self							:    Dict				,	snake_case_							:    Tuple				,	snake_case_							:    List[str])->							int:
						if self.act:
											__lowerCAmelCase	   =self.act(snake_case_)
						__lowerCAmelCase	   =self.linear(snake_case_)
						__lowerCAmelCase	   =emb[:, :, None, None]
						__lowerCAmelCase   ,	__lowerCAmelCase	   =emb.chunk(2				,	dim=1)

						__lowerCAmelCase	   =F.group_norm(snake_case_				,	self.num_groups				,	eps=self.eps)
						__lowerCAmelCase	   =x * (1 + scale) + shift
						return x









import os
from typing import Dict, List, Tuple, TypeVar, Union


lowercase_	       =			TypeVar('''T''')

lowercase_	       =			Union[List[T], Tuple[T, ...]]
lowercase_	       =			Union[T, List[T], Dict[str, T]]
lowercase_	       =			Union[str, bytes, os.PathLike]




