




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 a :
						"""simple docstring"""

						def __init__( self :     int				,							lowerCamelCase__ :     List[str]				,							lowerCamelCase__ :     Optional[Any]=13				,							lowerCamelCase__ :     Optional[Any]=30				,							lowerCamelCase__ :     Union[str, Any]=2				,							lowerCamelCase__ :     int=3				,							lowerCamelCase__ :     int=True				,							lowerCamelCase__ :     List[Any]=True				,							lowerCamelCase__ :     Any=32				,							lowerCamelCase__ :     Optional[Any]=5				,							lowerCamelCase__ :     Any=4				,							lowerCamelCase__ :     str=37				,							lowerCamelCase__ :     Tuple="gelu"				,							lowerCamelCase__ :     str=0.1				,							lowerCamelCase__ :     List[str]=0.1				,							lowerCamelCase__ :     str=10				,							lowerCamelCase__ :     List[str]=0.0_2				,							lowerCamelCase__ :     str=None				,							)    ->						Dict:
													"""simple docstring"""


													__lowercase      =    parent
													__lowercase      =    batch_size
													__lowercase      =    image_size
													__lowercase      =    patch_size
													__lowercase      =    num_channels
													__lowercase      =    is_training
													__lowercase      =    use_labels
													__lowercase      =    hidden_size
													__lowercase      =    num_hidden_layers
													__lowercase      =    num_attention_heads
													__lowercase      =    intermediate_size
													__lowercase      =    hidden_act
													__lowercase      =    hidden_dropout_prob
													__lowercase      =    attention_probs_dropout_prob
													__lowercase      =    type_sequence_label_size
													__lowercase      =    initializer_range
													__lowercase      =    scope

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






						def     UpperCAmelCase_      ( self :     List[Any]				)    ->						Optional[int]:
													"""simple docstring"""


													__lowercase      =    floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]				)

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

													__lowercase      =    self.get_config()

													return config, pixel_values, labels






						def     UpperCAmelCase_      ( self :     List[str]				)    ->						int:
													"""simple docstring"""


													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     UpperCAmelCase_      ( self :     Optional[int]				,							lowerCamelCase__ :     str				,							lowerCamelCase__ :     Optional[int]				,							lowerCamelCase__ :     Dict				)    ->						Dict:
													"""simple docstring"""


													__lowercase      =    ViTMSNModel(config=lowerCamelCase__				)
													model.to(lowerCamelCase__				)
													model.eval()
													__lowercase      =    model(lowerCamelCase__				)
													self.parent.assertEqual(result.last_hidden_state.shape				,							(self.batch_size, self.seq_length, self.hidden_size)				)






						def     UpperCAmelCase_      ( self :     Any				,							lowerCamelCase__ :     Dict				,							lowerCamelCase__ :     List[Any]				,							lowerCamelCase__ :     List[str]				)    ->						Optional[Any]:
													"""simple docstring"""


													__lowercase      =    self.type_sequence_label_size
													__lowercase      =    ViTMSNForImageClassification(lowerCamelCase__				)
													model.to(lowerCamelCase__				)
													model.eval()
													__lowercase      =    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
													__lowercase      =    1
													__lowercase      =    ViTMSNForImageClassification(lowerCamelCase__				)
													model.to(lowerCamelCase__				)
													model.eval()

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






						def     UpperCAmelCase_      ( self :     int				)    ->						str:
													"""simple docstring"""


													__lowercase      =    self.prepare_config_and_inputs()
													__lowercase     ,     __lowercase     ,     __lowercase      =    config_and_inputs
													__lowercase      =    {'''pixel_values''': pixel_values}
													return config, inputs_dict







