import inspect
import unittest

from transformers import MobileViTConfig
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
				import torch

				from transformers import MobileViTForImageClassification, MobileViTForSemanticSegmentation, MobileViTModel
				from transformers.models.mobilevit.modeling_mobilevit import MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
				from PIL import Image

				from transformers import MobileViTImageProcessor





class     lowerCAmelCase__     (				SCREAMING_SNAKE_CASE_			):


		'''simple docstring'''






		def   _snake_case       (       self     :     Optional[int]		)      ->	Tuple:
				_lowerCamelCase				   =  self.config_class(**self.inputs_dict		)
				self.parent.assertTrue(hasattr(snake_case__     ,  'hidden_sizes'		)		)
				self.parent.assertTrue(hasattr(snake_case__     ,  'neck_hidden_sizes'		)		)
				self.parent.assertTrue(hasattr(snake_case__     ,  'num_attention_heads'		)		)





class     lowerCAmelCase__     :


		'''simple docstring'''






		def __init__(       self     :     Tuple     ,  snake_case__     :     int     ,  snake_case__     :     Union[str, Any]=1_3     ,  snake_case__     :     int=3_2     ,  snake_case__     :     Tuple=2     ,  snake_case__     :     Optional[Any]=3     ,  snake_case__     :     Dict=6_4_0     ,  snake_case__     :     str=4     ,  snake_case__     :     Union[str, Any]="silu"     ,  snake_case__     :     Any=3     ,  snake_case__     :     int=3_2     ,  snake_case__     :     List[Any]=0.1     ,  snake_case__     :     Optional[int]=0.1     ,  snake_case__     :     int=0.1     ,  snake_case__     :     List[Any]=0.02     ,  snake_case__     :     Optional[Any]=True     ,  snake_case__     :     List[str]=True     ,  snake_case__     :     List[Any]=1_0     ,  snake_case__     :     Union[str, Any]=None     ,  )      ->	Dict:
				_lowerCamelCase				   =  parent
				_lowerCamelCase				   =  batch_size
				_lowerCamelCase				   =  image_size
				_lowerCamelCase				   =  patch_size
				_lowerCamelCase				   =  num_channels
				_lowerCamelCase				   =  last_hidden_size
				_lowerCamelCase				   =  num_attention_heads
				_lowerCamelCase				   =  hidden_act
				_lowerCamelCase				   =  conv_kernel_size
				_lowerCamelCase				   =  output_stride
				_lowerCamelCase				   =  hidden_dropout_prob
				_lowerCamelCase				   =  attention_probs_dropout_prob
				_lowerCamelCase				   =  classifier_dropout_prob
				_lowerCamelCase				   =  use_labels
				_lowerCamelCase				   =  is_training
				_lowerCamelCase				   =  num_labels
				_lowerCamelCase				   =  initializer_range
				_lowerCamelCase				   =  scope
		def   _snake_case       (       self     :     int		)      ->	Union[str, Any]:
				_lowerCamelCase				   =  floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]		)

				_lowerCamelCase				   =  None
				_lowerCamelCase				   =  None
				if self.use_labels:
						_lowerCamelCase				   =  ids_tensor([self.batch_size]     ,  self.num_labels		)
						_lowerCamelCase				   =  ids_tensor([self.batch_size, self.image_size, self.image_size]     ,  self.num_labels		)

				_lowerCamelCase				   =  self.get_config()

				return config, pixel_values, labels, pixel_labels
		def   _snake_case       (       self     :     Any		)      ->	List[str]:
				return MobileViTConfig(
				    image_size=self.image_size     ,  patch_size=self.patch_size     ,  num_channels=self.num_channels     ,  num_attention_heads=self.num_attention_heads     ,  hidden_act=self.hidden_act     ,  conv_kernel_size=self.conv_kernel_size     ,  output_stride=self.output_stride     ,  hidden_dropout_prob=self.hidden_dropout_prob     ,  attention_probs_dropout_prob=self.attention_probs_dropout_prob     ,  classifier_dropout_prob=self.classifier_dropout_prob     ,  initializer_range=self.initializer_range     ,  )
		def   _snake_case       (       self     :     int     ,  snake_case__     :     Dict     ,  snake_case__     :     List[Any]     ,  snake_case__     :     Tuple     ,  snake_case__     :     Optional[int]		)      ->	Optional[Any]:
				_lowerCamelCase				   =  MobileViTModel(config=snake_case__		)
				model.to(snake_case__		)
				model.eval()
				_lowerCamelCase				   =  model(snake_case__		)
				self.parent.assertEqual(
				    result.last_hidden_state.shape     ,  (
				        self.batch_size,
				        self.last_hidden_size,
				        self.image_size // self.output_stride,
				        self.image_size // self.output_stride,
				    )     ,  )
		def   _snake_case       (       self     :     List[Any]     ,  snake_case__     :     int     ,  snake_case__     :     Optional[Any]     ,  snake_case__     :     List[Any]     ,  snake_case__     :     Optional[Any]		)      ->	str:
				_lowerCamelCase				   =  self.num_labels
				_lowerCamelCase				   =  MobileViTForImageClassification(snake_case__		)
				model.to(snake_case__		)
				model.eval()
				_lowerCamelCase				   =  model(snake_case__     ,  labels=snake_case__		)
				self.parent.assertEqual(result.logits.shape     ,  (self.batch_size, self.num_labels)		)
		def   _snake_case       (       self     :     Optional[int]     ,  snake_case__     :     List[str]     ,  snake_case__     :     Dict     ,  snake_case__     :     List[str]     ,  snake_case__     :     Optional[int]		)      ->	Dict:
				_lowerCamelCase				   =  self.num_labels
				_lowerCamelCase				   =  MobileViTForSemanticSegmentation(snake_case__		)
				model.to(snake_case__		)
				model.eval()
				_lowerCamelCase				   =  model(snake_case__		)
				self.parent.assertEqual(
				    result.logits.shape     ,  (
				        self.batch_size,
				        self.num_labels,
				        self.image_size // self.output_stride,
				        self.image_size // self.output_stride,
				    )     ,  )
				_lowerCamelCase				   =  model(snake_case__     ,  labels=snake_case__		)
				self.parent.assertEqual(
				    result.logits.shape     ,  (
				        self.batch_size,
				        self.num_labels,
				        self.image_size // self.output_stride,
				        self.image_size // self.output_stride,
				    )     ,  )



		def   _snake_case       (       self     :     Dict		)      ->	str:
				_lowerCamelCase				   =  self.prepare_config_and_inputs()
				_lowerCamelCase   ,							_lowerCamelCase   ,							_lowerCamelCase   ,							_lowerCamelCase				   =  config_and_inputs
				_lowerCamelCase				   =  {'pixel_values': pixel_values}
				return config, inputs_dict





