




# HF Trainer benchmarking tool
#
# This tool can be used to run and compare multiple dimensions of the HF Trainers args.
#
# It then prints a report once in github format with all the information that needs to be shared
# with others and second time in a console-friendly format, so it's easier to use for tuning things up.
#
# The main idea is:
#
#     ./trainer-benchmark.py --base-cmd '<cmd args that don't change>' \
#     --variations '--tf32 0|--tf32 1' '--fp16 0|--fp16 1|--bf16 1' \
#     --target-metric-key train_samples_per_second
#
# The variations can be any command line argument that you want to compare and not just dtype as in
# the example.
#
# --variations allows you to compare variations in multiple dimensions.
#
# as the first dimention has 2 options and the second 3 in our example, this will run the trainer 6
# times adding one of:
#
#    1. --tf32 0 --fp16 0
#    2. --tf32 0 --fp16 1
#    3. --tf32 0 --bf16 1
#    4. --tf32 1 --fp16 0
#    5. --tf32 1 --fp16 1
#    6. --tf32 1 --bf16 1
#
# and print the results. This is just a cartesian product - and more than 2 dimensions can be used.
#
# If you want to rely on defaults, this:
#    --variations '--tf32 0|--tf32 1' '--fp16 0|--fp16 1|--bf16 1'
# is identical to this:
#    --variations '--tf32 0|--tf32 1' '|--fp16|--bf16'
#
# the leading empty variation in the 2nd dimension is a valid variation.
#
# So here we get the following 6 variations:
#
#    1. --tf32 0
#    2. --tf32 0 --fp16
#    3. --tf32 0 --bf16
#    4. --tf32 1
#    5. --tf32 1 --fp16
#    6. --tf32 1 --bf16
#
# In this particular case we don't know what the default tf32 setting is as it's normally
# pytorch-version dependent). That's why it's best to do an explicit setting of each variation:
#    `--tf32 0|--tf32 1`
#
# Here is a full example of a train:
#
# CUDA_VISIBLE_DEVICES=0 python ./scripts/benchmark/trainer-benchmark.py \
# --base-cmd \
# ' examples/pytorch/translation/run_translation.py --model_name_or_path t5-small \
# --output_dir output_dir --do_train --label_smoothing 0.1 --logging_strategy no \
# --save_strategy no --per_device_train_batch_size 32 --max_source_length 512 \
# --max_target_length 512 --num_train_epochs 1 --overwrite_output_dir \
# --source_lang en --target_lang ro --dataset_name wmt16 --dataset_config "ro-en" \
# --source_prefix "translate English to Romanian: " --warmup_steps 50 \
# --max_train_samples 20000 --dataloader_num_workers 2 ' \
# --target-metric-key train_samples_per_second --repeat-times 1 --variations \
# '|--fp16|--bf16' '--tf32 0|--tf32 1' --report-metric-keys train_loss \
# --repeat-times 1 --base-variation '--tf32 0'
#
# and here is a possible output:
#
#
# | Variation       |     Train |   Diff |   Train |
# |                 |   samples |      % |    loss |
# |                 |       per |        |         |
# |                 |    second |        |         |
# |:----------------|----------:|-------:|--------:|
# | --tf32 0        |    285.11 |      0 |    2.51 |
# | --tf32 1        |    342.09 |     20 |    2.51 |
# | --fp16 --tf32 0 |    423.49 |     49 |    2.51 |
# | --fp16 --tf32 1 |    423.13 |     48 |    2.51 |
# | --bf16 --tf32 0 |    416.80 |     46 |    2.52 |
# | --bf16 --tf32 1 |    415.87 |     46 |    2.52 |
#
#
# So you can quickly compare the different outcomes.
#
# Typically running each experiment once is enough, but if the environment is unstable you can
# re-run each multiple times, e.g., 3 using --repeat-times 3 and it will report the averaged results.
#
# By default it'll use the lowest result as the base line to use as 100% and then compare the rest to
# it as can be seen from the table above, but you can also specify which combination is the one to use as
# the baseline, e.g., to change to another entry use: --base-variation '--tf32 1 --fp16 0'
#
# --target-metric-key is there to tell the program which metrics to compare - the different metric keys are
# inside output_dir/all_results.json. e.g., to measure eval performance instead of train use:
#    --target-metric-key eval_samples_per_second
# but of course you will need to adjust the --base-cmd value in the example to perform evaluation as
# well (as currently it doesn't)
#

