




'''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 						snake_case_							(_a	:							Dict    ,   _a	:							Union[str, Any]     ):
    return (preds == labels).mean()


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






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






def 						snake_case_							():
    # See all possible arguments in src/transformers/training_args.py
    # or by passing the --help flag to this script.
    # We now keep distinct sets of args, for a cleaner separation of concerns.

    UpperCAmelCase			       =		HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)     )
    UpperCAmelCase       ,     UpperCAmelCase       ,     UpperCAmelCase			       =		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'''    ,   _a     )

    # Set seed
    set_seed(training_args.seed     )

    try:
        UpperCAmelCase			       =		processors[data_args.task_name]()
        UpperCAmelCase			       =		processor.get_labels()
        UpperCAmelCase			       =		len(_a     )
    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.

    UpperCAmelCase			       =		AutoConfig.from_pretrained(
        model_args.config_name if model_args.config_name else model_args.model_name_or_path    ,   num_labels=_a    ,   finetuning_task=data_args.task_name    ,   cache_dir=model_args.cache_dir    ,   )
    UpperCAmelCase			       =		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    ,   )
    UpperCAmelCase			       =		AutoModelForMultipleChoice.from_pretrained(
        model_args.model_name_or_path    ,   from_tf=bool('''.ckpt''' in model_args.model_name_or_path     )    ,   config=_a    ,   cache_dir=model_args.cache_dir    ,   )

    # Get datasets
    UpperCAmelCase			       =		(
        MultipleChoiceDataset(
            data_dir=data_args.data_dir    ,   tokenizer=_a    ,   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
    )
    UpperCAmelCase			       =		(
        MultipleChoiceDataset(
            data_dir=data_args.data_dir    ,   tokenizer=_a    ,   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(_a	:							EvalPrediction     ) -> Dict:
        UpperCAmelCase			       =		np.argmax(p.predictions    ,   axis=1     )
        return {"acc": simple_accuracy(_a    ,   p.label_ids     )}

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

    # Initialize our Trainer
    UpperCAmelCase			       =		Trainer(
        model=_a    ,   args=_a    ,   train_dataset=_a    ,   eval_dataset=_a    ,   compute_metrics=_a    ,   data_collator=_a    ,   )

    # 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
    UpperCAmelCase			       =		{}
    if training_args.do_eval:
        logger.info('''*** Evaluate ***'''     )

        UpperCAmelCase			       =		trainer.evaluate()

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

                results.update(_a     )

    return results





def 						snake_case_							(_a	:							Optional[int]     ):
    # For xla_spawn (TPUs)
    main()


if __name__ == "__main__":
   main()







"""simple docstring"""





import inspect
import unittest

import numpy as np

from transformers import BeitConfig
from transformers.testing_utils import require_flax, require_vision, slow
from transformers.utils import cached_property, is_flax_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor, ids_tensor


if is_flax_available():
							import jax

							from transformers import FlaxBeitForImageClassification, FlaxBeitForMaskedImageModeling, FlaxBeitModel

if is_vision_available():
							from PIL import Image

							from transformers import BeitImageProcessor







class 				SCREAMING_SNAKE_CASE					(		unittest.TestCase       ):






					"""simple docstring"""



					def __init__(       self			:				Optional[Any]   ,lowercase_			:				List[str]   ,lowercase_			:				Any=1_0_0   ,lowercase_			:				str=1_3   ,lowercase_			:				Any=3_0   ,lowercase_			:				Optional[int]=2   ,lowercase_			:				Dict=3   ,lowercase_			:				Optional[int]=True   ,lowercase_			:				Union[str, Any]=True   ,lowercase_			:				Optional[Any]=3_2   ,lowercase_			:				List[Any]=5   ,lowercase_			:				Any=4   ,lowercase_			:				Optional[int]=3_7   ,lowercase_			:				List[Any]="gelu"   ,lowercase_			:				Dict=0.1   ,lowercase_			:				List[Any]=0.1   ,lowercase_			:				int=1_0   ,lowercase_			:				int=0.02   ,lowercase_			:				List[str]=3   ,):
						lowerCAmelCase__	:						int  				=	parent
						lowerCAmelCase__	:						Dict  				=	vocab_size
						lowerCAmelCase__	:						List[Any]  				=	batch_size
						lowerCAmelCase__	:						Union[str, Any]  				=	image_size
						lowerCAmelCase__	:						Optional[int]  				=	patch_size
						lowerCAmelCase__	:						str  				=	num_channels
						lowerCAmelCase__	:						str  				=	is_training
						lowerCAmelCase__	:						Optional[Any]  				=	use_labels
						lowerCAmelCase__	:						Union[str, Any]  				=	hidden_size
						lowerCAmelCase__	:						Optional[Any]  				=	num_hidden_layers
						lowerCAmelCase__	:						Any  				=	num_attention_heads
						lowerCAmelCase__	:						Union[str, Any]  				=	intermediate_size
						lowerCAmelCase__	:						List[Any]  				=	hidden_act
						lowerCAmelCase__	:						str  				=	hidden_dropout_prob
						lowerCAmelCase__	:						List[Any]  				=	attention_probs_dropout_prob
						lowerCAmelCase__	:						Union[str, Any]  				=	type_sequence_label_size
						lowerCAmelCase__	:						Dict  				=	initializer_range

						# in BeiT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token)
						lowerCAmelCase__	:						Any  				=	(image_size // patch_size) ** 2
						lowerCAmelCase__	:						str  				=	num_patches + 1







					def        __lowerCAmelCase (       self			:				Tuple		):
						lowerCAmelCase__	:						int  				=	floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]		)

						lowerCAmelCase__	:						Optional[int]  				=	None
						if self.use_labels:
							lowerCAmelCase__	:						str  				=	ids_tensor([self.batch_size]   ,self.type_sequence_label_size		)

						lowerCAmelCase__	:						List[str]  				=	BeitConfig(
						    vocab_size=self.vocab_size   ,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   ,is_decoder=lowercase_   ,initializer_range=self.initializer_range   ,)

						return config, pixel_values, labels







					def        __lowerCAmelCase (       self			:				Union[str, Any]   ,lowercase_			:				str   ,lowercase_			:				Dict   ,lowercase_			:				Any		):
						lowerCAmelCase__	:						Any  				=	FlaxBeitModel(config=lowercase_		)
						lowerCAmelCase__	:						str  				=	model(lowercase_		)
						self.parent.assertEqual(result.last_hidden_state.shape   ,(self.batch_size, self.seq_length, self.hidden_size)		)







					def        __lowerCAmelCase (       self			:				Dict   ,lowercase_			:				Any   ,lowercase_			:				Union[str, Any]   ,lowercase_			:				Any		):
						lowerCAmelCase__	:						Optional[int]  				=	FlaxBeitForMaskedImageModeling(config=lowercase_		)
						lowerCAmelCase__	:						str  				=	model(lowercase_		)
						self.parent.assertEqual(result.logits.shape   ,(self.batch_size, self.seq_length - 1, self.vocab_size)		)







					def        __lowerCAmelCase (       self			:				List[str]   ,lowercase_			:				str   ,lowercase_			:				List[str]   ,lowercase_			:				str		):
						lowerCAmelCase__	:						Dict  				=	self.type_sequence_label_size
						lowerCAmelCase__	:						Tuple  				=	FlaxBeitForImageClassification(config=lowercase_		)
						lowerCAmelCase__	:						List[str]  				=	model(lowercase_		)
						self.parent.assertEqual(result.logits.shape   ,(self.batch_size, self.type_sequence_label_size)		)

						# test greyscale images
						lowerCAmelCase__	:						int  				=	1
						lowerCAmelCase__	:						Tuple  				=	FlaxBeitForImageClassification(lowercase_		)

						lowerCAmelCase__	:						str  				=	floats_tensor([self.batch_size, 1, self.image_size, self.image_size]		)
						lowerCAmelCase__	:						List[str]  				=	model(lowercase_		)







					def        __lowerCAmelCase (       self			:				List[Any]		):
						lowerCAmelCase__	:						List[str]  				=	self.prepare_config_and_inputs()
						(
						    (
						    lowerCAmelCase__
						)				,(
						    lowerCAmelCase__
						)				,(
						    lowerCAmelCase__
						)				,
						)	:						Optional[int]  				=	config_and_inputs
						lowerCAmelCase__	:						Dict  				=	{'''pixel_values''': pixel_values}
						return config, inputs_dict







@require_flax
class 				SCREAMING_SNAKE_CASE					(		a_    ,							unittest.TestCase       ):






					"""simple docstring"""



					lowercase__				 =       (
					    (FlaxBeitModel, FlaxBeitForImageClassification, FlaxBeitForMaskedImageModeling) if is_flax_available() else ()
					)







					def        __lowerCAmelCase (       self			:				int		):
						lowerCAmelCase__	:						Tuple  				=	FlaxBeitModelTester(self		)
						lowerCAmelCase__	:						str  				=	ConfigTester(self   ,config_class=lowercase_   ,has_text_modality=lowercase_   ,hidden_size=3_7		)







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







					def        __lowerCAmelCase (       self			:				Optional[int]		):
						lowerCAmelCase__				,lowerCAmelCase__	:						Optional[Any]  				=	self.model_tester.prepare_config_and_inputs_for_common()

						for model_class in self.all_model_classes:
							lowerCAmelCase__	:						List[str]  				=	model_class(lowercase_		)
							lowerCAmelCase__	:						Optional[int]  				=	inspect.signature(model.__call__		)
							# signature.parameters is an OrderedDict => so arg_names order is deterministic
							lowerCAmelCase__	:						Tuple  				=	[*signature.parameters.keys()]

							lowerCAmelCase__	:						Optional[Any]  				=	['''pixel_values''']
							self.assertListEqual(arg_names[:1]   ,lowercase_		)







					def        __lowerCAmelCase (       self			:				Union[str, Any]		):
						lowerCAmelCase__				,lowerCAmelCase__	:						List[Any]  				=	self.model_tester.prepare_config_and_inputs_for_common()

						for model_class in self.all_model_classes:
							with self.subTest(model_class.__name__		):
								lowerCAmelCase__	:						Union[str, Any]  				=	self._prepare_for_class(lowercase_   ,lowercase_		)
								lowerCAmelCase__	:						Dict  				=	model_class(lowercase_		)

								@jax.jit
								def model_jitted(lowercase_			:				Dict   ,**lowercase_			:				List[Any]		):
									return model(pixel_values=lowercase_   ,**lowercase_		)

								with self.subTest('''JIT Enabled'''		):
									lowerCAmelCase__	:						Any  				=	model_jitted(**lowercase_		).to_tuple()

								with self.subTest('''JIT Disabled'''		):
									with jax.disable_jit():
										lowerCAmelCase__	:						int  				=	model_jitted(**lowercase_		).to_tuple()

								self.assertEqual(len(lowercase_		)   ,len(lowercase_		)		)
								for jitted_output, output in zip(lowercase_   ,lowercase_		):
									self.assertEqual(jitted_output.shape   ,output.shape		)







					def        __lowerCAmelCase (       self			:				Any		):
						lowerCAmelCase__	:						Optional[int]  				=	self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_model(*lowercase_		)







					def        __lowerCAmelCase (       self			:				str		):
						lowerCAmelCase__	:						Optional[Any]  				=	self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_for_masked_lm(*lowercase_		)







					def        __lowerCAmelCase (       self			:				Any		):
						lowerCAmelCase__	:						Optional[Any]  				=	self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_for_image_classification(*lowercase_		)







					@slow
					def        __lowerCAmelCase (       self			:				List[str]		):
						for model_class_name in self.all_model_classes:
							lowerCAmelCase__	:						Tuple  				=	model_class_name.from_pretrained('''microsoft/beit-base-patch16-224'''		)
							lowerCAmelCase__	:						List[Any]  				=	model(np.ones((1, 3, 2_2_4, 2_2_4)		)		)
							self.assertIsNotNone(lowercase_		)

def   __SCREAMING_SNAKE_CASE  (      ):
	lowerCAmelCase__	:						List[str]  				=	Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' )
	return image







@require_vision
@require_flax
class 				SCREAMING_SNAKE_CASE					(		unittest.TestCase       ):






					"""simple docstring"""



					@cached_property
					def        __lowerCAmelCase (       self			:				Dict		):
						return BeitImageProcessor.from_pretrained('''microsoft/beit-base-patch16-224'''		) if is_vision_available() else None







					@slow
					def        __lowerCAmelCase (       self			:				int		):
						lowerCAmelCase__	:						Tuple  				=	FlaxBeitForMaskedImageModeling.from_pretrained('''microsoft/beit-base-patch16-224-pt22k'''		)

						lowerCAmelCase__	:						List[str]  				=	self.default_image_processor
						lowerCAmelCase__	:						Optional[int]  				=	prepare_img()
						lowerCAmelCase__	:						Union[str, Any]  				=	image_processor(images=lowercase_   ,return_tensors='''np'''		).pixel_values

						# prepare bool_masked_pos
						lowerCAmelCase__	:						str  				=	np.ones((1, 1_9_6)   ,dtype=lowercase_		)

						# forward pass
						lowerCAmelCase__	:						Dict  				=	model(pixel_values=lowercase_   ,bool_masked_pos=lowercase_		)
						lowerCAmelCase__	:						str  				=	outputs.logits

						# verify the logits
						lowerCAmelCase__	:						Any  				=	(1, 1_9_6, 8_1_9_2)
						self.assertEqual(logits.shape   ,lowercase_		)

						lowerCAmelCase__	:						str  				=	np.array(
						    [[-3.2437, 0.5072, -13.9174], [-3.2456, 0.4948, -13.9401], [-3.2033, 0.5121, -13.8550]]		)

						self.assertTrue(np.allclose(logits[bool_masked_pos][:3, :3]   ,lowercase_   ,atol=1E-2		)		)







					@slow
					def        __lowerCAmelCase (       self			:				Optional[int]		):
						lowerCAmelCase__	:						List[str]  				=	FlaxBeitForImageClassification.from_pretrained('''microsoft/beit-base-patch16-224'''		)

						lowerCAmelCase__	:						Dict  				=	self.default_image_processor
						lowerCAmelCase__	:						Optional[Any]  				=	prepare_img()
						lowerCAmelCase__	:						Any  				=	image_processor(images=lowercase_   ,return_tensors='''np'''		)

						# forward pass
						lowerCAmelCase__	:						List[Any]  				=	model(**lowercase_		)
						lowerCAmelCase__	:						int  				=	outputs.logits

						# verify the logits
						lowerCAmelCase__	:						Dict  				=	(1, 1_0_0_0)
						self.assertEqual(logits.shape   ,lowercase_		)

						lowerCAmelCase__	:						Dict  				=	np.array([-1.2385, -1.0987, -1.0108]		)

						self.assertTrue(np.allclose(logits[0, :3]   ,lowercase_   ,atol=1E-4		)		)

						lowerCAmelCase__	:						Union[str, Any]  				=	2_8_1
						self.assertEqual(logits.argmax(-1		).item()   ,lowercase_		)







					@slow
					def        __lowerCAmelCase (       self			:				List[Any]		):
						lowerCAmelCase__	:						Tuple  				=	FlaxBeitForImageClassification.from_pretrained('''microsoft/beit-large-patch16-224-pt22k-ft22k'''		)

						lowerCAmelCase__	:						Union[str, Any]  				=	self.default_image_processor
						lowerCAmelCase__	:						str  				=	prepare_img()
						lowerCAmelCase__	:						Union[str, Any]  				=	image_processor(images=lowercase_   ,return_tensors='''np'''		)

						# forward pass
						lowerCAmelCase__	:						Tuple  				=	model(**lowercase_		)
						lowerCAmelCase__	:						int  				=	outputs.logits

						# verify the logits
						lowerCAmelCase__	:						Optional[int]  				=	(1, 2_1_8_4_1)
						self.assertEqual(logits.shape   ,lowercase_		)

						lowerCAmelCase__	:						Union[str, Any]  				=	np.array([1.6881, -0.2787, 0.5901]		)

						self.assertTrue(np.allclose(logits[0, :3]   ,lowercase_   ,atol=1E-4		)		)

						lowerCAmelCase__	:						Optional[int]  				=	2_3_9_6
						self.assertEqual(logits.argmax(-1		).item()   ,lowercase_		)




