



import argparse
import collections
import json
import os
import re
import string
import sys

import numpy as np


lowercase_						=       re.compile(r"""\b(a|an|the)\b""", re.UNICODE)

lowercase_						=       None



def __lowerCAmelCase	(       ):
			lowercase__   					=			argparse.ArgumentParser("Official evaluation script for SQuAD version 2.0."					)
			parser.add_argument("data_file"  ,					metavar="data.json"  ,					help="Input data JSON file."					)
			parser.add_argument("pred_file"  ,					metavar="pred.json"  ,					help="Model predictions."					)
			parser.add_argument(
			    "--out-file"  ,					"-o"  ,					metavar="eval.json"  ,					help="Write accuracy metrics to file (default is stdout)."					)
			parser.add_argument(
			    "--na-prob-file"  ,					"-n"  ,					metavar="na_prob.json"  ,					help="Model estimates of probability of no answer."					)
			parser.add_argument(
			    "--na-prob-thresh"  ,					"-t"  ,					type=SCREAMING_SNAKE_CASE_  ,					default=1.0  ,					help="Predict \"\" if no-answer probability exceeds this (default = 1.0)."  ,					)
			parser.add_argument(
			    "--out-image-dir"  ,					"-p"  ,					metavar="out_images"  ,					default=SCREAMING_SNAKE_CASE_  ,					help="Save precision-recall curves to directory."					)
			parser.add_argument("--verbose"  ,					"-v"  ,					action="store_true"					)
			if len(sys.argv					) == 1:
						parser.print_help()
						sys.exit(1					)
			return parser.parse_args()



def __lowerCAmelCase	(       SCREAMING_SNAKE_CASE_					):
			lowercase__   					=			{}
			for article in dataset:
						for p in article["paragraphs"]:
									for qa in p["qas"]:
												lowercase__   					=			bool(qa["answers"]["text"]					)
			return qid_to_has_ans



def __lowerCAmelCase	(       SCREAMING_SNAKE_CASE_					):

			def remove_articles(SCREAMING_SNAKE_CASE_					):
						return ARTICLES_REGEX.sub(" "  ,					SCREAMING_SNAKE_CASE_					)

			def white_space_fix(SCREAMING_SNAKE_CASE_					):
						return " ".join(text.split()					)

			def remove_punc(SCREAMING_SNAKE_CASE_					):
						lowercase__   					=			set(string.punctuation					)
						return "".join(ch for ch in text if ch not in exclude					)

			def lower(SCREAMING_SNAKE_CASE_					):
						return text.lower()

			return white_space_fix(remove_articles(remove_punc(lower(SCREAMING_SNAKE_CASE_					)					)					)					)



def __lowerCAmelCase	(       SCREAMING_SNAKE_CASE_					):
			if not s:
						return []
			return normalize_answer(SCREAMING_SNAKE_CASE_					).split()



def __lowerCAmelCase	(       SCREAMING_SNAKE_CASE_  ,					SCREAMING_SNAKE_CASE_					):
			return int(normalize_answer(SCREAMING_SNAKE_CASE_					) == normalize_answer(SCREAMING_SNAKE_CASE_					)					)



def __lowerCAmelCase	(       SCREAMING_SNAKE_CASE_  ,					SCREAMING_SNAKE_CASE_					):
			lowercase__   					=			get_tokens(SCREAMING_SNAKE_CASE_					)
			lowercase__   					=			get_tokens(SCREAMING_SNAKE_CASE_					)
			lowercase__   					=			collections.Counter(SCREAMING_SNAKE_CASE_					) & collections.Counter(SCREAMING_SNAKE_CASE_					)
			lowercase__   					=			sum(common.values()					)
			if len(SCREAMING_SNAKE_CASE_					) == 0 or len(SCREAMING_SNAKE_CASE_					) == 0:
						# If either is no-answer, then F1 is 1 if they agree, 0 otherwise
						return int(gold_toks == pred_toks					)
			if num_same == 0:
						return 0
			lowercase__   					=			1.0 * num_same / len(SCREAMING_SNAKE_CASE_					)
			lowercase__   					=			1.0 * num_same / len(SCREAMING_SNAKE_CASE_					)
			lowercase__   					=			(2 * precision * recall) / (precision + recall)
			return fa



