


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   SCREAMING_SNAKE_CASE_			(nn.Module						):




       '''simple docstring'''



       def __init__(						self				:				Union[str, Any]		,				__a				:				int		,				__a				:				int		,				__a				:				int		,				__a				:				Optional[Any]=0.0		,				__a				:				Optional[int] = None		,				__a				:				str = "geglu"		,				__a				:				Optional[int] = None		,				__a				:				bool = False		,				__a				:				bool = False		,				__a				:				bool = False		,				__a				:				bool = False		,				__a				:				bool = True		,				__a				:				str = "layer_norm"		,				__a				:				bool = False		,				)					->Any:
          super().__init__()
          lowerCamelCase_						:   str		= only_cross_attention

          lowerCamelCase_						:   int		= (num_embeds_ada_norm is not None) and norm_type == """ada_norm_zero"""
          lowerCamelCase_						:   Optional[Any]		= (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_						:   List[str]		= AdaLayerNorm(__a		,				__a							)
          elif self.use_ada_layer_norm_zero:
             lowerCamelCase_						:   List[str]		= AdaLayerNormZero(__a		,				__a							)
          else:
             lowerCamelCase_						:   Dict		= nn.LayerNorm(__a		,				elementwise_affine=__a							)
          lowerCamelCase_						:   str		= Attention(
              query_dim=__a		,				heads=__a		,				dim_head=__a		,				dropout=__a		,				bias=__a		,				cross_attention_dim=cross_attention_dim if only_cross_attention else None		,				upcast_attention=__a		,				)

          # 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_						:   Any		= (
                 AdaLayerNorm(__a		,				__a							)
                 if self.use_ada_layer_norm
                 else nn.LayerNorm(__a		,				elementwise_affine=__a							)
             )
             lowerCamelCase_						:   int		= Attention(
                 query_dim=__a		,				cross_attention_dim=cross_attention_dim if not double_self_attention else None		,				heads=__a		,				dim_head=__a		,				dropout=__a		,				bias=__a		,				upcast_attention=__a		,				)  # is self-attn if encoder_hidden_states is none
          else:
             lowerCamelCase_						:   Optional[Any]		= None
             lowerCamelCase_						:   str		= None

          # 3. Feed-forward
          lowerCamelCase_						:   Optional[Any]		= nn.LayerNorm(__a		,				elementwise_affine=__a							)
          lowerCamelCase_						:   int		= FeedForward(__a		,				dropout=__a		,				activation_fn=__a		,				final_dropout=__a							)

          # let chunk size default to None
          lowerCamelCase_						:   Optional[Any]		= None
          lowerCamelCase_						:   Any		= 0



       def 				_lowerCAmelCase							(						self				:				str		,				__a				:				Optional[int]		,				__a				:				int							)					->Union[str, Any]:
          # Sets chunk feed-forward
          lowerCamelCase_						:   str		= chunk_size
          lowerCamelCase_						:   Union[str, Any]		= dim




       def 				_lowerCAmelCase							(						self				:				Any		,				__a				:				torch.FloatTensor		,				__a				:				Optional[torch.FloatTensor] = None		,				__a				:				Optional[torch.FloatTensor] = None		,				__a				:				Optional[torch.FloatTensor] = None		,				__a				:				Optional[torch.LongTensor] = None		,				__a				:				Dict[str, Any] = None		,				__a				:				Optional[torch.LongTensor] = None		,				)					->List[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_						:   Optional[int]		= self.norma(__a		,				__a							)
          elif self.use_ada_layer_norm_zero:
             lowerCamelCase_,	lowerCamelCase_,	lowerCamelCase_,	lowerCamelCase_,	lowerCamelCase_						:   Optional[Any]		= self.norma(
                 __a		,				__a		,				__a		,				hidden_dtype=hidden_states.dtype							)
          else:
             lowerCamelCase_						:   Dict		= self.norma(__a							)

          lowerCamelCase_						:   List[str]		= cross_attention_kwargs if cross_attention_kwargs is not None else {}

          lowerCamelCase_						:   Optional[Any]		= self.attna(
              __a		,				encoder_hidden_states=encoder_hidden_states if self.only_cross_attention else None		,				attention_mask=__a		,				**__a		,				)
          if self.use_ada_layer_norm_zero:
             lowerCamelCase_						:   int		= gate_msa.unsqueeze(1							) * attn_output
          lowerCamelCase_						:   Union[str, Any]		= attn_output + hidden_states

          # 2. Cross-Attention
          if self.attna is not None:
             lowerCamelCase_						:   Optional[Any]		= (
                 self.norma(__a		,				__a							) if self.use_ada_layer_norm else self.norma(__a							)
             )

             lowerCamelCase_						:   Any		= self.attna(
                 __a		,				encoder_hidden_states=__a		,				attention_mask=__a		,				**__a		,				)
             lowerCamelCase_						:   Tuple		= attn_output + hidden_states

          # 3. Feed-forward
          lowerCamelCase_						:   Any		= self.norma(__a							)

          if self.use_ada_layer_norm_zero:
             lowerCamelCase_						:   Union[str, Any]		= 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_						:   List[Any]		= norm_hidden_states.shape[self._chunk_dim] // self._chunk_size
             lowerCamelCase_						:   List[Any]		= torch.cat(
                 [self.ff(__a							) for hid_slice in norm_hidden_states.chunk(__a		,				dim=self._chunk_dim							)]		,				dim=self._chunk_dim		,				)
          else:
             lowerCamelCase_						:   Optional[Any]		= self.ff(__a							)

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

          lowerCamelCase_						:   Any		= ff_output + hidden_states

          return hidden_states







class   SCREAMING_SNAKE_CASE_			(nn.Module						):




       '''simple docstring'''



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

          if activation_fn == "gelu":
             lowerCamelCase_						:   str		= GELU(__a		,				__a							)
          if activation_fn == "gelu-approximate":
             lowerCamelCase_						:   Union[str, Any]		= GELU(__a		,				__a		,				approximate="""tanh"""							)
          elif activation_fn == "geglu":
             lowerCamelCase_						:   Any		= GEGLU(__a		,				__a							)
          elif activation_fn == "geglu-approximate":
             lowerCamelCase_						:   List[Any]		= ApproximateGELU(__a		,				__a							)

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




       def 				_lowerCAmelCase							(						self				:				Optional[int]		,				__a				:				int							)					->List[str]:
          for module in self.net:
             lowerCamelCase_						:   Tuple		= module(__a							)
          return hidden_states







class   SCREAMING_SNAKE_CASE_			(nn.Module						):




       '''simple docstring'''



       def __init__(						self				:				Optional[int]		,				__a				:				int		,				__a				:				int		,				__a				:				str = "none"							)					->int:
          super().__init__()
          lowerCamelCase_						:   List[str]		= nn.Linear(__a		,				__a							)
          lowerCamelCase_						:   List[str]		= approximate



       def 				_lowerCAmelCase							(						self				:				Optional[int]		,				__a				:				List[str]							)					->str:
          if gate.device.type != "mps":
             return F.gelu(__a		,				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 				_lowerCAmelCase							(						self				:				Union[str, Any]		,				__a				:				str							)					->List[str]:
          lowerCamelCase_						:   Optional[int]		= self.proj(__a							)
          lowerCamelCase_						:   Optional[int]		= self.gelu(__a							)
          return hidden_states







class   SCREAMING_SNAKE_CASE_			(nn.Module						):




       '''simple docstring'''



       def __init__(						self				:				Tuple		,				__a				:				int		,				__a				:				int							)					->Tuple:
          super().__init__()
          lowerCamelCase_						:   int		= nn.Linear(__a		,				dim_out * 2							)



       def 				_lowerCAmelCase							(						self				:				Dict		,				__a				:				Optional[Any]							)					->Any:
          if gate.device.type != "mps":
             return F.gelu(__a							)
          # mps: gelu is not implemented for float16
          return F.gelu(gate.to(dtype=torch.floataa							)							).to(dtype=gate.dtype							)




       def 				_lowerCAmelCase							(						self				:				str		,				__a				:				Union[str, Any]							)					->str:
          lowerCamelCase_,	lowerCamelCase_						:   Optional[int]		= self.proj(__a							).chunk(2		,				dim=-1							)
          return hidden_states * self.gelu(__a							)







class   SCREAMING_SNAKE_CASE_			(nn.Module						):




       '''simple docstring'''



       def __init__(						self				:				Any		,				__a				:				int		,				__a				:				int							)					->Any:
          super().__init__()
          lowerCamelCase_						:   int		= nn.Linear(__a		,				__a							)




       def 				_lowerCAmelCase							(						self				:				int		,				__a				:				Tuple							)					->str:
          lowerCamelCase_						:   List[str]		= self.proj(__a							)
          return x * torch.sigmoid(1.702 * x							)







class   SCREAMING_SNAKE_CASE_			(nn.Module						):




       '''simple docstring'''



       def __init__(						self				:				List[str]		,				__a				:				Tuple		,				__a				:				int							)					->Optional[Any]:
          super().__init__()
          lowerCamelCase_						:   Any		= nn.Embedding(__a		,				__a							)
          lowerCamelCase_						:   Union[str, Any]		= nn.SiLU()
          lowerCamelCase_						:   int		= nn.Linear(__a		,				embedding_dim * 2							)
          lowerCamelCase_						:   str		= nn.LayerNorm(__a		,				elementwise_affine=__a							)




       def 				_lowerCAmelCase							(						self				:				Any		,				__a				:				Union[str, Any]		,				__a				:				List[str]							)					->Optional[Any]:
          lowerCamelCase_						:   Optional[int]		= self.linear(self.silu(self.emb(__a							)							)							)
          lowerCamelCase_,	lowerCamelCase_						:   Optional[Any]		= torch.chunk(__a		,				2							)
          lowerCamelCase_						:   Union[str, Any]		= self.norm(__a							) * (1 + scale) + shift
          return x







class   SCREAMING_SNAKE_CASE_			(nn.Module						):




       '''simple docstring'''



       def __init__(						self				:				Tuple		,				__a				:				Dict		,				__a				:				str							)					->int:
          super().__init__()

          lowerCamelCase_						:   List[Any]		= CombinedTimestepLabelEmbeddings(__a		,				__a							)

          lowerCamelCase_						:   Union[str, Any]		= nn.SiLU()
          lowerCamelCase_						:   Union[str, Any]		= nn.Linear(__a		,				6 * embedding_dim		,				bias=__a							)
          lowerCamelCase_						:   Optional[Any]		= nn.LayerNorm(__a		,				elementwise_affine=__a		,				eps=1e-6							)




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







class   SCREAMING_SNAKE_CASE_			(nn.Module						):




       '''simple docstring'''



       def __init__(						self				:				List[str]		,				__a				:				int		,				__a				:				int		,				__a				:				int		,				__a				:				Optional[str] = None		,				__a				:				float = 1e-5							)					->Optional[int]:
          super().__init__()
          lowerCamelCase_						:   int		= num_groups
          lowerCamelCase_						:   int		= eps

          if act_fn is None:
             lowerCamelCase_						:   Optional[int]		= None
          else:
             lowerCamelCase_						:   Optional[Any]		= get_activation(__a							)

          lowerCamelCase_						:   List[Any]		= nn.Linear(__a		,				out_dim * 2							)




       def 				_lowerCAmelCase							(						self				:				str		,				__a				:				Optional[Any]		,				__a				:				Dict							)					->Optional[int]:
          if self.act:
             lowerCamelCase_						:   Dict		= self.act(__a							)
          lowerCamelCase_						:   Optional[Any]		= self.linear(__a							)
          lowerCamelCase_						:   Dict		= emb[:, :, None, None]
          lowerCamelCase_,	lowerCamelCase_						:   Dict		= emb.chunk(2		,				dim=1							)

          lowerCamelCase_						:   Any		= F.group_norm(__a		,				self.num_groups		,				eps=self.eps							)
          lowerCamelCase_						:   Union[str, Any]		= x * (1 + scale) + shift
          return x









snake_case__				:	List[Any]					       =					[
    999,
    800,
    799,
    600,
    599,
    500,
    400,
    399,
    377,
    355,
    333,
    311,
    288,
    266,
    244,
    222,
    200,
    199,
    177,
    155,
    133,
    111,
    88,
    66,
    44,
    22,
    0,
]

snake_case__				:	Tuple					       =					[
    999,
    976,
    952,
    928,
    905,
    882,
    858,
    857,
    810,
    762,
    715,
    714,
    572,
    429,
    428,
    286,
    285,
    238,
    190,
    143,
    142,
    118,
    95,
    71,
    47,
    24,
    0,
]

snake_case__				:	List[Any]					       =					[
    999,
    988,
    977,
    966,
    955,
    944,
    933,
    922,
    911,
    900,
    899,
    879,
    859,
    840,
    820,
    800,
    799,
    766,
    733,
    700,
    699,
    650,
    600,
    599,
    500,
    499,
    400,
    399,
    350,
    300,
    299,
    266,
    233,
    200,
    199,
    179,
    159,
    140,
    120,
    100,
    99,
    88,
    77,
    66,
    55,
    44,
    33,
    22,
    11,
    0,
]

snake_case__				:	List[str]					       =					[
    999,
    995,
    992,
    989,
    985,
    981,
    978,
    975,
    971,
    967,
    964,
    961,
    957,
    956,
    951,
    947,
    942,
    937,
    933,
    928,
    923,
    919,
    914,
    913,
    908,
    903,
    897,
    892,
    887,
    881,
    876,
    871,
    870,
    864,
    858,
    852,
    846,
    840,
    834,
    828,
    827,
    820,
    813,
    806,
    799,
    792,
    785,
    784,
    777,
    770,
    763,
    756,
    749,
    742,
    741,
    733,
    724,
    716,
    707,
    699,
    698,
    688,
    677,
    666,
    656,
    655,
    645,
    634,
    623,
    613,
    612,
    598,
    584,
    570,
    569,
    555,
    541,
    527,
    526,
    505,
    484,
    483,
    462,
    440,
    439,
    396,
    395,
    352,
    351,
    308,
    307,
    264,
    263,
    220,
    219,
    176,
    132,
    88,
    44,
    0,
]

snake_case__				:	Any					       =					[
    999,
    997,
    995,
    992,
    990,
    988,
    986,
    984,
    981,
    979,
    977,
    975,
    972,
    970,
    968,
    966,
    964,
    961,
    959,
    957,
    956,
    954,
    951,
    949,
    946,
    944,
    941,
    939,
    936,
    934,
    931,
    929,
    926,
    924,
    921,
    919,
    916,
    914,
    913,
    910,
    907,
    905,
    902,
    899,
    896,
    893,
    891,
    888,
    885,
    882,
    879,
    877,
    874,
    871,
    870,
    867,
    864,
    861,
    858,
    855,
    852,
    849,
    846,
    843,
    840,
    837,
    834,
    831,
    828,
    827,
    824,
    821,
    817,
    814,
    811,
    808,
    804,
    801,
    798,
    795,
    791,
    788,
    785,
    784,
    780,
    777,
    774,
    770,
    766,
    763,
    760,
    756,
    752,
    749,
    746,
    742,
    741,
    737,
    733,
    730,
    726,
    722,
    718,
    714,
    710,
    707,
    703,
    699,
    698,
    694,
    690,
    685,
    681,
    677,
    673,
    669,
    664,
    660,
    656,
    655,
    650,
    646,
    641,
    636,
    632,
    627,
    622,
    618,
    613,
    612,
    607,
    602,
    596,
    591,
    586,
    580,
    575,
    570,
    569,
    563,
    557,
    551,
    545,
    539,
    533,
    527,
    526,
    519,
    512,
    505,
    498,
    491,
    484,
    483,
    474,
    466,
    457,
    449,
    440,
    439,
    428,
    418,
    407,
    396,
    395,
    381,
    366,
    352,
    351,
    330,
    308,
    307,
    286,
    264,
    263,
    242,
    220,
    219,
    176,
    175,
    132,
    131,
    88,
    44,
    0,
]

snake_case__				:	int					       =					[
    999,
    991,
    982,
    974,
    966,
    958,
    950,
    941,
    933,
    925,
    916,
    908,
    900,
    899,
    874,
    850,
    825,
    800,
    799,
    700,
    600,
    500,
    400,
    300,
    200,
    100,
    0,
]

snake_case__				:	Any					       =					[
    999,
    992,
    985,
    978,
    971,
    964,
    957,
    949,
    942,
    935,
    928,
    921,
    914,
    907,
    900,
    899,
    879,
    859,
    840,
    820,
    800,
    799,
    766,
    733,
    700,
    699,
    650,
    600,
    599,
    500,
    499,
    400,
    399,
    300,
    299,
    200,
    199,
    100,
    99,
    0,
]

snake_case__				:	Union[str, Any]					       =					[
    999,
    996,
    992,
    989,
    985,
    982,
    979,
    975,
    972,
    968,
    965,
    961,
    958,
    955,
    951,
    948,
    944,
    941,
    938,
    934,
    931,
    927,
    924,
    920,
    917,
    914,
    910,
    907,
    903,
    900,
    899,
    891,
    884,
    876,
    869,
    861,
    853,
    846,
    838,
    830,
    823,
    815,
    808,
    800,
    799,
    788,
    777,
    766,
    755,
    744,
    733,
    722,
    711,
    700,
    699,
    688,
    677,
    666,
    655,
    644,
    633,
    622,
    611,
    600,
    599,
    585,
    571,
    557,
    542,
    528,
    514,
    500,
    499,
    485,
    471,
    457,
    442,
    428,
    414,
    400,
    399,
    379,
    359,
    340,
    320,
    300,
    299,
    279,
    259,
    240,
    220,
    200,
    199,
    166,
    133,
    100,
    99,
    66,
    33,
    0,
]





