


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  snake_case_     (nn.Module   ):
					def __init__(   self     :Any    ,__snake_case     :int    ,__snake_case     :int    ,__snake_case     :int    ,__snake_case     :int=0.0    ,__snake_case     :Optional[int] = None    ,__snake_case     :str = "geglu"    ,__snake_case     :Optional[int] = None    ,__snake_case     :bool = False    ,__snake_case     :bool = False    ,__snake_case     :bool = False    ,__snake_case     :bool = False    ,__snake_case     :bool = True    ,__snake_case     :str = "layer_norm"    ,__snake_case     :bool = False    ,)      ->					Union[str, Any]:
												super().__init__()
												a__    =  only_cross_attention

												a__    =  (num_embeds_ada_norm is not None) and norm_type == "ada_norm_zero"
												a__    =  (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:
																			a__    =  AdaLayerNorm(__lowerCamelCase    ,__lowerCamelCase   )
												elif self.use_ada_layer_norm_zero:
																			a__    =  AdaLayerNormZero(__lowerCamelCase    ,__lowerCamelCase   )
												else:
																			a__    =  nn.LayerNorm(__lowerCamelCase    ,elementwise_affine=__lowerCamelCase   )
												a__    =  Attention(
												    query_dim=__lowerCamelCase    ,heads=__lowerCamelCase    ,dim_head=__lowerCamelCase    ,dropout=__lowerCamelCase    ,bias=__lowerCamelCase    ,cross_attention_dim=cross_attention_dim if only_cross_attention else None    ,upcast_attention=__lowerCamelCase    ,)

												# 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.
																			a__    =  (
																			    AdaLayerNorm(__lowerCamelCase    ,__lowerCamelCase   )
																			    if self.use_ada_layer_norm
																			    else nn.LayerNorm(__lowerCamelCase    ,elementwise_affine=__lowerCamelCase   )
																			)
																			a__    =  Attention(
																			    query_dim=__lowerCamelCase    ,cross_attention_dim=cross_attention_dim if not double_self_attention else None    ,heads=__lowerCamelCase    ,dim_head=__lowerCamelCase    ,dropout=__lowerCamelCase    ,bias=__lowerCamelCase    ,upcast_attention=__lowerCamelCase    ,)  # is self-attn if encoder_hidden_states is none
												else:
																			a__    =  None
																			a__    =  None

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

												# let chunk size default to None
												a__    =  None
												a__    =  0
					def 				lowerCamelCase__(   self     :int    ,__snake_case     :Optional[int]    ,__snake_case     :int   )      ->					Union[str, Any]:
												# Sets chunk feed-forward
												a__    =  chunk_size
												a__    =  dim



					def 				lowerCamelCase__(   self     :Any    ,__snake_case     :torch.FloatTensor    ,__snake_case     :Optional[torch.FloatTensor] = None    ,__snake_case     :Optional[torch.FloatTensor] = None    ,__snake_case     :Optional[torch.FloatTensor] = None    ,__snake_case     :Optional[torch.LongTensor] = None    ,__snake_case     :Dict[str, Any] = None    ,__snake_case     :Optional[torch.LongTensor] = None    ,)      ->					str:
												# Notice that normalization is always applied before the real computation in the following blocks.
												# 1. Self-Attention
												if self.use_ada_layer_norm:
																			a__    =  self.norma(__lowerCamelCase    ,__lowerCamelCase   )
												elif self.use_ada_layer_norm_zero:
																			a__    =  self.norma(
																			    __lowerCamelCase    ,__lowerCamelCase    ,__lowerCamelCase    ,hidden_dtype=hidden_states.dtype   )
												else:
																			a__    =  self.norma(__lowerCamelCase   )

												a__    =  cross_attention_kwargs if cross_attention_kwargs is not None else {}

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

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

																			a__    =  self.attna(
																			    __lowerCamelCase    ,encoder_hidden_states=__lowerCamelCase    ,attention_mask=__lowerCamelCase    ,**__lowerCamelCase    ,)
																			a__    =  attn_output + hidden_states

												# 3. Feed-forward
												a__    =  self.norma(__lowerCamelCase   )

												if self.use_ada_layer_norm_zero:
																			a__    =  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`.'   )

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

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

												a__    =  ff_output + hidden_states

												return hidden_states







class  snake_case_     (nn.Module   ):
					def __init__(   self     :int    ,__snake_case     :int    ,__snake_case     :Optional[int] = None    ,__snake_case     :int = 4    ,__snake_case     :float = 0.0    ,__snake_case     :str = "geglu"    ,__snake_case     :bool = False    ,)      ->					Dict:
												super().__init__()
												a__    =  int(dim * mult   )
												a__    =  dim_out if dim_out is not None else dim

												if activation_fn == "gelu":
																			a__    =  GELU(__lowerCamelCase    ,__lowerCamelCase   )
												if activation_fn == "gelu-approximate":
																			a__    =  GELU(__lowerCamelCase    ,__lowerCamelCase    ,approximate='tanh'   )
												elif activation_fn == "geglu":
																			a__    =  GEGLU(__lowerCamelCase    ,__lowerCamelCase   )
												elif activation_fn == "geglu-approximate":
																			a__    =  ApproximateGELU(__lowerCamelCase    ,__lowerCamelCase   )

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



					def 				lowerCamelCase__(   self     :Union[str, Any]    ,__snake_case     :Optional[int]   )      ->					List[str]:
												for module in self.net:
																			a__    =  module(__lowerCamelCase   )
												return hidden_states







class  snake_case_     (nn.Module   ):
					def __init__(   self     :Optional[int]    ,__snake_case     :int    ,__snake_case     :int    ,__snake_case     :str = "none"   )      ->					Optional[Any]:
												super().__init__()
												a__    =  nn.Linear(__lowerCamelCase    ,__lowerCamelCase   )
												a__    =  approximate
					def 				lowerCamelCase__(   self     :Optional[Any]    ,__snake_case     :str   )      ->					List[str]:
												if gate.device.type != "mps":
																			return F.gelu(__lowerCamelCase    ,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     :List[Any]    ,__snake_case     :str   )      ->					List[Any]:
												a__    =  self.proj(__lowerCamelCase   )
												a__    =  self.gelu(__lowerCamelCase   )
												return hidden_states







class  snake_case_     (nn.Module   ):
					def __init__(   self     :List[str]    ,__snake_case     :int    ,__snake_case     :int   )      ->					Optional[Any]:
												super().__init__()
												a__    =  nn.Linear(__lowerCamelCase    ,dim_out * 2   )
					def 				lowerCamelCase__(   self     :List[str]    ,__snake_case     :Union[str, Any]   )      ->					Optional[int]:
												if gate.device.type != "mps":
																			return F.gelu(__lowerCamelCase   )
												# mps: gelu is not implemented for float16
												return F.gelu(gate.to(dtype=torch.floataa   )   ).to(dtype=gate.dtype   )



					def 				lowerCamelCase__(   self     :Optional[int]    ,__snake_case     :Tuple   )      ->					Tuple:
												a__    =  self.proj(__lowerCamelCase   ).chunk(2    ,dim=-1   )
												return hidden_states * self.gelu(__lowerCamelCase   )







class  snake_case_     (nn.Module   ):
					def __init__(   self     :Tuple    ,__snake_case     :int    ,__snake_case     :int   )      ->					Union[str, Any]:
												super().__init__()
												a__    =  nn.Linear(__lowerCamelCase    ,__lowerCamelCase   )



					def 				lowerCamelCase__(   self     :Optional[Any]    ,__snake_case     :Union[str, Any]   )      ->					Optional[Any]:
												a__    =  self.proj(__lowerCamelCase   )
												return x * torch.sigmoid(1.7_02 * x   )







class  snake_case_     (nn.Module   ):
					def __init__(   self     :List[str]    ,__snake_case     :Union[str, Any]    ,__snake_case     :Optional[int]   )      ->					Union[str, Any]:
												super().__init__()
												a__    =  nn.Embedding(__lowerCamelCase    ,__lowerCamelCase   )
												a__    =  nn.SiLU()
												a__    =  nn.Linear(__lowerCamelCase    ,embedding_dim * 2   )
												a__    =  nn.LayerNorm(__lowerCamelCase    ,elementwise_affine=__lowerCamelCase   )



					def 				lowerCamelCase__(   self     :Optional[int]    ,__snake_case     :Any    ,__snake_case     :Any   )      ->					Optional[int]:
												a__    =  self.linear(self.silu(self.emb(__lowerCamelCase   )   )   )
												a__    =  torch.chunk(__lowerCamelCase    ,2   )
												a__    =  self.norm(__lowerCamelCase   ) * (1 + scale) + shift
												return x







class  snake_case_     (nn.Module   ):
					def __init__(   self     :Union[str, Any]    ,__snake_case     :Optional[Any]    ,__snake_case     :Union[str, Any]   )      ->					Optional[int]:
												super().__init__()

												a__    =  CombinedTimestepLabelEmbeddings(__lowerCamelCase    ,__lowerCamelCase   )

												a__    =  nn.SiLU()
												a__    =  nn.Linear(__lowerCamelCase    ,6 * embedding_dim    ,bias=__lowerCamelCase   )
												a__    =  nn.LayerNorm(__lowerCamelCase    ,elementwise_affine=__lowerCamelCase    ,eps=1E-6   )



					def 				lowerCamelCase__(   self     :Optional[Any]    ,__snake_case     :List[Any]    ,__snake_case     :Tuple    ,__snake_case     :Any    ,__snake_case     :Dict=None   )      ->					Dict:
												a__    =  self.linear(self.silu(self.emb(__lowerCamelCase    ,__lowerCamelCase    ,hidden_dtype=__lowerCamelCase   )   )   )
												a__    =  emb.chunk(6    ,dim=1   )
												a__    =  self.norm(__lowerCamelCase   ) * (1 + scale_msa[:, None]) + shift_msa[:, None]
												return x, gate_msa, shift_mlp, scale_mlp, gate_mlp







class  snake_case_     (nn.Module   ):
					def __init__(   self     :str    ,__snake_case     :int    ,__snake_case     :int    ,__snake_case     :int    ,__snake_case     :Optional[str] = None    ,__snake_case     :float = 1E-5   )      ->					Dict:
												super().__init__()
												a__    =  num_groups
												a__    =  eps

												if act_fn is None:
																			a__    =  None
												else:
																			a__    =  get_activation(__lowerCamelCase   )

												a__    =  nn.Linear(__lowerCamelCase    ,out_dim * 2   )



					def 				lowerCamelCase__(   self     :str    ,__snake_case     :Union[str, Any]    ,__snake_case     :int   )      ->					str:
												if self.act:
																			a__    =  self.act(__lowerCamelCase   )
												a__    =  self.linear(__lowerCamelCase   )
												a__    =  emb[:, :, None, None]
												a__    =  emb.chunk(2    ,dim=1   )

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








import os
import tempfile
import unittest

from transformers import is_torch_available
from transformers.testing_utils import require_torch


if is_torch_available():
						import torch
						from torch import nn

						from transformers import (
						    Adafactor,
						    AdamW,
						    get_constant_schedule,
						    get_constant_schedule_with_warmup,
						    get_cosine_schedule_with_warmup,
						    get_cosine_with_hard_restarts_schedule_with_warmup,
						    get_inverse_sqrt_schedule,
						    get_linear_schedule_with_warmup,
						    get_polynomial_decay_schedule_with_warmup,
						)






def 							__lowercase     (				__lowerCAmelCase							:       str      ,					__lowerCAmelCase							:       Any=1_0     ):
							a__    =  []
							for _ in range(__lowerCAmelCase     ):
														lrs.append(scheduler.get_lr()[0]     )
														scheduler.step()
							return lrs






def 							__lowercase     (				__lowerCAmelCase							:       Optional[int]      ,					__lowerCAmelCase							:       List[str]=1_0     ):
							a__    =  []
							for step in range(__lowerCAmelCase     ):
														lrs.append(scheduler.get_lr()[0]     )
														scheduler.step()
														if step == num_steps // 2:
																					with tempfile.TemporaryDirectory() as tmpdirname:
																												a__    =  os.path.join(__lowerCAmelCase      ,					'schedule.bin'     )
																												torch.save(scheduler.state_dict()      ,					__lowerCAmelCase     )

																												a__    =  torch.load(__lowerCAmelCase     )
																												scheduler.load_state_dict(__lowerCAmelCase     )
							return lrs







@require_torch
class  snake_case_     (unittest.TestCase   ):
					def 				lowerCamelCase__(   self     :Optional[int]    ,__snake_case     :List[Any]    ,__snake_case     :int    ,__snake_case     :Union[str, Any]   )      ->					int:
												self.assertEqual(len(__snake_case   )    ,len(__snake_case   )   )
												for a, b in zip(__snake_case    ,__snake_case   ):
																			self.assertAlmostEqual(__snake_case    ,__snake_case    ,delta=__snake_case   )
					def 				lowerCamelCase__(   self     :Optional[Any]   )      ->					str:
												a__    =  torch.tensor([0.1, -0.2, -0.1]    ,requires_grad=__snake_case   )
												a__    =  torch.tensor([0.4, 0.2, -0.5]   )
												a__    =  nn.MSELoss()
												# No warmup, constant schedule, no gradient clipping
												a__    =  AdamW(params=[w]    ,lr=2E-1    ,weight_decay=0.0   )
												for _ in range(1_00   ):
																			a__    =  criterion(__snake_case    ,__snake_case   )
																			loss.backward()
																			optimizer.step()
																			w.grad.detach_()  # No zero_grad() function on simple tensors. we do it ourselves.
																			w.grad.zero_()
												self.assertListAlmostEqual(w.tolist()    ,[0.4, 0.2, -0.5]    ,tol=1E-2   )



					def 				lowerCamelCase__(   self     :Tuple   )      ->					int:
												a__    =  torch.tensor([0.1, -0.2, -0.1]    ,requires_grad=__snake_case   )
												a__    =  torch.tensor([0.4, 0.2, -0.5]   )
												a__    =  nn.MSELoss()
												# No warmup, constant schedule, no gradient clipping
												a__    =  Adafactor(
												    params=[w]    ,lr=1E-2    ,eps=(1E-30, 1E-3)    ,clip_threshold=1.0    ,decay_rate=-0.8    ,betaa=__snake_case    ,weight_decay=0.0    ,relative_step=__snake_case    ,scale_parameter=__snake_case    ,warmup_init=__snake_case    ,)
												for _ in range(10_00   ):
																			a__    =  criterion(__snake_case    ,__snake_case   )
																			loss.backward()
																			optimizer.step()
																			w.grad.detach_()  # No zero_grad() function on simple tensors. we do it ourselves.
																			w.grad.zero_()
												self.assertListAlmostEqual(w.tolist()    ,[0.4, 0.2, -0.5]    ,tol=1E-2   )







@require_torch
class  snake_case_     (unittest.TestCase   ):
					UpperCAmelCase__      :					str					   =    nn.Linear(5_0			,		5_0   ) if is_torch_available() else None
					UpperCAmelCase__      :					Dict					   =    AdamW(m.parameters()			,		lr=1_0.0   ) if is_torch_available() else None
					UpperCAmelCase__      :					Optional[Any]					   =    1_0
					def 				lowerCamelCase__(   self     :Optional[Any]    ,__snake_case     :Optional[int]    ,__snake_case     :Tuple    ,__snake_case     :int    ,__snake_case     :Any=None   )      ->					Optional[Any]:
												self.assertEqual(len(__snake_case   )    ,len(__snake_case   )   )
												for a, b in zip(__snake_case    ,__snake_case   ):
																			self.assertAlmostEqual(__snake_case    ,__snake_case    ,delta=__snake_case    ,msg=__snake_case   )



					def 				lowerCamelCase__(   self     :Tuple   )      ->					List[Any]:
												a__    =  {'num_warmup_steps': 2, 'num_training_steps': 10}
												# schedulers doct format
												# function: (sched_args_dict, expected_learning_rates)
												a__    =  {
												    get_constant_schedule: ({}, [10.0] * self.num_steps),
												    get_constant_schedule_with_warmup: (
												        {'num_warmup_steps': 4},
												        [0.0, 2.5, 5.0, 7.5, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0],
												    ),
												    get_linear_schedule_with_warmup: (
												        {**common_kwargs},
												        [0.0, 5.0, 10.0, 8.75, 7.5, 6.25, 5.0, 3.75, 2.5, 1.25],
												    ),
												    get_cosine_schedule_with_warmup: (
												        {**common_kwargs},
												        [0.0, 5.0, 10.0, 9.61, 8.53, 6.91, 5.0, 3.08, 1.46, 0.38],
												    ),
												    get_cosine_with_hard_restarts_schedule_with_warmup: (
												        {**common_kwargs, 'num_cycles': 2},
												        [0.0, 5.0, 10.0, 8.53, 5.0, 1.46, 10.0, 8.53, 5.0, 1.46],
												    ),
												    get_polynomial_decay_schedule_with_warmup: (
												        {**common_kwargs, 'power': 2.0, 'lr_end': 1E-7},
												        [0.0, 5.0, 10.0, 7.6_56, 5.6_25, 3.9_06, 2.5, 1.4_06, 0.6_25, 0.1_56],
												    ),
												    get_inverse_sqrt_schedule: (
												        {'num_warmup_steps': 2},
												        [0.0, 5.0, 10.0, 8.1_65, 7.0_71, 6.3_25, 5.7_74, 5.3_45, 5.0, 4.7_14],
												    ),
												}

												for scheduler_func, data in scheds.items():
																			a__   ,      a__    =  data

																			a__    =  scheduler_func(self.optimizer    ,**__snake_case   )
																			self.assertEqual(len([scheduler.get_lr()[0]]   )    ,1   )
																			a__    =  unwrap_schedule(__snake_case    ,self.num_steps   )
																			self.assertListAlmostEqual(
																			    __snake_case    ,__snake_case    ,tol=1E-2    ,msg=F'failed for {scheduler_func} in normal scheduler'    ,)

																			a__    =  scheduler_func(self.optimizer    ,**__snake_case   )
																			if scheduler_func.__name__ != "get_constant_schedule":
																										LambdaScheduleWrapper.wrap_scheduler(__snake_case   )  # wrap to test picklability of the schedule
																			a__    =  unwrap_and_save_reload_schedule(__snake_case    ,self.num_steps   )
																			self.assertListEqual(__snake_case    ,__snake_case    ,msg=F'failed for {scheduler_func} in save and reload'   )







class  snake_case_     :
					def __init__(   self     :Tuple    ,__snake_case     :str   )      ->					Any:
												a__    =  fn
					def __call__(   self     :List[str]    ,*__snake_case     :Optional[Any]    ,**__snake_case     :Optional[int]   )      ->					Union[str, Any]:
												return self.fn(*__snake_case    ,**__snake_case   )



					@classmethod
					def 				lowerCamelCase__(   self     :Tuple    ,__snake_case     :Union[str, Any]   )      ->					Dict:
												a__    =  list(map(self    ,scheduler.lr_lambdas   )   )