def __lowerCAmelCase	(       SCREAMING_SNAKE_CASE_  ,					SCREAMING_SNAKE_CASE_					):
			lowercase__   					=			{}
			lowercase__   					=			{}
			for article in dataset:
						for p in article["paragraphs"]:
									for qa in p["qas"]:
												lowercase__   					=			qa["id"]
												lowercase__   					=			[t for t in qa["answers"]["text"] if normalize_answer(SCREAMING_SNAKE_CASE_					)]
												if not gold_answers:
															# For unanswerable questions, only correct answer is empty string
															lowercase__   					=			[""]
												if qid not in preds:
															print(f'''Missing prediction for {qid}'''					)
															continue
												lowercase__   					=			preds[qid]
												# Take max over all gold answers
												lowercase__   					=			max(compute_exact(SCREAMING_SNAKE_CASE_  ,					SCREAMING_SNAKE_CASE_					) for a in gold_answers					)
												lowercase__   					=			max(compute_fa(SCREAMING_SNAKE_CASE_  ,					SCREAMING_SNAKE_CASE_					) for a in gold_answers					)
			return exact_scores, fa_scores



def __lowerCAmelCase	(       SCREAMING_SNAKE_CASE_  ,					SCREAMING_SNAKE_CASE_  ,					SCREAMING_SNAKE_CASE_  ,					SCREAMING_SNAKE_CASE_					):
			lowercase__   					=			{}
			for qid, s in scores.items():
						lowercase__   					=			na_probs[qid] > na_prob_thresh
						if pred_na:
									lowercase__   					=			float(not qid_to_has_ans[qid]					)
						else:
									lowercase__   					=			s
			return new_scores



def __lowerCAmelCase	(       SCREAMING_SNAKE_CASE_  ,					SCREAMING_SNAKE_CASE_  ,					SCREAMING_SNAKE_CASE_=None					):
			if not qid_list:
						lowercase__   					=			len(SCREAMING_SNAKE_CASE_					)
						return collections.OrderedDict(
						    [
						        ("exact", 100.0 * sum(exact_scores.values()					) / total),
						        ("f1", 100.0 * sum(fa_scores.values()					) / total),
						        ("total", total),
						    ]					)
			else:
						lowercase__   					=			len(SCREAMING_SNAKE_CASE_					)
						return collections.OrderedDict(
						    [
						        ("exact", 100.0 * sum(exact_scores[k] for k in qid_list					) / total),
						        ("f1", 100.0 * sum(fa_scores[k] for k in qid_list					) / total),
						        ("total", total),
						    ]					)



def __lowerCAmelCase	(       SCREAMING_SNAKE_CASE_  ,					SCREAMING_SNAKE_CASE_  ,					SCREAMING_SNAKE_CASE_					):
			for k in new_eval:
						lowercase__   					=			new_eval[k]



def __lowerCAmelCase	(       SCREAMING_SNAKE_CASE_  ,					SCREAMING_SNAKE_CASE_  ,					SCREAMING_SNAKE_CASE_  ,					SCREAMING_SNAKE_CASE_					):
			plt.step(SCREAMING_SNAKE_CASE_  ,					SCREAMING_SNAKE_CASE_  ,					color="b"  ,					alpha=0.2  ,					where="post"					)
			plt.fill_between(SCREAMING_SNAKE_CASE_  ,					SCREAMING_SNAKE_CASE_  ,					step="post"  ,					alpha=0.2  ,					color="b"					)
			plt.xlabel("Recall"					)
			plt.ylabel("Precision"					)
			plt.xlim([0.0, 1.05]					)
			plt.ylim([0.0, 1.05]					)
			plt.title(SCREAMING_SNAKE_CASE_					)
			plt.savefig(SCREAMING_SNAKE_CASE_					)
			plt.clf()



