




"""simple docstring"""







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					):


						def __init__(							self				:			Optional[Any]						,						lowerCAmelCase				:			int						,						lowerCAmelCase				:			int						,						lowerCAmelCase				:			int						,						lowerCAmelCase				:			Dict=0.0						,						lowerCAmelCase				:			Optional[int] = None						,						lowerCAmelCase				:			str = "geglu"						,						lowerCAmelCase				:			Optional[int] = None						,						lowerCAmelCase				:			bool = False						,						lowerCAmelCase				:			bool = False						,						lowerCAmelCase				:			bool = False						,						lowerCAmelCase				:			bool = False						,						lowerCAmelCase				:			bool = True						,						lowerCAmelCase				:			str = "layer_norm"						,						lowerCAmelCase				:			bool = False						,						):
										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(__a						,						__a					)
										elif self.use_ada_layer_norm_zero:
														lowerCAmelCase  =				AdaLayerNormZero(__a						,						__a					)
										else:
														lowerCAmelCase  =				nn.LayerNorm(__a						,						elementwise_affine=__a					)
										lowerCAmelCase  =				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  =				(
														    AdaLayerNorm(__a						,						__a					)
														    if self.use_ada_layer_norm
														    else nn.LayerNorm(__a						,						elementwise_affine=__a					)
														)
														lowerCAmelCase  =				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  =				None
														lowerCAmelCase  =				None

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

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


						def   __lowercase (							self				:			List[str]						,						lowerCAmelCase				:			Optional[int]						,						lowerCAmelCase				:			int					):
										# Sets chunk feed-forward
										lowerCAmelCase  =				chunk_size
										lowerCAmelCase  =				dim




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

										lowerCAmelCase  =				cross_attention_kwargs if cross_attention_kwargs is not None else {}

										lowerCAmelCase  =				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  =				gate_msa.unsqueeze(1					) * attn_output
										lowerCAmelCase  =				attn_output + hidden_states

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

														lowerCAmelCase  =				self.attna(
														    __a						,						encoder_hidden_states=__a						,						attention_mask=__a						,						**__a						,						)
														lowerCAmelCase  =				attn_output + hidden_states

										# 3. Feed-forward
										lowerCAmelCase  =				self.norma(__a					)

										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(__a					) for hid_slice in norm_hidden_states.chunk(__a						,						dim=self._chunk_dim					)]						,						dim=self._chunk_dim						,						)
										else:
														lowerCAmelCase  =				self.ff(__a					)

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

										lowerCAmelCase  =				ff_output + hidden_states

										return hidden_states






class       SCREAMING_SNAKE_CASE__					(					nn.Module					):


						def __init__(							self				:			Optional[int]						,						lowerCAmelCase				:			int						,						lowerCAmelCase				:			Optional[int] = None						,						lowerCAmelCase				:			int = 4						,						lowerCAmelCase				:			float = 0.0						,						lowerCAmelCase				:			str = "geglu"						,						lowerCAmelCase				:			bool = False						,						):
										super().__init__()
										lowerCAmelCase  =				int(dim * mult					)
										lowerCAmelCase  =				dim_out if dim_out is not None else dim

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

										lowerCAmelCase  =				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   __lowercase (							self				:			Tuple						,						lowerCAmelCase				:			Tuple					):
										for module in self.net:
														lowerCAmelCase  =				module(__a					)
										return hidden_states






class       SCREAMING_SNAKE_CASE__					(					nn.Module					):


						def __init__(							self				:			int						,						lowerCAmelCase				:			int						,						lowerCAmelCase				:			int						,						lowerCAmelCase				:			str = "none"					):
										super().__init__()
										lowerCAmelCase  =				nn.Linear(__a						,						__a					)
										lowerCAmelCase  =				approximate


						def   __lowercase (							self				:			Optional[int]						,						lowerCAmelCase				:			int					):
										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   __lowercase (							self				:			List[str]						,						lowerCAmelCase				:			int					):
										lowerCAmelCase  =				self.proj(__a					)
										lowerCAmelCase  =				self.gelu(__a					)
										return hidden_states