import argparse
import datetime
import io
import itertools
import json
import math
import os
import platform
import re
import shlex
import subprocess
import sys
from pathlib import Path
from statistics import fmean

import pandas as pd
import torch
from tqdm import tqdm

import transformers


lowercase__				:     Union[str, Any] 		=						float("nan")
class 		UpperCAmelCase   :







						'''simple docstring'''





						def __init__(						self							:     Optional[Any]       ,	__lowercase							:     str						):






							"""simple docstring"""






							snake_case_		    =     sys.stdout
							snake_case_		    =     open(SCREAMING_SNAKE_CASE__       ,	"a"						)






						def __getattr__(						self							:     Dict       ,	__lowercase							:     Any						):






							"""simple docstring"""






							return getattr(self.stdout       ,	SCREAMING_SNAKE_CASE__						)






						def        snake_case__						(						self							:     Optional[Any]       ,	__lowercase							:     Dict						):






							"""simple docstring"""






							self.stdout.write(SCREAMING_SNAKE_CASE__						)
							# strip tqdm codes
							self.file.write(re.sub(r"^.*\r"       ,	""       ,	SCREAMING_SNAKE_CASE__       ,	0       ,	re.M						)						)







def 						lowerCamelCase__    (		_A=80     ,	_A=False							):







	'''simple docstring'''





	snake_case_		    =     []

	# deal with critical env vars
	snake_case_		    =     ["CUDA_VISIBLE_DEVICES"]
	for key in env_keys:
		snake_case_		    =     os.environ.get(__lowerCAmelCase     ,	__lowerCAmelCase							)
		if val is not None:
			cmd.append(f"{key}={val}"							)

    # python executable (not always needed if the script is executable)
	snake_case_		    =     sys.executable if full_python_path else sys.executable.split("/"							)[-1]
	cmd.append(__lowerCAmelCase							)

	# now the normal args
	cmd += list(map(shlex.quote     ,	sys.argv							)							)

	# split up into up to MAX_WIDTH lines with shell multi-line escapes
	snake_case_		    =     []
	snake_case_		    =     ""
	while len(__lowerCAmelCase							) > 0:
		current_line += f"{cmd.pop(0							)} "
		if len(__lowerCAmelCase							) == 0 or len(__lowerCAmelCase							) + len(cmd[0]							) + 1 > max_width - 1:
			lines.append(__lowerCAmelCase							)
			snake_case_		    =     ""
	return "\\\n".join(__lowerCAmelCase							)


def 						lowerCamelCase__    (		_A     ,	_A							):







	'''simple docstring'''





	snake_case_		    =     re.sub(R"[\\\n]+"     ,	" "     ,	args.base_cmd							)

	# remove --output_dir if any and set our own
	snake_case_		    =     re.sub("--output_dir\s+[^\s]+"     ,	""     ,	args.base_cmd							)
	args.base_cmd += f" --output_dir {output_dir}"

	# ensure we have --overwrite_output_dir
	snake_case_		    =     re.sub("--overwrite_output_dir\s+"     ,	""     ,	args.base_cmd							)
	args.base_cmd += " --overwrite_output_dir"

	return [sys.executable] + shlex.split(args.base_cmd							)