@require_torch
class a (     __SCREAMING_SNAKE_CASE       ,						__SCREAMING_SNAKE_CASE       ,						unittest.TestCase  ):
						"""simple docstring"""

						UpperCamelCase_	:       Tuple       	=		(ViTMSNModel, ViTMSNForImageClassification) if is_torch_available() else ()
						UpperCamelCase_	:       int       	=		(
						    {'feature-extraction': ViTMSNModel, 'image-classification': ViTMSNForImageClassification}
						    if is_torch_available()
						    else {}
						)

						UpperCamelCase_	:       Any       	=		False
						UpperCamelCase_	:       str       	=		False
						UpperCamelCase_	:       str       	=		False
						UpperCamelCase_	:       List[Any]       	=		False






						def     UpperCAmelCase_      ( self :     str				)    ->						Any:
													"""simple docstring"""


													__lowercase      =    ViTMSNModelTester(self				)
													__lowercase      =    ConfigTester(self				,							config_class=lowerCamelCase__				,							has_text_modality=lowerCamelCase__				,							hidden_size=37				)






						def     UpperCAmelCase_      ( self :     List[str]				)    ->						int:
													"""simple docstring"""


													self.config_tester.run_common_tests()






						@unittest.skip(reason='''ViTMSN does not use inputs_embeds'''				)
						def     UpperCAmelCase_      ( self :     List[str]				)    ->						Optional[Any]:
													"""simple docstring"""


													pass






						def     UpperCAmelCase_      ( self :     int				)    ->						Tuple:
													"""simple docstring"""


													__lowercase     ,     __lowercase      =    self.model_tester.prepare_config_and_inputs_for_common()

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






						def     UpperCAmelCase_      ( self :     Optional[Any]				)    ->						str:
													"""simple docstring"""


													__lowercase     ,     __lowercase      =    self.model_tester.prepare_config_and_inputs_for_common()

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

																				__lowercase      =    ['''pixel_values''']
																				self.assertListEqual(arg_names[:1]				,							lowerCamelCase__				)






						def     UpperCAmelCase_      ( self :     Optional[int]				)    ->						List[str]:
													"""simple docstring"""


													__lowercase      =    self.model_tester.prepare_config_and_inputs()
													self.model_tester.create_and_check_model(*lowerCamelCase__				)






						def     UpperCAmelCase_      ( self :     Tuple				)    ->						str:
													"""simple docstring"""


													__lowercase      =    self.model_tester.prepare_config_and_inputs()
													self.model_tester.create_and_check_for_image_classification(*lowerCamelCase__				)






						@slow
						def     UpperCAmelCase_      ( self :     str				)    ->						List[str]:
													"""simple docstring"""


													for model_name in VIT_MSN_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																				__lowercase      =    ViTMSNModel.from_pretrained(lowerCamelCase__				)
																				self.assertIsNotNone(lowerCamelCase__				)







def 		_A(       )    -> Union[str, Any]:
							'''simple docstring'''


							__lowercase      =    Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''				)
							return image







@require_torch
@require_vision
class a (     unittest.TestCase  ):
						"""simple docstring"""

						@cached_property
						def     UpperCAmelCase_      ( self :     int				)    ->						List[Any]:
													"""simple docstring"""


													return ViTImageProcessor.from_pretrained('''facebook/vit-msn-small'''				) if is_vision_available() else None






						@slow
						def     UpperCAmelCase_      ( self :     Optional[Any]				)    ->						Optional[int]:
													"""simple docstring"""


													torch.manual_seed(2				)
													__lowercase      =    ViTMSNForImageClassification.from_pretrained('''facebook/vit-msn-small'''				).to(lowerCamelCase__				)

													__lowercase      =    self.default_image_processor
													__lowercase      =    prepare_img()
													__lowercase      =    image_processor(images=lowerCamelCase__				,							return_tensors='''pt'''				).to(lowerCamelCase__				)

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

													# verify the logits
													__lowercase      =    torch.Size((1, 1_000)				)
													self.assertEqual(outputs.logits.shape				,							lowerCamelCase__				)

													__lowercase      =    torch.tensor([-0.0_8_0_3, -0.4_4_5_4, -0.2_3_7_5]				).to(lowerCamelCase__				)

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












# This code is adapted from OpenAI's release
# https://github.com/openai/human-eval/blob/master/human_eval/execution.py

import contextlib
import faulthandler
import io
import multiprocessing
import os
import platform
import signal
import tempfile







def 		_A(       UpperCamelCase__							:			Any				,       UpperCamelCase__							:			int				,       UpperCamelCase__							:			List[Any]				,       UpperCamelCase__							:			int				)    -> List[Any]:
							'''simple docstring'''


							__lowercase      =    multiprocessing.Manager()
							__lowercase      =    manager.list()

							__lowercase      =    multiprocessing.Process(target=UpperCamelCase__				,       args=(check_program, result, timeout)				)
							p.start()
							p.join(timeout=timeout + 1				)
							if p.is_alive():
														p.kill()

							if not result:
														result.append('''timed out'''				)

							return {
							    "task_id": task_id,
							    "passed": result[0] == "passed",
							    "result": result[0],
							    "completion_id": completion_id,
							}







def 		_A(       UpperCamelCase__							:			int				,       UpperCamelCase__							:			List[Any]				,       UpperCamelCase__							:			Optional[int]				)    -> List[Any]:
							'''simple docstring'''


							with create_tempdir():
														# These system calls are needed when cleaning up tempdir.
														import os
														import shutil

														__lowercase      =    shutil.rmtree
														__lowercase      =    os.rmdir
														__lowercase      =    os.chdir

														# Disable functionalities that can make destructive changes to the test.
														reliability_guard()

														# Run program.
														try:
																					__lowercase      =    {}
																					with swallow_io():
																												with time_limit(UpperCamelCase__				):
																																			exec(UpperCamelCase__				,       UpperCamelCase__				)
																					result.append('''passed'''				)
														except TimeoutException:
																					result.append('''timed out'''				)
														except BaseException as e:
																					result.append(F'failed: {e}'				)

														# Needed for cleaning up.
														__lowercase      =    rmtree
														__lowercase      =    rmdir
														__lowercase      =    chdir







