




"""simple docstring"""







import random
import timeit
from functools import wraps
from typing import Callable, Optional

from ..configuration_utils import PretrainedConfig
from ..models.auto.modeling_tf_auto import TF_MODEL_MAPPING, TF_MODEL_WITH_LM_HEAD_MAPPING
from ..utils import is_pyanvml_available, is_tf_available, logging
from .benchmark_utils import (
    Benchmark,
    Memory,
    MemorySummary,
    measure_peak_memory_cpu,
    start_memory_tracing,
    stop_memory_tracing,
)


if is_tf_available():
		import tensorflow as tf
		from tensorflow.python.framework.errors_impl import ResourceExhaustedError

		from .benchmark_args_tf import TensorFlowBenchmarkArguments

if is_pyanvml_available():
		import pyanvml.pyanvml as nvml

a      =							logging.get_logger(__name__)





def 							lowercase					(snake_case__   : bool      ,       snake_case__   : bool )     ->  Tuple:


				'''simple docstring'''






				def run_func(snake_case__   : Any ):
								@wraps(snake_case__ )
								def run_in_eager_mode(*snake_case__   : Optional[Any]      ,       **snake_case__   : int ):
												return func(*snake_case__      ,       **snake_case__ )

								@wraps(snake_case__ )
								@tf.function(experimental_compile=snake_case__ )
								def run_in_graph_mode(*snake_case__   : int      ,       **snake_case__   : Tuple ):
												return func(*snake_case__      ,       **snake_case__ )

								if do_eager_mode is True:
												if use_xla is not False:
																raise ValueError(
																    """Cannot run model in XLA, if `args.eager_mode` is set to `True`. Please set `args.eager_mode=False`.""" )
												return run_in_eager_mode
								else:
												return run_in_graph_mode

				return run_func





def 							lowercase					(snake_case__   : int      ,       snake_case__   : int      ,       snake_case__   : int )     ->  ["tf.Tensor"]:


				'''simple docstring'''






				lowerCAmelCase  =				random.Random()
				lowerCAmelCase  =				[rng.randint(0      ,       vocab_size - 1 ) for i in range(batch_size * sequence_length )]
				return tf.constant(snake_case__      ,       shape=(batch_size, sequence_length)      ,       dtype=tf.intaa )