def 						lowerCamelCase__    (		_A     ,	_A     ,	_A     ,	_A     ,	_A     ,	_A     ,	_A							):







	'''simple docstring'''





	if 0:
		import random
		from time import sleep

		sleep(0							)
		return dict(
		    {k: random.uniform(0     ,	100							) for k in metric_keys}     ,	**{target_metric_key: random.choice([nan, 10.31, 1_00.2, 55.66_66, 2_22.22_22_22_22]							)}     ,	)

	snake_case_		    =     subprocess.run(__lowerCAmelCase     ,	capture_output=__lowerCAmelCase     ,	text=__lowerCAmelCase							)

	if verbose:
		print("STDOUT"     ,	result.stdout							)
		print("STDERR"     ,	result.stderr							)

	# save the streams
	snake_case_		    =     variation.replace(" "     ,	"-"							)
	with open(Path(__lowerCAmelCase							) / f"log.{prefix}.stdout.txt"     ,	"w"							) as f:
		f.write(result.stdout							)
	with open(Path(__lowerCAmelCase							) / f"log.{prefix}.stderr.txt"     ,	"w"							) as f:
		f.write(result.stderr							)

	if result.returncode != 0:
		if verbose:
			print("failed"							)
		return {target_metric_key: nan}

	with io.open(f"{output_dir}/all_results.json"     ,	"r"     ,	encoding="utf-8"							) as f:
		snake_case_		    =     json.load(__lowerCAmelCase							)

	# filter out just the keys we want
	return {k: v for k, v in metrics.items() if k in metric_keys}


def 						lowerCamelCase__    (		_A     ,	_A     ,	_A     ,	_A     ,	_A     ,	_A     ,	_A     ,	_A     ,	_A     ,	_A     ,	):







	'''simple docstring'''





	snake_case_		    =     []
	snake_case_		    =     []
	snake_case_		    =     f"{id}: {variation:<{longest_variation_len}}"
	snake_case_		    =     f"{preamble}: "
	snake_case_		    =     set(report_metric_keys + [target_metric_key]							)
	for i in tqdm(range(__lowerCAmelCase							)     ,	desc=__lowerCAmelCase     ,	leave=__lowerCAmelCase							):
		snake_case_		    =     process_run_single(
		    __lowerCAmelCase     ,	__lowerCAmelCase     ,	__lowerCAmelCase     ,	__lowerCAmelCase     ,	__lowerCAmelCase     ,	__lowerCAmelCase     ,	__lowerCAmelCase							)
		snake_case_		    =     single_run_metrics[target_metric_key]
		if not math.isnan(__lowerCAmelCase							):
			metrics.append(__lowerCAmelCase							)
			results.append(__lowerCAmelCase							)
			outcome += "✓"
		else:
			outcome += "✘"
	snake_case_		    =     f"\33[2K\r{outcome}"
	if len(__lowerCAmelCase							) > 0:
		snake_case_		    =     {k: fmean([x[k] for x in metrics]							) for k in metrics[0].keys()}
		snake_case_		    =     round(mean_metrics[target_metric_key]     ,	2							)
		snake_case_		    =     f"{outcome} {mean_target}"
		if len(__lowerCAmelCase							) > 1:
			results_str += f" {tuple(round(__lowerCAmelCase     ,	2							) for x in results							)}"
		print(__lowerCAmelCase							)
		snake_case_		    =     variation
		return mean_metrics
	else:
		print(__lowerCAmelCase							)
		return {variation_key: variation, target_metric_key: nan}


def 						lowerCamelCase__    (		):







	'''simple docstring'''





	snake_case_		    =     torch.cuda.get_device_properties(torch.device("cuda"							)							)
	return f"\nDatetime    : {datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'							)}\n\nSoftware:\ntransformers: {transformers.__version__}\ntorch       : {torch.__version__}\ncuda        : {torch.version.cuda}\npython      : {platform.python_version()}\n\nHardware:\n{torch.cuda.device_count()} GPUs      : {properties.name}, {properties.total_memory/2**30:0.2f}GB\n"