@contextlib.contextmanager
def 		_A(       UpperCamelCase__							:			Union[str, Any]				)    -> Optional[int]:
							'''simple docstring'''


							def signal_handler(UpperCamelCase__							:			List[str]				,       UpperCamelCase__							:			Optional[Any]				):
														raise TimeoutException('''Timed out!'''				)

							signal.setitimer(signal.ITIMER_REAL				,       UpperCamelCase__				)
							signal.signal(signal.SIGALRM				,       UpperCamelCase__				)
							try:
														yield
							finally:
														signal.setitimer(signal.ITIMER_REAL				,       0				)







@contextlib.contextmanager
def 		_A(       )    -> Any:
							'''simple docstring'''


							__lowercase      =    WriteOnlyStringIO()
							with contextlib.redirect_stdout(UpperCamelCase__				):
														with contextlib.redirect_stderr(UpperCamelCase__				):
																					with redirect_stdin(UpperCamelCase__				):
																												yield







@contextlib.contextmanager
def 		_A(       )    -> Tuple:
							'''simple docstring'''


							with tempfile.TemporaryDirectory() as dirname:
														with chdir(UpperCamelCase__				):
																					yield dirname







class a (     __SCREAMING_SNAKE_CASE  ):
						"""simple docstring"""

						pass







class a (     io.StringIO  ):
						"""simple docstring"""

						def     UpperCAmelCase_      ( self :     List[str]				,							*lowerCamelCase__ :     str				,							**lowerCamelCase__ :     str				)    ->						Tuple:
													"""simple docstring"""


													raise OSError






						def     UpperCAmelCase_      ( self :     List[str]				,							*lowerCamelCase__ :     List[str]				,							**lowerCamelCase__ :     Dict				)    ->						List[Any]:
													"""simple docstring"""


													raise OSError






						def     UpperCAmelCase_      ( self :     List[str]				,							*lowerCamelCase__ :     Dict				,							**lowerCamelCase__ :     Dict				)    ->						Optional[int]:
													"""simple docstring"""


													raise OSError






						def     UpperCAmelCase_      ( self :     Tuple				,							*lowerCamelCase__ :     Optional[Any]				,							**lowerCamelCase__ :     Tuple				)    ->						Optional[Any]:
													"""simple docstring"""


													return False







class a (     contextlib._RedirectStream  ):  # type: ignore
						"""simple docstring"""

						UpperCamelCase_	:       str       	=		'stdin'







@contextlib.contextmanager
def 		_A(       UpperCamelCase__							:			int				)    -> Any:
							'''simple docstring'''


							if root == ".":
														yield
														return
							__lowercase      =    os.getcwd()
							os.chdir(UpperCamelCase__				)
							try:
														yield
							except BaseException as exc:
														raise exc
							finally:
														os.chdir(UpperCamelCase__				)







def 		_A(       UpperCamelCase__							:			Optional[Any]=None				)    -> Any:
							'''simple docstring'''


							if maximum_memory_bytes is not None:
														import resource

														resource.setrlimit(resource.RLIMIT_AS				,       (maximum_memory_bytes, maximum_memory_bytes)				)
														resource.setrlimit(resource.RLIMIT_DATA				,       (maximum_memory_bytes, maximum_memory_bytes)				)
														if not platform.uname().system == "Darwin":
																					resource.setrlimit(resource.RLIMIT_STACK				,       (maximum_memory_bytes, maximum_memory_bytes)				)

							faulthandler.disable()

							import builtins

							__lowercase      =    None
							__lowercase      =    None

							import os

							__lowercase      =    '''1'''

							__lowercase      =    None
							__lowercase      =    None
							__lowercase      =    None
							__lowercase      =    None
							__lowercase      =    None
							__lowercase      =    None
							__lowercase      =    None
							__lowercase      =    None
							__lowercase      =    None
							__lowercase      =    None
							__lowercase      =    None
							__lowercase      =    None
							__lowercase      =    None
							__lowercase      =    None
							__lowercase      =    None
							__lowercase      =    None
							__lowercase      =    None
							__lowercase      =    None
							__lowercase      =    None
							__lowercase      =    None
							__lowercase      =    None
							__lowercase      =    None
							__lowercase      =    None
							__lowercase      =    None
							__lowercase      =    None
							__lowercase      =    None
							__lowercase      =    None

							import shutil

							__lowercase      =    None
							__lowercase      =    None
							__lowercase      =    None

							import subprocess

							__lowercase      =    None  # type: ignore

							__lowercase      =    None

							import sys

							__lowercase      =    None
							__lowercase      =    None
							__lowercase      =    None
							__lowercase      =    None
							__lowercase      =    None