@require_torch
class     lowerCAmelCase__     (				SCREAMING_SNAKE_CASE_     ,SCREAMING_SNAKE_CASE_     ,unittest.TestCase			):


		'''simple docstring'''






		lowerCAmelCase_     =   (
		    (MobileViTModel, MobileViTForImageClassification, MobileViTForSemanticSegmentation)
		    if is_torch_available()
		    else ()
		)
		lowerCAmelCase_     =   (
		    {
		        'feature-extraction': MobileViTModel,
		        'image-classification': MobileViTForImageClassification,
		        'image-segmentation': MobileViTForSemanticSegmentation,
		    }
		    if is_torch_available()
		    else {}
		)

		lowerCAmelCase_     =   False
		lowerCAmelCase_     =   False
		lowerCAmelCase_     =   False
		lowerCAmelCase_     =   False
		def   _snake_case       (       self     :     Tuple		)      ->	Tuple:
				_lowerCamelCase				   =  MobileViTModelTester(self		)
				_lowerCamelCase				   =  MobileViTConfigTester(self     ,  config_class=snake_case__     ,  has_text_modality=snake_case__		)
		def   _snake_case       (       self     :     List[Any]		)      ->	Any:
				self.config_tester.run_common_tests()
		@unittest.skip(reason='MobileViT does not use inputs_embeds'		)
		def   _snake_case       (       self     :     Any		)      ->	Optional[Any]:
				pass
		@unittest.skip(reason='MobileViT does not support input and output embeddings'		)
		def   _snake_case       (       self     :     Dict		)      ->	int:
				pass
		@unittest.skip(reason='MobileViT does not output attentions'		)
		def   _snake_case       (       self     :     List[Any]		)      ->	Tuple:
				pass
		def   _snake_case       (       self     :     Any		)      ->	Any:
				_lowerCamelCase   ,							_lowerCamelCase				   =  self.model_tester.prepare_config_and_inputs_for_common()

				for model_class in self.all_model_classes:
						_lowerCamelCase				   =  model_class(snake_case__		)
						_lowerCamelCase				   =  inspect.signature(model.forward		)
						# signature.parameters is an OrderedDict => so arg_names order is deterministic
						_lowerCamelCase				   =  [*signature.parameters.keys()]

						_lowerCamelCase				   =  ['pixel_values']
						self.assertListEqual(arg_names[:1]     ,  snake_case__		)
		@unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.'		)
		def   _snake_case       (       self     :     Any		)      ->	Optional[int]:
				pass
		def   _snake_case       (       self     :     List[str]		)      ->	int:
				_lowerCamelCase				   =  self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_model(*snake_case__		)
		def   _snake_case       (       self     :     Optional[Any]		)      ->	Dict:
				def check_hidden_states_output(snake_case__     :     Union[str, Any]     ,  snake_case__     :     Dict     ,  snake_case__     :     List[Any]		):
						_lowerCamelCase				   =  model_class(snake_case__		)
						model.to(snake_case__		)
						model.eval()

						with torch.no_grad():
								_lowerCamelCase				   =  model(**self._prepare_for_class(snake_case__     ,  snake_case__		)		)

						_lowerCamelCase				   =  outputs.hidden_states

						_lowerCamelCase				   =  5
						self.assertEqual(len(snake_case__		)     ,  snake_case__		)

						# MobileViT's feature maps are of shape (batch_size, num_channels, height, width)
						# with the width and height being successively divided by 2.
						_lowerCamelCase				   =  2
						for i in range(len(snake_case__		)		):
								self.assertListEqual(
								    list(hidden_states[i].shape[-2:]		)     ,  [self.model_tester.image_size // divisor, self.model_tester.image_size // divisor]     ,  )
								divisor *= 2

						self.assertEqual(self.model_tester.output_stride     ,  divisor // 2		)

				_lowerCamelCase   ,							_lowerCamelCase				   =  self.model_tester.prepare_config_and_inputs_for_common()

				for model_class in self.all_model_classes:
						_lowerCamelCase				   =  True
						check_hidden_states_output(snake_case__     ,  snake_case__     ,  snake_case__		)

						# check that output_hidden_states also work using config
						del inputs_dict["output_hidden_states"]
						_lowerCamelCase				   =  True

						check_hidden_states_output(snake_case__     ,  snake_case__     ,  snake_case__		)
		def   _snake_case       (       self     :     Any		)      ->	str:
				_lowerCamelCase				   =  self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_for_image_classification(*snake_case__		)
		def   _snake_case       (       self     :     Optional[Any]		)      ->	List[str]:
				_lowerCamelCase				   =  self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_for_semantic_segmentation(*snake_case__		)



		@slow
		def   _snake_case       (       self     :     Tuple		)      ->	Any:
				for model_name in MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
						_lowerCamelCase				   =  MobileViTModel.from_pretrained(snake_case__		)
						self.assertIsNotNone(snake_case__		)



def 	lowerCamelCase					(	)   ->    List[str]:
		_lowerCamelCase				   =  Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'							)
		return image





@require_torch
@require_vision
class     lowerCAmelCase__     (				unittest.TestCase			):


		'''simple docstring'''






		@cached_property
		def   _snake_case       (       self     :     Optional[int]		)      ->	Any:
				return MobileViTImageProcessor.from_pretrained('apple/mobilevit-xx-small'		) if is_vision_available() else None
		@slow
		def   _snake_case       (       self     :     Union[str, Any]		)      ->	Optional[int]:
				_lowerCamelCase				   =  MobileViTForImageClassification.from_pretrained('apple/mobilevit-xx-small'		).to(snake_case__		)

				_lowerCamelCase				   =  self.default_image_processor
				_lowerCamelCase				   =  prepare_img()
				_lowerCamelCase				   =  image_processor(images=snake_case__     ,  return_tensors='pt'		).to(snake_case__		)

				# forward pass
				with torch.no_grad():
						_lowerCamelCase				   =  model(**snake_case__		)

				# verify the logits
				_lowerCamelCase				   =  torch.Size((1, 1_0_0_0)		)
				self.assertEqual(outputs.logits.shape     ,  snake_case__		)

				_lowerCamelCase				   =  torch.tensor([-1.9364, -1.2327, -0.4653]		).to(snake_case__		)

				self.assertTrue(torch.allclose(outputs.logits[0, :3]     ,  snake_case__     ,  atol=1e-4		)		)
		@slow
		def   _snake_case       (       self     :     Tuple		)      ->	Tuple:
				_lowerCamelCase				   =  MobileViTForSemanticSegmentation.from_pretrained('apple/deeplabv3-mobilevit-xx-small'		)
				_lowerCamelCase				   =  model.to(snake_case__		)

				_lowerCamelCase				   =  MobileViTImageProcessor.from_pretrained('apple/deeplabv3-mobilevit-xx-small'		)

				_lowerCamelCase				   =  prepare_img()
				_lowerCamelCase				   =  image_processor(images=snake_case__     ,  return_tensors='pt'		).to(snake_case__		)

				# forward pass
				with torch.no_grad():
						_lowerCamelCase				   =  model(**snake_case__		)
				_lowerCamelCase				   =  outputs.logits

				# verify the logits
				_lowerCamelCase				   =  torch.Size((1, 2_1, 3_2, 3_2)		)
				self.assertEqual(logits.shape     ,  snake_case__		)

				_lowerCamelCase				   =  torch.tensor(
				    [
				        [[6.9713, 6.9786, 7.2422], [7.2893, 7.2825, 7.4446], [7.6580, 7.8797, 7.9420]],
				        [[-10.6869, -10.3250, -10.3471], [-10.4228, -9.9868, -9.7132], [-11.0405, -11.0221, -10.7318]],
				        [[-3.3089, -2.8539, -2.6740], [-3.2706, -2.5621, -2.5108], [-3.2534, -2.6615, -2.6651]],
				    ]     ,  device=snake_case__     ,  )

				self.assertTrue(torch.allclose(logits[0, :3, :3, :3]     ,  snake_case__     ,  atol=1e-4		)		)



		@slow
		def   _snake_case       (       self     :     List[str]		)      ->	Optional[int]:
				_lowerCamelCase				   =  MobileViTForSemanticSegmentation.from_pretrained('apple/deeplabv3-mobilevit-xx-small'		)
				_lowerCamelCase				   =  model.to(snake_case__		)

				_lowerCamelCase				   =  MobileViTImageProcessor.from_pretrained('apple/deeplabv3-mobilevit-xx-small'		)

				_lowerCamelCase				   =  prepare_img()
				_lowerCamelCase				   =  image_processor(images=snake_case__     ,  return_tensors='pt'		).to(snake_case__		)

				# forward pass
				with torch.no_grad():
						_lowerCamelCase				   =  model(**snake_case__		)

				_lowerCamelCase				   =  outputs.logits.detach().cpu()

				_lowerCamelCase				   =  image_processor.post_process_semantic_segmentation(outputs=snake_case__     ,  target_sizes=[(5_0, 6_0)]		)
				_lowerCamelCase				   =  torch.Size((5_0, 6_0)		)
				self.assertEqual(segmentation[0].shape     ,  snake_case__		)

				_lowerCamelCase				   =  image_processor.post_process_semantic_segmentation(outputs=snake_case__		)
				_lowerCamelCase				   =  torch.Size((3_2, 3_2)		)
				self.assertEqual(segmentation[0].shape     ,  snake_case__		)
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     lowerCAmelCase__     (				nn.Module			):


		'''simple docstring'''






		def __init__(       self     :     Dict     ,  snake_case__     :     int     ,  snake_case__     :     int     ,  snake_case__     :     int     ,  snake_case__     :     Tuple=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     ,  )      ->	Dict:
				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   _snake_case       (       self     :     str     ,  snake_case__     :     Optional[int]     ,  snake_case__     :     int		)      ->	Optional[Any]:
				# Sets chunk feed-forward
				_lowerCamelCase				   =  chunk_size
				_lowerCamelCase				   =  dim



		def   _snake_case       (       self     :     Union[str, 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     ,  )      ->	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				   =  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     lowerCAmelCase__     (				nn.Module			):


		'''simple docstring'''






		def __init__(       self     :     Union[str, Any]     ,  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     ,  )      ->	Optional[int]:
				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   _snake_case       (       self     :     Tuple     ,  snake_case__     :     List[Any]		)      ->	Optional[int]:
				for module in self.net:
						_lowerCamelCase				   =  module(snake_case__		)
				return hidden_states





class     lowerCAmelCase__     (				nn.Module			):


		'''simple docstring'''






		def __init__(       self     :     str     ,  snake_case__     :     int     ,  snake_case__     :     int     ,  snake_case__     :     str = "none"		)      ->	Any:
				super().__init__()
				_lowerCamelCase				   =  nn.Linear(snake_case__     ,  snake_case__		)
				_lowerCamelCase				   =  approximate
		def   _snake_case       (       self     :     List[Any]     ,  snake_case__     :     List[Any]		)      ->	int:
				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   _snake_case       (       self     :     Optional[int]     ,  snake_case__     :     Union[str, Any]		)      ->	str:
				_lowerCamelCase				   =  self.proj(snake_case__		)
				_lowerCamelCase				   =  self.gelu(snake_case__		)
				return hidden_states





class     lowerCAmelCase__     (				nn.Module			):


		'''simple docstring'''






		def __init__(       self     :     Dict     ,  snake_case__     :     int     ,  snake_case__     :     int		)      ->	List[Any]:
				super().__init__()
				_lowerCamelCase				   =  nn.Linear(snake_case__     ,  dim_out * 2		)
		def   _snake_case       (       self     :     Optional[Any]     ,  snake_case__     :     Optional[int]		)      ->	Optional[Any]:
				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   _snake_case       (       self     :     List[str]     ,  snake_case__     :     Optional[Any]		)      ->	Optional[int]:
				_lowerCamelCase   ,							_lowerCamelCase				   =  self.proj(snake_case__		).chunk(2     ,  dim=-1		)
				return hidden_states * self.gelu(snake_case__		)





class     lowerCAmelCase__     (				nn.Module			):


		'''simple docstring'''






		def __init__(       self     :     Dict     ,  snake_case__     :     int     ,  snake_case__     :     int		)      ->	Tuple:
				super().__init__()
				_lowerCamelCase				   =  nn.Linear(snake_case__     ,  snake_case__		)



		def   _snake_case       (       self     :     Optional[Any]     ,  snake_case__     :     List[Any]		)      ->	Optional[int]:
				_lowerCamelCase				   =  self.proj(snake_case__		)
				return x * torch.sigmoid(1.702 * x		)





class     lowerCAmelCase__     (				nn.Module			):


		'''simple docstring'''






		def __init__(       self     :     Optional[Any]     ,  snake_case__     :     Tuple     ,  snake_case__     :     Any		)      ->	Dict:
				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   _snake_case       (       self     :     Tuple     ,  snake_case__     :     str     ,  snake_case__     :     Dict		)      ->	Optional[int]:
				_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     lowerCAmelCase__     (				nn.Module			):


		'''simple docstring'''






		def __init__(       self     :     Any     ,  snake_case__     :     Optional[Any]     ,  snake_case__     :     Union[str, Any]		)      ->	Dict:
				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   _snake_case       (       self     :     Dict     ,  snake_case__     :     Tuple     ,  snake_case__     :     str     ,  snake_case__     :     str     ,  snake_case__     :     List[Any]=None		)      ->	int:
				_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     lowerCAmelCase__     (				nn.Module			):


		'''simple docstring'''






		def __init__(       self     :     Tuple     ,  snake_case__     :     int     ,  snake_case__     :     int     ,  snake_case__     :     int     ,  snake_case__     :     Optional[str] = None     ,  snake_case__     :     float = 1e-5		)      ->	int:
				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   _snake_case       (       self     :     Union[str, Any]     ,  snake_case__     :     int     ,  snake_case__     :     Optional[Any]		)      ->	Union[str, Any]:
				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