class       SCREAMING_SNAKE_CASE__					(					nn.Module					):


						def __init__(							self				:			List[str]						,						lowerCAmelCase				:			int						,						lowerCAmelCase				:			int					):
										super().__init__()
										lowerCAmelCase  =				nn.Linear(__a						,						dim_out * 2					)


						def   __lowercase (							self				:			Any						,						lowerCAmelCase				:			Optional[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   __lowercase (							self				:			Tuple						,						lowerCAmelCase				:			Tuple					):
										lowerCAmelCase  =				self.proj(__a					).chunk(2						,						dim=-1					)
										return hidden_states * self.gelu(__a					)






class       SCREAMING_SNAKE_CASE__					(					nn.Module					):


						def __init__(							self				:			int						,						lowerCAmelCase				:			int						,						lowerCAmelCase				:			int					):
										super().__init__()
										lowerCAmelCase  =				nn.Linear(__a						,						__a					)




						def   __lowercase (							self				:			Union[str, Any]						,						lowerCAmelCase				:			Any					):
										lowerCAmelCase  =				self.proj(__a					)
										return x * torch.sigmoid(1.702 * x					)






class       SCREAMING_SNAKE_CASE__					(					nn.Module					):


						def __init__(							self				:			Dict						,						lowerCAmelCase				:			List[str]						,						lowerCAmelCase				:			Tuple					):
										super().__init__()
										lowerCAmelCase  =				nn.Embedding(__a						,						__a					)
										lowerCAmelCase  =				nn.SiLU()
										lowerCAmelCase  =				nn.Linear(__a						,						embedding_dim * 2					)
										lowerCAmelCase  =				nn.LayerNorm(__a						,						elementwise_affine=__a					)




						def   __lowercase (							self				:			Any						,						lowerCAmelCase				:			str						,						lowerCAmelCase				:			List[Any]					):
										lowerCAmelCase  =				self.linear(self.silu(self.emb(__a					)					)					)
										lowerCAmelCase  =				torch.chunk(__a						,						2					)
										lowerCAmelCase  =				self.norm(__a					) * (1 + scale) + shift
										return x






class       SCREAMING_SNAKE_CASE__					(					nn.Module					):


						def __init__(							self				:			Tuple						,						lowerCAmelCase				:			List[Any]						,						lowerCAmelCase				:			Tuple					):
										super().__init__()

										lowerCAmelCase  =				CombinedTimestepLabelEmbeddings(__a						,						__a					)

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




						def   __lowercase (							self				:			Optional[int]						,						lowerCAmelCase				:			str						,						lowerCAmelCase				:			Optional[Any]						,						lowerCAmelCase				:			Dict						,						lowerCAmelCase				:			Tuple=None					):
										lowerCAmelCase  =				self.linear(self.silu(self.emb(__a						,						__a						,						hidden_dtype=__a					)					)					)
										lowerCAmelCase  =				emb.chunk(6						,						dim=1					)
										lowerCAmelCase  =				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					):


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

										if act_fn is None:
														lowerCAmelCase  =				None
										else:
														lowerCAmelCase  =				get_activation(__a					)

										lowerCAmelCase  =				nn.Linear(__a						,						out_dim * 2					)




						def   __lowercase (							self				:			List[str]						,						lowerCAmelCase				:			Union[str, Any]						,						lowerCAmelCase				:			Any					):
										if self.act:
														lowerCAmelCase  =				self.act(__a					)
										lowerCAmelCase  =				self.linear(__a					)
										lowerCAmelCase  =				emb[:, :, None, None]
										lowerCAmelCase  =				emb.chunk(2						,						dim=1					)

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









"""simple docstring"""







import inspect
import unittest

from transformers import ViTMSNConfig
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 torch import nn

		from transformers import ViTMSNForImageClassification, ViTMSNModel
		from transformers.models.vit_msn.modeling_vit_msn import VIT_MSN_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
		from PIL import Image

		from transformers import ViTImageProcessor






class       SCREAMING_SNAKE_CASE__					:


						def __init__(							self				:			List[Any]						,						lowerCAmelCase				:			Tuple						,						lowerCAmelCase				:			Optional[int]=13						,						lowerCAmelCase				:			List[str]=30						,						lowerCAmelCase				:			Dict=2						,						lowerCAmelCase				:			Any=3						,						lowerCAmelCase				:			str=True						,						lowerCAmelCase				:			List[Any]=True						,						lowerCAmelCase				:			Dict=32						,						lowerCAmelCase				:			Dict=5						,						lowerCAmelCase				:			str=4						,						lowerCAmelCase				:			List[Any]=37						,						lowerCAmelCase				:			List[Any]="gelu"						,						lowerCAmelCase				:			List[Any]=0.1						,						lowerCAmelCase				:			List[Any]=0.1						,						lowerCAmelCase				:			Optional[int]=10						,						lowerCAmelCase				:			List[str]=0.02						,						lowerCAmelCase				:			List[str]=None						,						):
										lowerCAmelCase  =				parent
										lowerCAmelCase  =				batch_size
										lowerCAmelCase  =				image_size
										lowerCAmelCase  =				patch_size
										lowerCAmelCase  =				num_channels
										lowerCAmelCase  =				is_training
										lowerCAmelCase  =				use_labels
										lowerCAmelCase  =				hidden_size
										lowerCAmelCase  =				num_hidden_layers
										lowerCAmelCase  =				num_attention_heads
										lowerCAmelCase  =				intermediate_size
										lowerCAmelCase  =				hidden_act
										lowerCAmelCase  =				hidden_dropout_prob
										lowerCAmelCase  =				attention_probs_dropout_prob
										lowerCAmelCase  =				type_sequence_label_size
										lowerCAmelCase  =				initializer_range
										lowerCAmelCase  =				scope

										# in ViT MSN, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token)
										lowerCAmelCase  =				(image_size // patch_size) ** 2
										lowerCAmelCase  =				num_patches + 1


						def   __lowercase (							self				:			List[str]					):
										lowerCAmelCase  =				floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]					)

										lowerCAmelCase  =				None
										if self.use_labels:
														lowerCAmelCase  =				ids_tensor([self.batch_size]						,						self.type_sequence_label_size					)

										lowerCAmelCase  =				self.get_config()

										return config, pixel_values, labels


						def   __lowercase (							self				:			Tuple					):
										return ViTMSNConfig(
										    image_size=self.image_size						,						patch_size=self.patch_size						,						num_channels=self.num_channels						,						hidden_size=self.hidden_size						,						num_hidden_layers=self.num_hidden_layers						,						num_attention_heads=self.num_attention_heads						,						intermediate_size=self.intermediate_size						,						hidden_act=self.hidden_act						,						hidden_dropout_prob=self.hidden_dropout_prob						,						attention_probs_dropout_prob=self.attention_probs_dropout_prob						,						initializer_range=self.initializer_range						,						)


						def   __lowercase (							self				:			Any						,						lowerCAmelCase				:			Any						,						lowerCAmelCase				:			Tuple						,						lowerCAmelCase				:			Tuple					):
										lowerCAmelCase  =				ViTMSNModel(config=lowerCAmelCase					)
										model.to(lowerCAmelCase					)
										model.eval()
										lowerCAmelCase  =				model(lowerCAmelCase					)
										self.parent.assertEqual(result.last_hidden_state.shape						,						(self.batch_size, self.seq_length, self.hidden_size)					)


						def   __lowercase (							self				:			List[str]						,						lowerCAmelCase				:			int						,						lowerCAmelCase				:			str						,						lowerCAmelCase				:			int					):
										lowerCAmelCase  =				self.type_sequence_label_size
										lowerCAmelCase  =				ViTMSNForImageClassification(lowerCAmelCase					)
										model.to(lowerCAmelCase					)
										model.eval()
										lowerCAmelCase  =				model(lowerCAmelCase						,						labels=lowerCAmelCase					)
										print("""Pixel and labels shape: {pixel_values.shape}, {labels.shape}"""					)
										print("""Labels: {labels}"""					)
										self.parent.assertEqual(result.logits.shape						,						(self.batch_size, self.type_sequence_label_size)					)

										# test greyscale images
										lowerCAmelCase  =				1
										lowerCAmelCase  =				ViTMSNForImageClassification(lowerCAmelCase					)
										model.to(lowerCAmelCase					)
										model.eval()

										lowerCAmelCase  =				floats_tensor([self.batch_size, 1, self.image_size, self.image_size]					)
										lowerCAmelCase  =				model(lowerCAmelCase					)
										self.parent.assertEqual(result.logits.shape						,						(self.batch_size, self.type_sequence_label_size)					)




						def   __lowercase (							self				:			Optional[Any]					):
										lowerCAmelCase  =				self.prepare_config_and_inputs()
										lowerCAmelCase ,						lowerCAmelCase ,						lowerCAmelCase  =				config_and_inputs
										lowerCAmelCase  =				{"""pixel_values""": pixel_values}
										return config, inputs_dict