def __lowerCAmelCase	(       SCREAMING_SNAKE_CASE_  ,					SCREAMING_SNAKE_CASE_  ,					SCREAMING_SNAKE_CASE_  ,					SCREAMING_SNAKE_CASE_  ,					SCREAMING_SNAKE_CASE_=None  ,					SCREAMING_SNAKE_CASE_=None					):
			lowercase__   					=			sorted(SCREAMING_SNAKE_CASE_  ,					key=lambda SCREAMING_SNAKE_CASE_					: na_probs[k]					)
			lowercase__   					=			0.0
			lowercase__   					=			1.0
			lowercase__   					=			0.0
			lowercase__   					=			[1.0]
			lowercase__   					=			[0.0]
			lowercase__   					=			0.0
			for i, qid in enumerate(SCREAMING_SNAKE_CASE_					):
						if qid_to_has_ans[qid]:
									true_pos += scores[qid]
						lowercase__   					=			true_pos / float(i + 1					)
						lowercase__   					=			true_pos / float(SCREAMING_SNAKE_CASE_					)
						if i == len(SCREAMING_SNAKE_CASE_					) - 1 or na_probs[qid] != na_probs[qid_list[i + 1]]:
									# i.e., if we can put a threshold after this point
									avg_prec += cur_p * (cur_r - recalls[-1])
									precisions.append(SCREAMING_SNAKE_CASE_					)
									recalls.append(SCREAMING_SNAKE_CASE_					)
			if out_image:
						plot_pr_curve(SCREAMING_SNAKE_CASE_  ,					SCREAMING_SNAKE_CASE_  ,					SCREAMING_SNAKE_CASE_  ,					SCREAMING_SNAKE_CASE_					)
			return {"ap": 100.0 * avg_prec}



def __lowerCAmelCase	(       SCREAMING_SNAKE_CASE_  ,					SCREAMING_SNAKE_CASE_  ,					SCREAMING_SNAKE_CASE_  ,					SCREAMING_SNAKE_CASE_  ,					SCREAMING_SNAKE_CASE_  ,					SCREAMING_SNAKE_CASE_					):
			if out_image_dir and not os.path.exists(SCREAMING_SNAKE_CASE_					):
						os.makedirs(SCREAMING_SNAKE_CASE_					)
			lowercase__   					=			sum(1 for v in qid_to_has_ans.values() if v					)
			if num_true_pos == 0:
						return
			lowercase__   					=			make_precision_recall_eval(
			    SCREAMING_SNAKE_CASE_  ,					SCREAMING_SNAKE_CASE_  ,					SCREAMING_SNAKE_CASE_  ,					SCREAMING_SNAKE_CASE_  ,					out_image=os.path.join(SCREAMING_SNAKE_CASE_  ,					"pr_exact.png"					)  ,					title="Precision-Recall curve for Exact Match score"  ,					)
			lowercase__   					=			make_precision_recall_eval(
			    SCREAMING_SNAKE_CASE_  ,					SCREAMING_SNAKE_CASE_  ,					SCREAMING_SNAKE_CASE_  ,					SCREAMING_SNAKE_CASE_  ,					out_image=os.path.join(SCREAMING_SNAKE_CASE_  ,					"pr_f1.png"					)  ,					title="Precision-Recall curve for F1 score"  ,					)
			lowercase__   					=			{k: float(SCREAMING_SNAKE_CASE_					) for k, v in qid_to_has_ans.items()}
			lowercase__   					=			make_precision_recall_eval(
			    SCREAMING_SNAKE_CASE_  ,					SCREAMING_SNAKE_CASE_  ,					SCREAMING_SNAKE_CASE_  ,					SCREAMING_SNAKE_CASE_  ,					out_image=os.path.join(SCREAMING_SNAKE_CASE_  ,					"pr_oracle.png"					)  ,					title="Oracle Precision-Recall curve (binary task of HasAns vs. NoAns)"  ,					)
			merge_eval(SCREAMING_SNAKE_CASE_  ,					SCREAMING_SNAKE_CASE_  ,					"pr_exact"					)
			merge_eval(SCREAMING_SNAKE_CASE_  ,					SCREAMING_SNAKE_CASE_  ,					"pr_f1"					)
			merge_eval(SCREAMING_SNAKE_CASE_  ,					SCREAMING_SNAKE_CASE_  ,					"pr_oracle"					)



def __lowerCAmelCase	(       SCREAMING_SNAKE_CASE_  ,					SCREAMING_SNAKE_CASE_  ,					SCREAMING_SNAKE_CASE_  ,					SCREAMING_SNAKE_CASE_					):
			if not qid_list:
						return
			lowercase__   					=			[na_probs[k] for k in qid_list]
			lowercase__   					=			np.ones_like(SCREAMING_SNAKE_CASE_					) / float(len(SCREAMING_SNAKE_CASE_					)					)
			plt.hist(SCREAMING_SNAKE_CASE_  ,					weights=SCREAMING_SNAKE_CASE_  ,					bins=20  ,					range=(0.0, 1.0)					)
			plt.xlabel("Model probability of no-answer"					)
			plt.ylabel("Proportion of dataset"					)
			plt.title(f'''Histogram of no-answer probability: {name}'''					)
			plt.savefig(os.path.join(SCREAMING_SNAKE_CASE_  ,					f'''na_prob_hist_{name}.png'''					)					)
			plt.clf()



