




"""simple docstring"""







import logging
import os
from dataclasses import dataclass, field
from typing import Dict, Optional

import numpy as np
from utils_multiple_choice import MultipleChoiceDataset, Split, processors

import transformers
from transformers import (
    AutoConfig,
    AutoModelForMultipleChoice,
    AutoTokenizer,
    DataCollatorWithPadding,
    EvalPrediction,
    HfArgumentParser,
    Trainer,
    TrainingArguments,
    set_seed,
)
from transformers.trainer_utils import is_main_process


a      =							logging.getLogger(__name__)





def 							lowercase					(snake_case__   : Tuple      ,       snake_case__   : int )     ->  List[str]:


				'''simple docstring'''






				return (preds == labels).mean()






@dataclass
class       SCREAMING_SNAKE_CASE__					:
						_a    						=						field(
						    metadata={'help': 'Path to pretrained model or model identifier from huggingface.co/models'}					)
						_a    						=						field(
						    default=_a						,				metadata={'help': 'Pretrained config name or path if not the same as model_name'}					)
						_a    						=						field(
						    default=_a						,				metadata={'help': 'Pretrained tokenizer name or path if not the same as model_name'}					)
						_a    						=						field(
						    default=_a						,				metadata={'help': 'Where do you want to store the pretrained models downloaded from huggingface.co'}						,				)






@dataclass
class       SCREAMING_SNAKE_CASE__					:
						_a    						=						field(metadata={'help': 'The name of the task to train on: ' + ', '.join(processors.keys()					)}					)
						_a    						=						field(metadata={'help': 'Should contain the data files for the task.'}					)
						_a    						=						field(
						    default=1_28						,				metadata={
						        'help': (
						            'The maximum total input sequence length after tokenization. Sequences longer '
						            'than this will be truncated, sequences shorter will be padded.'
						        )
						    }						,				)
						_a    						=						field(
						    default=_a						,				metadata={'help': 'Overwrite the cached training and evaluation sets'}					)





def 							lowercase					()     ->  List[str]:


				'''simple docstring'''






				lowerCAmelCase  =				HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) )
				lowerCAmelCase ,						lowerCAmelCase ,						lowerCAmelCase  =				parser.parse_args_into_dataclasses()

				if (
				    os.path.exists(training_args.output_dir )
				    and os.listdir(training_args.output_dir )
				    and training_args.do_train
				    and not training_args.overwrite_output_dir
				):
								raise ValueError(
								    f'''Output directory ({training_args.output_dir}) already exists and is not empty. Use'''
								    """ --overwrite_output_dir to overcome.""" )

				# Setup logging
				logging.basicConfig(
				    format="""%(asctime)s - %(levelname)s - %(name)s - %(message)s"""      ,       datefmt="""%m/%d/%Y %H:%M:%S"""      ,       level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN      ,       )
				logger.warning(
				    """Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s"""      ,       training_args.local_rank      ,       training_args.device      ,       training_args.n_gpu      ,       bool(training_args.local_rank != -1 )      ,       training_args.fpaa      ,       )
				# Set the verbosity to info of the Transformers logger (on main process only):
				if is_main_process(training_args.local_rank ):
								transformers.utils.logging.set_verbosity_info()
								transformers.utils.logging.enable_default_handler()
								transformers.utils.logging.enable_explicit_format()
				logger.info("""Training/evaluation parameters %s"""      ,       snake_case__ )

				# Set seed
				set_seed(training_args.seed )

				try:
								lowerCAmelCase  =				processors[data_args.task_name]()
								lowerCAmelCase  =				processor.get_labels()
								lowerCAmelCase  =				len(snake_case__ )
				except KeyError:
								raise ValueError("""Task not found: %s""" % (data_args.task_name) )

				# Load pretrained model and tokenizer
				#
				# Distributed training:
				# The .from_pretrained methods guarantee that only one local process can concurrently
				# download model & vocab.

				lowerCAmelCase  =				AutoConfig.from_pretrained(
				    model_args.config_name if model_args.config_name else model_args.model_name_or_path      ,       num_labels=snake_case__      ,       finetuning_task=data_args.task_name      ,       cache_dir=model_args.cache_dir      ,       )
				lowerCAmelCase  =				AutoTokenizer.from_pretrained(
				    model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path      ,       cache_dir=model_args.cache_dir      ,       )
				lowerCAmelCase  =				AutoModelForMultipleChoice.from_pretrained(
				    model_args.model_name_or_path      ,       from_tf=bool(""".ckpt""" in model_args.model_name_or_path )      ,       config=snake_case__      ,       cache_dir=model_args.cache_dir      ,       )

				# Get datasets
				lowerCAmelCase  =				(
				    MultipleChoiceDataset(
				        data_dir=data_args.data_dir      ,       tokenizer=snake_case__      ,       task=data_args.task_name      ,       max_seq_length=data_args.max_seq_length      ,       overwrite_cache=data_args.overwrite_cache      ,       mode=Split.train      ,       )
				    if training_args.do_train
				    else None
				)
				lowerCAmelCase  =				(
				    MultipleChoiceDataset(
				        data_dir=data_args.data_dir      ,       tokenizer=snake_case__      ,       task=data_args.task_name      ,       max_seq_length=data_args.max_seq_length      ,       overwrite_cache=data_args.overwrite_cache      ,       mode=Split.dev      ,       )
				    if training_args.do_eval
				    else None
				)

				def compute_metrics(snake_case__   : EvalPrediction ) -> Dict:
								lowerCAmelCase  =				np.argmax(p.predictions      ,       axis=1 )
								return {"acc": simple_accuracy(snake_case__      ,       p.label_ids )}

				# Data collator
				lowerCAmelCase  =				DataCollatorWithPadding(snake_case__      ,       pad_to_multiple_of=8 ) if training_args.fpaa else None

				# Initialize our Trainer
				lowerCAmelCase  =				Trainer(
				    model=snake_case__      ,       args=snake_case__      ,       train_dataset=snake_case__      ,       eval_dataset=snake_case__      ,       compute_metrics=snake_case__      ,       data_collator=snake_case__      ,       )

				# Training
				if training_args.do_train:
								trainer.train(
								    model_path=model_args.model_name_or_path if os.path.isdir(model_args.model_name_or_path ) else None )
								trainer.save_model()
								# For convenience, we also re-save the tokenizer to the same directory,
								# so that you can share your model easily on huggingface.co/models =)
								if trainer.is_world_master():
												tokenizer.save_pretrained(training_args.output_dir )

    # Evaluation
				lowerCAmelCase  =				{}
				if training_args.do_eval:
								logger.info("""*** Evaluate ***""" )

								lowerCAmelCase  =				trainer.evaluate()

								lowerCAmelCase  =				os.path.join(training_args.output_dir      ,       """eval_results.txt""" )
								if trainer.is_world_master():
												with open(snake_case__      ,       """w""" ) as writer:
																logger.info("""***** Eval results *****""" )
																for key, value in result.items():
																				logger.info("""  %s = %s"""      ,       snake_case__      ,       snake_case__ )
																				writer.write("""%s = %s\n""" % (key, value) )

																results.update(snake_case__ )

				return results





def 							lowercase					(snake_case__   : List[Any] )     ->  List[str]:


				'''simple docstring'''






				main()


if __name__ == "__main__":
		main()











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