def 						lowerCamelCase__    (		_A     ,	_A     ,	_A     ,	_A     ,	_A							):







	'''simple docstring'''





	snake_case_		    =     pd.DataFrame(__lowerCAmelCase							)
	snake_case_		    =     "variation"
	snake_case_		    =     "diff_%"

	snake_case_		    =     nan
	if base_variation is not None and len(df[df[variation_key] == base_variation]							):
		# this may still return nan
		snake_case_		    =     df.loc[df[variation_key] == base_variation][target_metric_key].item()
	if math.isnan(__lowerCAmelCase							):
		# as a fallback, use the minimal value as the sentinel
		snake_case_		    =     df.loc[df[target_metric_key] != nan][target_metric_key].min()

	# create diff column if possible
	if not math.isnan(__lowerCAmelCase							):
		snake_case_		    =     df.apply(
		    lambda _A							: round(100 * (r[target_metric_key] - sentinel_value) / sentinel_value							)
		    if not math.isnan(r[target_metric_key]							)
		    else 0     ,	axis="columns"     ,	)

	# re-order columns
	snake_case_		    =     [variation_key, target_metric_key, diff_key, *report_metric_keys]
	snake_case_		    =     df.reindex(__lowerCAmelCase     ,	axis="columns"							)  # reorder cols

	# capitalize
	snake_case_		    =     df.rename(str.capitalize     ,	axis="columns"							)

	# make the cols as narrow as possible
	snake_case_		    =     df.rename(lambda _A							: c.replace("_"     ,	"<br>"							)     ,	axis="columns"							)
	snake_case_		    =     df.rename(lambda _A							: c.replace("_"     ,	"\n"							)     ,	axis="columns"							)

	snake_case_		    =     ["", "Copy between the cut-here-lines and paste as is to github or a forum"]
	report += ["----------8<-----------------8<--------"]
	report += ["*** Results:", df_github.to_markdown(index=__lowerCAmelCase     ,	floatfmt=".2f"							)]
	report += ["```"]
	report += ["*** Setup:", get_versions()]
	report += ["*** The benchmark command line was:", get_original_command()]
	report += ["```"]
	report += ["----------8<-----------------8<--------"]
	report += ["*** Results (console):", df_console.to_markdown(index=__lowerCAmelCase     ,	floatfmt=".2f"							)]

	print("\n\n".join(__lowerCAmelCase							)							)


def 						lowerCamelCase__    (		):







	'''simple docstring'''





	snake_case_		    =     argparse.ArgumentParser()
	parser.add_argument(
	    "--base-cmd"     ,	default=__lowerCAmelCase     ,	type=__lowerCAmelCase     ,	required=__lowerCAmelCase     ,	help="Base cmd"     ,	)
	parser.add_argument(
	    "--variations"     ,	default=__lowerCAmelCase     ,	type=__lowerCAmelCase     ,	nargs="+"     ,	required=__lowerCAmelCase     ,	help="Multi-dimensional variations, example: \'|--fp16|--bf16\' \'|--tf32\'"     ,	)
	parser.add_argument(
	    "--base-variation"     ,	default=__lowerCAmelCase     ,	type=__lowerCAmelCase     ,	help="Baseline variation to compare to. if None the minimal target value will be used to compare against"     ,	)
	parser.add_argument(
	    "--target-metric-key"     ,	default=__lowerCAmelCase     ,	type=__lowerCAmelCase     ,	required=__lowerCAmelCase     ,	help="Target metric key in output_dir/all_results.json, e.g., train_samples_per_second"     ,	)
	parser.add_argument(
	    "--report-metric-keys"     ,	default=""     ,	type=__lowerCAmelCase     ,	help="Report metric keys - other metric keys from output_dir/all_results.json to report, e.g., train_loss. Use a single argument e.g., \'train_loss train_samples"     ,	)
	parser.add_argument(
	    "--repeat-times"     ,	default=1     ,	type=__lowerCAmelCase     ,	help="How many times to re-run each variation - an average will be reported"     ,	)
	parser.add_argument(
	    "--output_dir"     ,	default="output_benchmark"     ,	type=__lowerCAmelCase     ,	help="The output directory where all the benchmark reports will go to and additionally this directory will be used to override --output_dir in the script that is being benchmarked"     ,	)
	parser.add_argument(
	    "--verbose"     ,	default=__lowerCAmelCase     ,	action="store_true"     ,	help="Whether to show the outputs of each run or just the benchmark progress"     ,	)
	snake_case_		    =     parser.parse_args()

	snake_case_		    =     args.output_dir
	Path(__lowerCAmelCase							).mkdir(exist_ok=__lowerCAmelCase							)
	snake_case_		    =     get_base_command(__lowerCAmelCase     ,	__lowerCAmelCase							)

	# split each dimension into its --foo variations
	snake_case_		    =     [list(map(str.strip     ,	re.split(R"\|"     ,	__lowerCAmelCase							)							)							) for x in args.variations]
	# build a cartesian product of dimensions and convert those back into cmd-line arg strings,
	# while stripping white space for inputs that were empty
	snake_case_		    =     list(map(str.strip     ,	map(" ".join     ,	itertools.product(*__lowerCAmelCase							)							)							)							)
	snake_case_		    =     max(len(__lowerCAmelCase							) for x in variations							)

	# split wanted keys
	snake_case_		    =     args.report_metric_keys.split()

	# capture prints into a log file for convenience
	snake_case_		    =     f"benchmark-report-{datetime.datetime.now().strftime('%Y-%m-%d-%H-%M-%S'							)}.txt"
	print(f"\nNote: each run\'s output is also logged under {output_dir}/log.*.std*.txt"							)
	print(f"and this script\'s output is also piped into {report_fn}"							)

	snake_case_		    =     Tee(__lowerCAmelCase							)

	print(f"\n*** Running {len(__lowerCAmelCase							)} benchmarks:"							)
	print(f"Base command: {' '.join(__lowerCAmelCase							)}"							)

	snake_case_		    =     "variation"
	snake_case_		    =     []
	for id, variation in enumerate(tqdm(__lowerCAmelCase     ,	desc="Total completion: "     ,	leave=__lowerCAmelCase							)							):
		snake_case_		    =     base_cmd + variation.split()
		results.append(
		    process_run(
		        id + 1     ,	__lowerCAmelCase     ,	__lowerCAmelCase     ,	__lowerCAmelCase     ,	__lowerCAmelCase     ,	args.target_metric_key     ,	__lowerCAmelCase     ,	args.repeat_times     ,	__lowerCAmelCase     ,	args.verbose     ,	)							)

	process_results(__lowerCAmelCase     ,	args.target_metric_key     ,	__lowerCAmelCase     ,	args.base_variation     ,	__lowerCAmelCase							)