def __lowerCAmelCase	(       SCREAMING_SNAKE_CASE_  ,					SCREAMING_SNAKE_CASE_  ,					SCREAMING_SNAKE_CASE_  ,					SCREAMING_SNAKE_CASE_					):
			lowercase__   					=			sum(1 for k in qid_to_has_ans if not qid_to_has_ans[k]					)
			lowercase__   					=			num_no_ans
			lowercase__   					=			cur_score
			lowercase__   					=			0.0
			lowercase__   					=			sorted(SCREAMING_SNAKE_CASE_  ,					key=lambda SCREAMING_SNAKE_CASE_					: na_probs[k]					)
			for i, qid in enumerate(SCREAMING_SNAKE_CASE_					):
						if qid not in scores:
									continue
						if qid_to_has_ans[qid]:
									lowercase__   					=			scores[qid]
						else:
									if preds[qid]:
												lowercase__   					=			-1
									else:
												lowercase__   					=			0
						cur_score += diff
						if cur_score > best_score:
									lowercase__   					=			cur_score
									lowercase__   					=			na_probs[qid]
			return 100.0 * best_score / len(SCREAMING_SNAKE_CASE_					), best_thresh



def __lowerCAmelCase	(       SCREAMING_SNAKE_CASE_  ,					SCREAMING_SNAKE_CASE_  ,					SCREAMING_SNAKE_CASE_  ,					SCREAMING_SNAKE_CASE_  ,					SCREAMING_SNAKE_CASE_  ,					SCREAMING_SNAKE_CASE_					):
			lowercase__					,    lowercase__   					=			find_best_thresh(SCREAMING_SNAKE_CASE_  ,					SCREAMING_SNAKE_CASE_  ,					SCREAMING_SNAKE_CASE_  ,					SCREAMING_SNAKE_CASE_					)
			lowercase__					,    lowercase__   					=			find_best_thresh(SCREAMING_SNAKE_CASE_  ,					SCREAMING_SNAKE_CASE_  ,					SCREAMING_SNAKE_CASE_  ,					SCREAMING_SNAKE_CASE_					)
			lowercase__   					=			best_exact
			lowercase__   					=			exact_thresh
			lowercase__   					=			best_fa
			lowercase__   					=			fa_thresh