@require_torch
class       SCREAMING_SNAKE_CASE__					(					_a						,				_a						,				unittest.TestCase					):
						_a    						=						(ViTMSNModel, ViTMSNForImageClassification) if is_torch_available() else ()
						_a    						=						(
						    {'feature-extraction': ViTMSNModel, 'image-classification': ViTMSNForImageClassification}
						    if is_torch_available()
						    else {}
						)

						_a    						=						False
						_a    						=						False
						_a    						=						False
						_a    						=						False


						def   __lowercase (							self				:			Tuple					):
										lowerCAmelCase  =				ViTMSNModelTester(self					)
										lowerCAmelCase  =				ConfigTester(self						,						config_class=lowerCAmelCase						,						has_text_modality=lowerCAmelCase						,						hidden_size=37					)


						def   __lowercase (							self				:			Dict					):
										self.config_tester.run_common_tests()


						@unittest.skip(reason="""ViTMSN does not use inputs_embeds"""					)
						def   __lowercase (							self				:			Optional[Any]					):
										pass


						def   __lowercase (							self				:			int					):
										lowerCAmelCase ,						lowerCAmelCase  =				self.model_tester.prepare_config_and_inputs_for_common()

										for model_class in self.all_model_classes:
														lowerCAmelCase  =				model_class(lowerCAmelCase					)
														self.assertIsInstance(model.get_input_embeddings()						,						(nn.Module)					)
														lowerCAmelCase  =				model.get_output_embeddings()
														self.assertTrue(x is None or isinstance(lowerCAmelCase						,						nn.Linear					)					)


						def   __lowercase (							self				:			Optional[int]					):
										lowerCAmelCase ,						lowerCAmelCase  =				self.model_tester.prepare_config_and_inputs_for_common()

										for model_class in self.all_model_classes:
														lowerCAmelCase  =				model_class(lowerCAmelCase					)
														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]						,						lowerCAmelCase					)


						def   __lowercase (							self				:			Union[str, Any]					):
										lowerCAmelCase  =				self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_model(*lowerCAmelCase					)


						def   __lowercase (							self				:			Union[str, Any]					):
										lowerCAmelCase  =				self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_for_image_classification(*lowerCAmelCase					)




						@slow
						def   __lowercase (							self				:			Optional[Any]					):
										for model_name in VIT_MSN_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
														lowerCAmelCase  =				ViTMSNModel.from_pretrained(lowerCAmelCase					)
														self.assertIsNotNone(lowerCAmelCase					)





def 							lowercase					()     ->  Dict:


				'''simple docstring'''






				lowerCAmelCase  =				Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" )
				return image






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


						@cached_property
						def   __lowercase (							self				:			Dict					):
										return ViTImageProcessor.from_pretrained("""facebook/vit-msn-small"""					) if is_vision_available() else None




						@slow
						def   __lowercase (							self				:			Tuple					):
										torch.manual_seed(2					)
										lowerCAmelCase  =				ViTMSNForImageClassification.from_pretrained("""facebook/vit-msn-small"""					).to(lowerCAmelCase					)

										lowerCAmelCase  =				self.default_image_processor
										lowerCAmelCase  =				prepare_img()
										lowerCAmelCase  =				image_processor(images=lowerCAmelCase						,						return_tensors="""pt"""					).to(lowerCAmelCase					)

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

										# verify the logits
										lowerCAmelCase  =				torch.Size((1, 1000)					)
										self.assertEqual(outputs.logits.shape						,						lowerCAmelCase					)

										lowerCAmelCase  =				torch.tensor([-0.0803, -0.4454, -0.2375]					).to(lowerCAmelCase					)

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