if __name__ == "__main__":
		main()


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

import numpy as np


SCREAMING_SNAKE_CASE__   :			Union[str, Any]												=    re.compile(r"\b(a|an|the)\b", re.UNICODE)

SCREAMING_SNAKE_CASE__   :			int												=    None




def  __magic_name__ (   )			->   str:
				__lowerCamelCase    					=	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=__lowerCAmelCase		,  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=__lowerCAmelCase		,  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  __magic_name__ (   __lowerCAmelCase	:						List[str]							)			->   Union[str, Any]:
				__lowerCamelCase    					=	{}
				for article in dataset:
								for p in article["paragraphs"]:
												for qa in p["qas"]:
																__lowerCamelCase    					=	bool(qa['''answers''']['''text''']							)
				return qid_to_has_ans




def  __magic_name__ (   __lowerCAmelCase	:						Dict							)			->   Optional[Any]:

				def remove_articles(__lowerCAmelCase	:						Optional[int]							):
								return ARTICLES_REGEX.sub(''' '''		,  __lowerCAmelCase							)

				def white_space_fix(__lowerCAmelCase	:						Optional[int]							):
								return " ".join(text.split()							)

				def remove_punc(__lowerCAmelCase	:						Union[str, Any]							):
								__lowerCamelCase    					=	set(string.punctuation							)
								return "".join(ch for ch in text if ch not in exclude							)

				def lower(__lowerCAmelCase	:						Dict							):
								return text.lower()

				return white_space_fix(remove_articles(remove_punc(lower(__lowerCAmelCase							)							)							)							)




def  __magic_name__ (   __lowerCAmelCase	:						List[Any]							)			->   Optional[int]:
				if not s:
								return []
				return normalize_answer(__lowerCAmelCase							).split()




def  __magic_name__ (   __lowerCAmelCase	:						Tuple		,  __lowerCAmelCase	:						Tuple							)			->   int:
				return int(normalize_answer(__lowerCAmelCase							) == normalize_answer(__lowerCAmelCase							)							)