def __lowerCAmelCase	(       ):
			with open(OPTS.data_file					) as f:
						lowercase__   					=			json.load(SCREAMING_SNAKE_CASE_					)
						lowercase__   					=			dataset_json["data"]
			with open(OPTS.pred_file					) as f:
						lowercase__   					=			json.load(SCREAMING_SNAKE_CASE_					)
			if OPTS.na_prob_file:
						with open(OPTS.na_prob_file					) as f:
									lowercase__   					=			json.load(SCREAMING_SNAKE_CASE_					)
			else:
						lowercase__   					=			{k: 0.0 for k in preds}
			lowercase__   					=			make_qid_to_has_ans(SCREAMING_SNAKE_CASE_					)  # maps qid to True/False
			lowercase__   					=			[k for k, v in qid_to_has_ans.items() if v]
			lowercase__   					=			[k for k, v in qid_to_has_ans.items() if not v]
			lowercase__					,    lowercase__   					=			get_raw_scores(SCREAMING_SNAKE_CASE_  ,					SCREAMING_SNAKE_CASE_					)
			lowercase__   					=			apply_no_ans_threshold(SCREAMING_SNAKE_CASE_  ,					SCREAMING_SNAKE_CASE_  ,					SCREAMING_SNAKE_CASE_  ,					OPTS.na_prob_thresh					)
			lowercase__   					=			apply_no_ans_threshold(SCREAMING_SNAKE_CASE_  ,					SCREAMING_SNAKE_CASE_  ,					SCREAMING_SNAKE_CASE_  ,					OPTS.na_prob_thresh					)
			lowercase__   					=			make_eval_dict(SCREAMING_SNAKE_CASE_  ,					SCREAMING_SNAKE_CASE_					)
			if has_ans_qids:
						lowercase__   					=			make_eval_dict(SCREAMING_SNAKE_CASE_  ,					SCREAMING_SNAKE_CASE_  ,					qid_list=SCREAMING_SNAKE_CASE_					)
						merge_eval(SCREAMING_SNAKE_CASE_  ,					SCREAMING_SNAKE_CASE_  ,					"HasAns"					)
			if no_ans_qids:
						lowercase__   					=			make_eval_dict(SCREAMING_SNAKE_CASE_  ,					SCREAMING_SNAKE_CASE_  ,					qid_list=SCREAMING_SNAKE_CASE_					)
						merge_eval(SCREAMING_SNAKE_CASE_  ,					SCREAMING_SNAKE_CASE_  ,					"NoAns"					)
			if OPTS.na_prob_file:
						find_all_best_thresh(SCREAMING_SNAKE_CASE_  ,					SCREAMING_SNAKE_CASE_  ,					SCREAMING_SNAKE_CASE_  ,					SCREAMING_SNAKE_CASE_  ,					SCREAMING_SNAKE_CASE_  ,					SCREAMING_SNAKE_CASE_					)
			if OPTS.na_prob_file and OPTS.out_image_dir:
						run_precision_recall_analysis(SCREAMING_SNAKE_CASE_  ,					SCREAMING_SNAKE_CASE_  ,					SCREAMING_SNAKE_CASE_  ,					SCREAMING_SNAKE_CASE_  ,					SCREAMING_SNAKE_CASE_  ,					OPTS.out_image_dir					)
						histogram_na_prob(SCREAMING_SNAKE_CASE_  ,					SCREAMING_SNAKE_CASE_  ,					OPTS.out_image_dir  ,					"hasAns"					)
						histogram_na_prob(SCREAMING_SNAKE_CASE_  ,					SCREAMING_SNAKE_CASE_  ,					OPTS.out_image_dir  ,					"noAns"					)
			if OPTS.out_file:
						with open(OPTS.out_file  ,					"w"					) as f:
									json.dump(SCREAMING_SNAKE_CASE_  ,					SCREAMING_SNAKE_CASE_					)
			else:
						print(json.dumps(SCREAMING_SNAKE_CASE_  ,					indent=2					)					)


if __name__ == "__main__":
							lowercase_						=       parse_args()
							if OPTS.out_image_dir:
														import matplotlib

														matplotlib.use("""Agg""")
														import matplotlib.pyplot as plt
							main()









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

import torch
from datasets import load_dataset
from torchvision.transforms import Compose, Lambda, Normalize, RandomHorizontalFlip, RandomResizedCrop, ToTensor
from torchvision.transforms.functional import InterpolationMode

import transformers
from transformers import (
    HfArgumentParser,
    Trainer,
    TrainingArguments,
    ViTImageProcessor,
    ViTMAEConfig,
    ViTMAEForPreTraining,
)
from transformers.trainer_utils import get_last_checkpoint
from transformers.utils import check_min_version, send_example_telemetry
from transformers.utils.versions import require_version
lowercase_						=       logging.getLogger(__name__)

# Will error if the minimal version of Transformers is not installed. Remove at your own risks.
check_min_version("""4.31.0""")

require_version("""datasets>=1.8.0""", """To fix: pip install -r examples/pytorch/image-pretraining/requirements.txt""")
@dataclass
class 			_snake_case     :
				UpperCamelCase__			:   Optional[str]       						=field(
				    default="""cifar10"""      ,		metadata={"""help""": """Name of a dataset from the datasets package"""})
				UpperCamelCase__			:   Optional[str]       						=field(
				    default=lowercase__      ,		metadata={"""help""": """The configuration name of the dataset to use (via the datasets library)."""})
				UpperCamelCase__			:   Optional[str]       						=field(
				    default=lowercase__      ,		metadata={"""help""": """The column name of the images in the files."""})
				UpperCamelCase__			:   Optional[str]       						=field(default=lowercase__      ,		metadata={"""help""": """A folder containing the training data."""})
				UpperCamelCase__			:   Optional[str]       						=field(default=lowercase__      ,		metadata={"""help""": """A folder containing the validation data."""})
				UpperCamelCase__			:   Optional[float]       						=field(
				    default=0.15      ,		metadata={"""help""": """Percent to split off of train for validation."""})
				UpperCamelCase__			:   Optional[int]       						=field(
				    default=lowercase__      ,		metadata={
				        """help""": (
				            """For debugging purposes or quicker training, truncate the number of training examples to this """
				            """value if set."""
				        )
				    }      ,		)
				UpperCamelCase__			:   Optional[int]       						=field(
				    default=lowercase__      ,		metadata={
				        """help""": (
				            """For debugging purposes or quicker training, truncate the number of evaluation examples to this """
				            """value if set."""
				        )
				    }      ,		)




				def 							A__ (  self   :  Tuple  ):
							lowercase__   					=			{}
							if self.train_dir is not None:
										lowercase__   					=			self.train_dir
							if self.validation_dir is not None:
										lowercase__   					=			self.validation_dir
							lowercase__   					=			data_files if data_files else None