class       SCREAMING_SNAKE_CASE__					(					_a					):
						_a    						=						42
						_a    						=						42
						_a    						=						"TensorFlow"


						@property
						def   __lowercase (							self				:			Optional[int]					):
										return tf.__version__


						def   __lowercase (							self				:			Optional[Any]						,						lowerCAmelCase				:			str						,						lowerCAmelCase				:			int						,						lowerCAmelCase				:			int					):
										# initialize GPU on separate process
										lowerCAmelCase  =				self.args.strategy
										if strategy is None:
														raise ValueError("""A device strategy has to be initialized before using TensorFlow."""					)
										lowerCAmelCase  =				self._prepare_inference_func(lowerCAmelCase						,						lowerCAmelCase						,						lowerCAmelCase					)
										return self._measure_speed(_inference					)


						def   __lowercase (							self				:			str						,						lowerCAmelCase				:			str						,						lowerCAmelCase				:			int						,						lowerCAmelCase				:			int					):
										lowerCAmelCase  =				self.args.strategy
										if strategy is None:
														raise ValueError("""A device strategy has to be initialized before using TensorFlow."""					)
										lowerCAmelCase  =				self._prepare_train_func(lowerCAmelCase						,						lowerCAmelCase						,						lowerCAmelCase					)
										return self._measure_speed(_train					)


						def   __lowercase (							self				:			str						,						lowerCAmelCase				:			str						,						lowerCAmelCase				:			int						,						lowerCAmelCase				:			int					):
										# initialize GPU on separate process
										if self.args.is_gpu:
														tf.config.experimental.set_memory_growth(self.args.gpu_list[self.args.device_idx]						,						lowerCAmelCase					)
										lowerCAmelCase  =				self.args.strategy
										if strategy is None:
														raise ValueError("""A device strategy has to be initialized before using TensorFlow."""					)
										lowerCAmelCase  =				self._prepare_inference_func(lowerCAmelCase						,						lowerCAmelCase						,						lowerCAmelCase					)
										return self._measure_memory(_inference					)


						def   __lowercase (							self				:			int						,						lowerCAmelCase				:			str						,						lowerCAmelCase				:			int						,						lowerCAmelCase				:			int					):
										if self.args.is_gpu:
														tf.config.experimental.set_memory_growth(self.args.gpu_list[self.args.device_idx]						,						lowerCAmelCase					)
										lowerCAmelCase  =				self.args.strategy
										if strategy is None:
														raise ValueError("""A device strategy has to be initialized before using TensorFlow."""					)

										lowerCAmelCase  =				self._prepare_train_func(lowerCAmelCase						,						lowerCAmelCase						,						lowerCAmelCase					)
										return self._measure_memory(_train					)


						def   __lowercase (							self				:			List[str]						,						lowerCAmelCase				:			str						,						lowerCAmelCase				:			int						,						lowerCAmelCase				:			int					):
										lowerCAmelCase  =				self.config_dict[model_name]

										if self.args.fpaa:
														raise NotImplementedError("""Mixed precision is currently not supported."""					)

										lowerCAmelCase  =				(
										    hasattr(lowerCAmelCase						,						"""architectures"""					)
										    and isinstance(config.architectures						,						lowerCAmelCase					)
										    and len(config.architectures					) > 0
										)
										if not self.args.only_pretrain_model and has_model_class_in_config:
														try:
																		lowerCAmelCase  =				"""TF""" + config.architectures[0]  # prepend 'TF' for tensorflow model
																		lowerCAmelCase  =				__import__("""transformers"""						,						fromlist=[model_class]					)
																		lowerCAmelCase  =				getattr(lowerCAmelCase						,						lowerCAmelCase					)
																		lowerCAmelCase  =				model_cls(lowerCAmelCase					)
														except ImportError:
																		raise ImportError(
																		    f'''{model_class} does not exist. If you just want to test the pretrained model, you might want to'''
																		    """ set `--only_pretrain_model` or `args.only_pretrain_model=True`."""					)
										else:
														lowerCAmelCase  =				TF_MODEL_MAPPING[config.__class__](lowerCAmelCase					)

										# encoder-decoder has vocab size saved differently
										lowerCAmelCase  =				config.vocab_size if hasattr(lowerCAmelCase						,						"""vocab_size"""					) else config.encoder.vocab_size
										lowerCAmelCase  =				random_input_ids(lowerCAmelCase						,						lowerCAmelCase						,						lowerCAmelCase					)

										@run_with_tf_optimizations(self.args.eager_mode						,						self.args.use_xla					)
										def encoder_decoder_forward():
														return model(lowerCAmelCase						,						decoder_input_ids=lowerCAmelCase						,						training=lowerCAmelCase					)

										@run_with_tf_optimizations(self.args.eager_mode						,						self.args.use_xla					)
										def encoder_forward():
														return model(lowerCAmelCase						,						training=lowerCAmelCase					)

										lowerCAmelCase  =				encoder_decoder_forward if config.is_encoder_decoder else encoder_forward

										return _inference


						def   __lowercase (							self				:			Optional[int]						,						lowerCAmelCase				:			str						,						lowerCAmelCase				:			int						,						lowerCAmelCase				:			int					):
										lowerCAmelCase  =				self.config_dict[model_name]

										if self.args.eager_mode is not False:
														raise ValueError("""Training cannot be done in eager mode. Please make sure that `args.eager_mode = False`."""					)

										if self.args.fpaa:
														raise NotImplementedError("""Mixed precision is currently not supported."""					)

										lowerCAmelCase  =				(
										    hasattr(lowerCAmelCase						,						"""architectures"""					)
										    and isinstance(config.architectures						,						lowerCAmelCase					)
										    and len(config.architectures					) > 0
										)
										if not self.args.only_pretrain_model and has_model_class_in_config:
														try:
																		lowerCAmelCase  =				"""TF""" + config.architectures[0]  # prepend 'TF' for tensorflow model
																		lowerCAmelCase  =				__import__("""transformers"""						,						fromlist=[model_class]					)
																		lowerCAmelCase  =				getattr(lowerCAmelCase						,						lowerCAmelCase					)
																		lowerCAmelCase  =				model_cls(lowerCAmelCase					)
														except ImportError:
																		raise ImportError(
																		    f'''{model_class} does not exist. If you just want to test the pretrained model, you might want to'''
																		    """ set `--only_pretrain_model` or `args.only_pretrain_model=True`."""					)
										else:
														lowerCAmelCase  =				TF_MODEL_WITH_LM_HEAD_MAPPING[config.__class__](lowerCAmelCase					)

										# encoder-decoder has vocab size saved differently
										lowerCAmelCase  =				config.vocab_size if hasattr(lowerCAmelCase						,						"""vocab_size"""					) else config.encoder.vocab_size
										lowerCAmelCase  =				random_input_ids(lowerCAmelCase						,						lowerCAmelCase						,						lowerCAmelCase					)

										@run_with_tf_optimizations(self.args.eager_mode						,						self.args.use_xla					)
										def encoder_decoder_train():
														lowerCAmelCase  =				model(lowerCAmelCase						,						decoder_input_ids=lowerCAmelCase						,						labels=lowerCAmelCase						,						training=lowerCAmelCase					)[0]
														lowerCAmelCase  =				tf.gradients(lowerCAmelCase						,						model.trainable_variables					)
														return gradients

										@run_with_tf_optimizations(self.args.eager_mode						,						self.args.use_xla					)
										def encoder_train():
														lowerCAmelCase  =				model(lowerCAmelCase						,						labels=lowerCAmelCase						,						training=lowerCAmelCase					)[0]
														lowerCAmelCase  =				tf.gradients(lowerCAmelCase						,						model.trainable_variables					)
														return gradients

										lowerCAmelCase  =				encoder_decoder_train if config.is_encoder_decoder else encoder_train

										return _train


						def   __lowercase (							self				:			Optional[int]						,						lowerCAmelCase				:			List[str]					):
										with self.args.strategy.scope():
														try:
																		if self.args.is_tpu or self.args.use_xla:
																						# run additional 10 times to stabilize compilation for tpu
																						logger.info("""Do inference on TPU. Running model 5 times to stabilize compilation"""					)
																						timeit.repeat(lowerCAmelCase						,						repeat=1						,						number=5					)

																		# as written in https://docs.python.org/2/library/timeit.html#timeit.Timer.repeat, min should be taken rather than the average
																		lowerCAmelCase  =				timeit.repeat(
																		    lowerCAmelCase						,						repeat=self.args.repeat						,						number=10						,						)

																		return min(lowerCAmelCase					) / 10.0
														except ResourceExhaustedError as e:
																		self.print_fn(f'''Doesn\'t fit on GPU. {e}'''					)




						def   __lowercase (							self				:			Optional[Any]						,						lowerCAmelCase				:			Callable[[], None]					):
										logger.info(
										    """Note that TensorFlow allocates more memory than """
										    """it might need to speed up computation. """
										    """The memory reported here corresponds to the memory """
										    """reported by `nvidia-smi`, which can vary depending """
										    """on total available memory on the GPU that is used."""					)
										with self.args.strategy.scope():
														try:
																		if self.args.trace_memory_line_by_line:
																						if not self.args.eager_mode:
																										raise ValueError(
																										    """`args.eager_mode` is set to `False`. Make sure to run model in eager mode to measure memory"""
																										    """ consumption line by line."""					)
																						lowerCAmelCase  =				start_memory_tracing("""transformers"""					)

																		if self.args.is_tpu:
																						# tpu
																						raise NotImplementedError(
																						    """Memory Benchmarking is currently not implemented for TPU. Please disable memory benchmarking"""
																						    """ with `args.memory=False`"""					)
																		elif self.args.is_gpu:
																						# gpu
																						if not is_pyanvml_available():
																										logger.warning(
																										    """py3nvml not installed, we won't log GPU memory usage. """
																										    """Install py3nvml (pip install py3nvml) to log information about GPU."""					)
																										lowerCAmelCase  =				"""N/A"""
																						else:
																										logger.info(
																										    """Measuring total GPU usage on GPU device. Make sure to not have additional processes"""
																										    """ running on the same GPU."""					)
																										# init nvml
																										nvml.nvmlInit()
																										func()
																										lowerCAmelCase  =				nvml.nvmlDeviceGetHandleByIndex(self.args.device_idx					)
																										lowerCAmelCase  =				nvml.nvmlDeviceGetMemoryInfo(lowerCAmelCase					)
																										lowerCAmelCase  =				meminfo.used
																										lowerCAmelCase  =				Memory(lowerCAmelCase					)
																										# shutdown nvml
																										nvml.nvmlShutdown()
																		else:
																						# cpu
																						if self.args.trace_memory_line_by_line:
																										logger.info(
																										    """When enabling line by line tracing, the max peak memory for CPU is inaccurate in"""
																										    """ TensorFlow."""					)
																										lowerCAmelCase  =				None
																						else:
																										lowerCAmelCase  =				measure_peak_memory_cpu(lowerCAmelCase					)
																										lowerCAmelCase  =				Memory(lowerCAmelCase					) if isinstance(lowerCAmelCase						,						lowerCAmelCase					) else memory_bytes
																		if self.args.trace_memory_line_by_line:
																						lowerCAmelCase  =				stop_memory_tracing(lowerCAmelCase					)
																						if memory is None:
																										lowerCAmelCase  =				summary.total
																		else:
																						lowerCAmelCase  =				None

																		return memory, summary
														except ResourceExhaustedError as e:
																		self.print_fn(f'''Doesn\'t fit on GPU. {e}'''					)
																		return "N/A", None











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