def  __magic_name__ (   __lowerCAmelCase	:						Any		,  __lowerCAmelCase	:						Tuple							)			->   str:
				__lowerCamelCase    					=	get_tokens(__lowerCAmelCase							)
				__lowerCamelCase    					=	get_tokens(__lowerCAmelCase							)
				__lowerCamelCase    					=	collections.Counter(__lowerCAmelCase							) & collections.Counter(__lowerCAmelCase							)
				__lowerCamelCase    					=	sum(common.values()							)
				if len(__lowerCAmelCase							) == 0 or len(__lowerCAmelCase							) == 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
				__lowerCamelCase    					=	1.0 * num_same / len(__lowerCAmelCase							)
				__lowerCamelCase    					=	1.0 * num_same / len(__lowerCAmelCase							)
				__lowerCamelCase    					=	(2 * precision * recall) / (precision + recall)
				return fa




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




def  __magic_name__ (   __lowerCAmelCase	:						Tuple		,  __lowerCAmelCase	:						str		,  __lowerCAmelCase	:						Optional[int]		,  __lowerCAmelCase	:						Union[str, Any]							)			->   List[str]:
				__lowerCamelCase    					=	{}
				for qid, s in scores.items():
								__lowerCamelCase    					=	na_probs[qid] > na_prob_thresh
								if pred_na:
												__lowerCamelCase    					=	float(not qid_to_has_ans[qid]							)
								else:
												__lowerCamelCase    					=	s
				return new_scores




def  __magic_name__ (   __lowerCAmelCase	:						List[Any]		,  __lowerCAmelCase	:						Optional[int]		,  __lowerCAmelCase	:						Optional[Any]=None							)			->   Union[str, Any]:
				if not qid_list:
								__lowerCamelCase    					=	len(__lowerCAmelCase							)
								return collections.OrderedDict(
								    [
								        ('''exact''', 100.0 * sum(exact_scores.values()							) / total),
								        ('''f1''', 100.0 * sum(fa_scores.values()							) / total),
								        ('''total''', total),
								    ]							)
				else:
								__lowerCamelCase    					=	len(__lowerCAmelCase							)
								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  __magic_name__ (   __lowerCAmelCase	:						Any		,  __lowerCAmelCase	:						str		,  __lowerCAmelCase	:						Optional[Any]							)			->   int:
				for k in new_eval:
								__lowerCamelCase    					=	new_eval[k]