@dataclass
class 			_snake_case     :
				UpperCamelCase__			:   str       						=field(
				    default=lowercase__      ,		metadata={
				        """help""": (
				            """The model checkpoint for weights initialization.Don't set if you want to train a model from scratch."""
				        )
				    }      ,		)
				UpperCamelCase__			:   Optional[str]       						=field(
				    default=lowercase__      ,		metadata={"""help""": """Pretrained config name or path if not the same as model_name_or_path"""})
				UpperCamelCase__			:   Optional[str]       						=field(
				    default=lowercase__      ,		metadata={
				        """help""": (
				            """Override some existing default config settings when a model is trained from scratch. Example: """
				            """n_embd=10,resid_pdrop=0.2,scale_attn_weights=false,summary_type=cls_index"""
				        )
				    }      ,		)
				UpperCamelCase__			:   Optional[str]       						=field(
				    default=lowercase__      ,		metadata={"""help""": """Where do you want to store the pretrained models downloaded from s3"""})
				UpperCamelCase__			:   str       						=field(
				    default="""main"""      ,		metadata={"""help""": """The specific model version to use (can be a branch name, tag name or commit id)."""}      ,		)
				UpperCamelCase__			:   str       						=field(default=lowercase__      ,		metadata={"""help""": """Name or path of preprocessor config."""})
				UpperCamelCase__			:   bool       						=field(
				    default=lowercase__      ,		metadata={
				        """help""": (
				            """Will use the token generated when running `huggingface-cli login` (necessary to use this script """
				            """with private models)."""
				        )
				    }      ,		)
				UpperCamelCase__			:   float       						=field(
				    default=0.75      ,		metadata={"""help""": """The ratio of the number of masked tokens in the input sequence."""})
				UpperCamelCase__			:   bool       						=field(
				    default=lowercase__      ,		metadata={"""help""": """Whether or not to train with normalized pixel values as target."""})
@dataclass
class 			_snake_case     (   lowercase__):
				UpperCamelCase__			:   float       						=field(
				    default=1E-3      ,		metadata={"""help""": """Base learning rate: absolute_lr = base_lr * total_batch_size / 256."""})



def __lowerCAmelCase	(       SCREAMING_SNAKE_CASE_					):
			lowercase__   					=			torch.stack([example["pixel_values"] for example in examples]					)
			return {"pixel_values": pixel_values}



def __lowerCAmelCase	(       ):
			# 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.

			lowercase__   					=			HfArgumentParser((ModelArguments, DataTrainingArguments, CustomTrainingArguments)					)
			if len(sys.argv					) == 2 and sys.argv[1].endswith(".json"					):
						# If we pass only one argument to the script and it's the path to a json file,
						# let's parse it to get our arguments.
						lowercase__					,    lowercase__					,    lowercase__   					=			parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]					)					)
			else:
						lowercase__					,    lowercase__					,    lowercase__   					=			parser.parse_args_into_dataclasses()

			# Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
			# information sent is the one passed as arguments along with your Python/PyTorch versions.
			send_example_telemetry("run_mae"  ,					SCREAMING_SNAKE_CASE_  ,					SCREAMING_SNAKE_CASE_					)

			# Setup logging
			logging.basicConfig(
			    format="%(asctime)s - %(levelname)s - %(name)s - %(message)s"  ,					datefmt="%m/%d/%Y %H:%M:%S"  ,					handlers=[logging.StreamHandler(sys.stdout					)]  ,					)

			if training_args.should_log:
						# The default of training_args.log_level is passive, so we set log level at info here to have that default.
						transformers.utils.logging.set_verbosity_info()

			lowercase__   					=			training_args.get_process_log_level()
			logger.setLevel(SCREAMING_SNAKE_CASE_					)
			transformers.utils.logging.set_verbosity(SCREAMING_SNAKE_CASE_					)
			transformers.utils.logging.enable_default_handler()
			transformers.utils.logging.enable_explicit_format()

			# Log on each process the small summary:
			logger.warning(
			    f'''Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}'''
			    + f'''distributed training: {bool(training_args.local_rank != -1					)}, 16-bits training: {training_args.fpaa}'''					)
			logger.info(f'''Training/evaluation parameters {training_args}'''					)

			# Detecting last checkpoint.
			lowercase__   					=			None
			if os.path.isdir(training_args.output_dir					) and training_args.do_train and not training_args.overwrite_output_dir:
						lowercase__   					=			get_last_checkpoint(training_args.output_dir					)
						if last_checkpoint is None and len(os.listdir(training_args.output_dir					)					) > 0:
									raise ValueError(
									    f'''Output directory ({training_args.output_dir}) already exists and is not empty. '''
									    "Use --overwrite_output_dir to overcome."					)
						elif last_checkpoint is not None and training_args.resume_from_checkpoint is None:
									logger.info(
									    f'''Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change '''
									    "the `--output_dir` or add `--overwrite_output_dir` to train from scratch."					)

    # Initialize our dataset.
			lowercase__   					=			load_dataset(
			    data_args.dataset_name  ,					data_args.dataset_config_name  ,					data_files=data_args.data_files  ,					cache_dir=model_args.cache_dir  ,					use_auth_token=True if model_args.use_auth_token else None  ,					)

			# If we don't have a validation split, split off a percentage of train as validation.
			lowercase__   					=			None if "validation" in ds.keys() else data_args.train_val_split
			if isinstance(data_args.train_val_split  ,					SCREAMING_SNAKE_CASE_					) and data_args.train_val_split > 0.0:
						lowercase__   					=			ds["train"].train_test_split(data_args.train_val_split					)
						lowercase__   					=			split["train"]
						lowercase__   					=			split["test"]

			# Load pretrained model and image processor
			#
			# Distributed training:
			# The .from_pretrained methods guarantee that only one local process can concurrently
			# download model & vocab.
			lowercase__   					=			{
			    "cache_dir": model_args.cache_dir,
			    "revision": model_args.model_revision,
			    "use_auth_token": True if model_args.use_auth_token else None,
			}
			if model_args.config_name:
						lowercase__   					=			ViTMAEConfig.from_pretrained(model_args.config_name  ,					**SCREAMING_SNAKE_CASE_					)
			elif model_args.model_name_or_path:
						lowercase__   					=			ViTMAEConfig.from_pretrained(model_args.model_name_or_path  ,					**SCREAMING_SNAKE_CASE_					)
			else:
						lowercase__   					=			ViTMAEConfig()
						logger.warning("You are instantiating a new config instance from scratch."					)
						if model_args.config_overrides is not None:
									logger.info(f'''Overriding config: {model_args.config_overrides}'''					)
									config.update_from_string(model_args.config_overrides					)
									logger.info(f'''New config: {config}'''					)

    # adapt config
			config.update(
			    {
			        "mask_ratio": model_args.mask_ratio,
			        "norm_pix_loss": model_args.norm_pix_loss,
			    }					)

			# create image processor
			if model_args.image_processor_name:
						lowercase__   					=			ViTImageProcessor.from_pretrained(model_args.image_processor_name  ,					**SCREAMING_SNAKE_CASE_					)
			elif model_args.model_name_or_path:
						lowercase__   					=			ViTImageProcessor.from_pretrained(model_args.model_name_or_path  ,					**SCREAMING_SNAKE_CASE_					)
			else:
						lowercase__   					=			ViTImageProcessor()

			# create model
			if model_args.model_name_or_path:
						lowercase__   					=			ViTMAEForPreTraining.from_pretrained(
						    model_args.model_name_or_path  ,					from_tf=bool(".ckpt" in model_args.model_name_or_path					)  ,					config=SCREAMING_SNAKE_CASE_  ,					cache_dir=model_args.cache_dir  ,					revision=model_args.model_revision  ,					use_auth_token=True if model_args.use_auth_token else None  ,					)
			else:
						logger.info("Training new model from scratch"					)
						lowercase__   					=			ViTMAEForPreTraining(SCREAMING_SNAKE_CASE_					)

			if training_args.do_train:
						lowercase__   					=			ds["train"].column_names
			else:
						lowercase__   					=			ds["validation"].column_names

			if data_args.image_column_name is not None:
						lowercase__   					=			data_args.image_column_name
			elif "image" in column_names:
						lowercase__   					=			"image"
			elif "img" in column_names:
						lowercase__   					=			"img"
			else:
						lowercase__   					=			column_names[0]

			# transformations as done in original MAE paper
			# source: https://github.com/facebookresearch/mae/blob/main/main_pretrain.py
			if "shortest_edge" in image_processor.size:
						lowercase__   					=			image_processor.size["shortest_edge"]
			else:
						lowercase__   					=			(image_processor.size["height"], image_processor.size["width"])
			lowercase__   					=			Compose(
			    [
			        Lambda(lambda SCREAMING_SNAKE_CASE_					: img.convert("RGB"					) if img.mode != "RGB" else img					),
			        RandomResizedCrop(SCREAMING_SNAKE_CASE_  ,					scale=(0.2, 1.0)  ,					interpolation=InterpolationMode.BICUBIC					),
			        RandomHorizontalFlip(),
			        ToTensor(),
			        Normalize(mean=image_processor.image_mean  ,					std=image_processor.image_std					),
			    ]					)

			def preprocess_images(SCREAMING_SNAKE_CASE_					):
						lowercase__   					=			[transforms(SCREAMING_SNAKE_CASE_					) for image in examples[image_column_name]]
						return examples

			if training_args.do_train:
						if "train" not in ds:
									raise ValueError("--do_train requires a train dataset"					)
						if data_args.max_train_samples is not None:
									lowercase__   					=			ds["train"].shuffle(seed=training_args.seed					).select(range(data_args.max_train_samples					)					)
						# Set the training transforms
						ds["train"].set_transform(SCREAMING_SNAKE_CASE_					)

			if training_args.do_eval:
						if "validation" not in ds:
									raise ValueError("--do_eval requires a validation dataset"					)
						if data_args.max_eval_samples is not None:
									lowercase__   					=			(
									    ds["validation"].shuffle(seed=training_args.seed					).select(range(data_args.max_eval_samples					)					)
									)
						# Set the validation transforms
						ds["validation"].set_transform(SCREAMING_SNAKE_CASE_					)

			# Compute absolute learning rate
			lowercase__   					=			(
			    training_args.train_batch_size * training_args.gradient_accumulation_steps * training_args.world_size
			)
			if training_args.base_learning_rate is not None:
						lowercase__   					=			training_args.base_learning_rate * total_train_batch_size / 256

			# Initialize our trainer
			lowercase__   					=			Trainer(
			    model=SCREAMING_SNAKE_CASE_  ,					args=SCREAMING_SNAKE_CASE_  ,					train_dataset=ds["train"] if training_args.do_train else None  ,					eval_dataset=ds["validation"] if training_args.do_eval else None  ,					tokenizer=SCREAMING_SNAKE_CASE_  ,					data_collator=SCREAMING_SNAKE_CASE_  ,					)

			# Training
			if training_args.do_train:
						lowercase__   					=			None
						if training_args.resume_from_checkpoint is not None:
									lowercase__   					=			training_args.resume_from_checkpoint
						elif last_checkpoint is not None:
									lowercase__   					=			last_checkpoint
						lowercase__   					=			trainer.train(resume_from_checkpoint=SCREAMING_SNAKE_CASE_					)
						trainer.save_model()
						trainer.log_metrics("train"  ,					train_result.metrics					)
						trainer.save_metrics("train"  ,					train_result.metrics					)
						trainer.save_state()

			# Evaluation
			if training_args.do_eval:
						lowercase__   					=			trainer.evaluate()
						trainer.log_metrics("eval"  ,					SCREAMING_SNAKE_CASE_					)
						trainer.save_metrics("eval"  ,					SCREAMING_SNAKE_CASE_					)

			# Write model card and (optionally) push to hub
			lowercase__   					=			{
			    "tasks": "masked-auto-encoding",
			    "dataset": data_args.dataset_name,
			    "tags": ["masked-auto-encoding"],
			}
			if training_args.push_to_hub:
						trainer.push_to_hub(**SCREAMING_SNAKE_CASE_					)
			else:
						trainer.create_model_card(**SCREAMING_SNAKE_CASE_					)



def __lowerCAmelCase	(       SCREAMING_SNAKE_CASE_					):
			# For xla_spawn (TPUs)
			main()


if __name__ == "__main__":
							main()