def  __magic_name__ (   __lowerCAmelCase	:						Optional[int]		,  __lowerCAmelCase	:						List[Any]		,  __lowerCAmelCase	:						Dict		,  __lowerCAmelCase	:						Union[str, Any]							)			->   Optional[Any]:
				plt.step(__lowerCAmelCase		,  __lowerCAmelCase		,  color='''b'''		,  alpha=0.2		,  where='''post'''							)
				plt.fill_between(__lowerCAmelCase		,  __lowerCAmelCase		,  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(__lowerCAmelCase							)
				plt.savefig(__lowerCAmelCase							)
				plt.clf()




def  __magic_name__ (   __lowerCAmelCase	:						Any		,  __lowerCAmelCase	:						Optional[int]		,  __lowerCAmelCase	:						Tuple		,  __lowerCAmelCase	:						Tuple		,  __lowerCAmelCase	:						Optional[Any]=None		,  __lowerCAmelCase	:						Tuple=None							)			->   int:
				__lowerCamelCase    					=	sorted(__lowerCAmelCase		,  key=lambda __lowerCAmelCase							: na_probs[k]							)
				__lowerCamelCase    					=	0.0
				__lowerCamelCase    					=	1.0
				__lowerCamelCase    					=	0.0
				__lowerCamelCase    					=	[1.0]
				__lowerCamelCase    					=	[0.0]
				__lowerCamelCase    					=	0.0
				for i, qid in enumerate(__lowerCAmelCase							):
								if qid_to_has_ans[qid]:
												true_pos += scores[qid]
								__lowerCamelCase    					=	true_pos / float(i + 1							)
								__lowerCamelCase    					=	true_pos / float(__lowerCAmelCase							)
								if i == len(__lowerCAmelCase							) - 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(__lowerCAmelCase							)
												recalls.append(__lowerCAmelCase							)
				if out_image:
								plot_pr_curve(__lowerCAmelCase		,  __lowerCAmelCase		,  __lowerCAmelCase		,  __lowerCAmelCase							)
				return {"ap": 100.0 * avg_prec}




def  __magic_name__ (   __lowerCAmelCase	:						Optional[Any]		,  __lowerCAmelCase	:						List[str]		,  __lowerCAmelCase	:						Tuple		,  __lowerCAmelCase	:						List[str]		,  __lowerCAmelCase	:						List[Any]		,  __lowerCAmelCase	:						List[Any]							)			->   List[Any]:
				if out_image_dir and not os.path.exists(__lowerCAmelCase							):
								os.makedirs(__lowerCAmelCase							)
				__lowerCamelCase    					=	sum(1 for v in qid_to_has_ans.values() if v							)
				if num_true_pos == 0:
								return
				__lowerCamelCase    					=	make_precision_recall_eval(
				    __lowerCAmelCase		,  __lowerCAmelCase		,  __lowerCAmelCase		,  __lowerCAmelCase		,  out_image=os.path.join(__lowerCAmelCase		,  '''pr_exact.png'''							)		,  title='''Precision-Recall curve for Exact Match score'''		,  )
				__lowerCamelCase    					=	make_precision_recall_eval(
				    __lowerCAmelCase		,  __lowerCAmelCase		,  __lowerCAmelCase		,  __lowerCAmelCase		,  out_image=os.path.join(__lowerCAmelCase		,  '''pr_f1.png'''							)		,  title='''Precision-Recall curve for F1 score'''		,  )
				__lowerCamelCase    					=	{k: float(__lowerCAmelCase							) for k, v in qid_to_has_ans.items()}
				__lowerCamelCase    					=	make_precision_recall_eval(
				    __lowerCAmelCase		,  __lowerCAmelCase		,  __lowerCAmelCase		,  __lowerCAmelCase		,  out_image=os.path.join(__lowerCAmelCase		,  '''pr_oracle.png'''							)		,  title='''Oracle Precision-Recall curve (binary task of HasAns vs. NoAns)'''		,  )
				merge_eval(__lowerCAmelCase		,  __lowerCAmelCase		,  '''pr_exact'''							)
				merge_eval(__lowerCAmelCase		,  __lowerCAmelCase		,  '''pr_f1'''							)
				merge_eval(__lowerCAmelCase		,  __lowerCAmelCase		,  '''pr_oracle'''							)




def  __magic_name__ (   __lowerCAmelCase	:						Optional[Any]		,  __lowerCAmelCase	:						Any		,  __lowerCAmelCase	:						Optional[Any]		,  __lowerCAmelCase	:						int							)			->   Optional[Any]:
				if not qid_list:
								return
				__lowerCamelCase    					=	[na_probs[k] for k in qid_list]
				__lowerCamelCase    					=	np.ones_like(__lowerCAmelCase							) / float(len(__lowerCAmelCase							)							)
				plt.hist(__lowerCAmelCase		,  weights=__lowerCAmelCase		,  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(__lowerCAmelCase		,  f'''na_prob_hist_{name}.png'''							)							)
				plt.clf()




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




def  __magic_name__ (   __lowerCAmelCase	:						Dict		,  __lowerCAmelCase	:						Optional[int]		,  __lowerCAmelCase	:						int		,  __lowerCAmelCase	:						Union[str, Any]		,  __lowerCAmelCase	:						int		,  __lowerCAmelCase	:						Optional[Any]							)			->   int:
				__lowerCamelCase					,    __lowerCamelCase    					=	find_best_thresh(__lowerCAmelCase		,  __lowerCAmelCase		,  __lowerCAmelCase		,  __lowerCAmelCase							)
				__lowerCamelCase					,    __lowerCamelCase    					=	find_best_thresh(__lowerCAmelCase		,  __lowerCAmelCase		,  __lowerCAmelCase		,  __lowerCAmelCase							)
				__lowerCamelCase    					=	best_exact
				__lowerCamelCase    					=	exact_thresh
				__lowerCamelCase    					=	best_fa
				__lowerCamelCase    					=	fa_thresh




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


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

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



