


'''simple docstring'''
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


__snake_case							   =  float('''nan''')
class      lowercase			:

		"""simple docstring"""

		def __init__(	self					,     UpperCamelCase_							):

							'''simple docstring'''


							UpperCamelCase__     :Dict							      =				sys.stdout
							UpperCamelCase__     :str							      =				open(UpperCamelCase_					,     '''a'''							)




		def __getattr__(	self					,     UpperCamelCase_							):

							'''simple docstring'''


							return getattr(self.stdout					,     UpperCamelCase_							)




		def 					lowerCAmelCase__       (	self					,     UpperCamelCase_							):

							'''simple docstring'''


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



def     a   (    __a=80				,      __a=False     )						->			Optional[int]:



					'''simple docstring'''






					UpperCamelCase__     :List[Any]							      =				[]

					# deal with critical env vars
					UpperCamelCase__     :Optional[Any]							      =				['''CUDA_VISIBLE_DEVICES''']
					for key in env_keys:
										UpperCamelCase__     :Tuple							      =				os.environ.get(__a				,      __a     )
										if val is not None:
															cmd.append(f'''{key}={val}'''     )

    # python executable (not always needed if the script is executable)
					UpperCamelCase__     :List[str]							      =				sys.executable if full_python_path else sys.executable.split('''/'''     )[-1]
					cmd.append(__a     )

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

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


def     a   (    __a				,      __a     )						->			Optional[Any]:



					'''simple docstring'''






					UpperCamelCase__     :Optional[Any]							      =				re.sub(R'''[\\\n]+'''				,      ''' '''				,      args.base_cmd     )

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

					# ensure we have --overwrite_output_dir
					UpperCamelCase__     :Optional[Any]							      =				re.sub('''--overwrite_output_dir\s+'''				,      ''''''				,      args.base_cmd     )
					args.base_cmd += " --overwrite_output_dir"

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


def     a   (    __a				,      __a				,      __a				,      __a				,      __a				,      __a				,      __a     )						->			Tuple:



					'''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, 100.2, 55.6666, 222.22222222]     )}				,      )

					UpperCamelCase__     :str							      =				subprocess.run(__a				,      capture_output=__a				,      text=__a     )

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

					# save the streams
					UpperCamelCase__     :Union[str, Any]							      =				variation.replace(''' '''				,      '''-'''     )
					with open(Path(__a     ) / f'''log.{prefix}.stdout.txt'''				,      '''w'''     ) as f:
										f.write(result.stdout     )
					with open(Path(__a     ) / 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:
										UpperCamelCase__     :List[str]							      =				json.load(__a     )

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


def     a   (    __a				,      __a				,      __a				,      __a				,      __a				,      __a				,      __a				,      __a				,      __a				,      __a				,      )						->			Dict:



					'''simple docstring'''






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


def     a   (    )						->			Union[str, Any]:



					'''simple docstring'''






					UpperCamelCase__     :Any							      =				torch.cuda.get_device_properties(torch.device('''cuda'''     )     )
					return f'''
Datetime    : {datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"     )}

Software:
transformers: {transformers.__version__}
torch       : {torch.__version__}
cuda        : {torch.version.cuda}
python      : {platform.python_version()}

Hardware:
{torch.cuda.device_count()} GPUs      : {properties.name}, {properties.total_memory/2**30:0.2f}GB
'''


def     a   (    __a				,      __a				,      __a				,      __a				,      __a     )						->			Any:



					'''simple docstring'''






					UpperCamelCase__     :List[Any]							      =				pd.DataFrame(__a     )
					UpperCamelCase__     :int							      =				'''variation'''
					UpperCamelCase__     :Optional[Any]							      =				'''diff_%'''

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

					# create diff column if possible
					if not math.isnan(__a     ):
										UpperCamelCase__     :Optional[int]							      =				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
					UpperCamelCase__     :Union[str, Any]							      =				[variation_key, target_metric_key, diff_key, *report_metric_keys]
					UpperCamelCase__     :Dict							      =				df.reindex(__a				,      axis='''columns'''     )  # reorder cols

					# capitalize
					UpperCamelCase__     :Optional[int]							      =				df.rename(str.capitalize				,      axis='''columns'''     )

					# make the cols as narrow as possible
					UpperCamelCase__     :List[Any]							      =				df.rename(lambda __a     : c.replace('''_'''				,      '''<br>'''     )				,      axis='''columns'''     )
					UpperCamelCase__     :Optional[Any]							      =				df.rename(lambda __a     : c.replace('''_'''				,      '''\n'''     )				,      axis='''columns'''     )

					UpperCamelCase__     :Any							      =				['''''', '''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=__a				,      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=__a				,      floatfmt='''.2f'''     )]

					print('''\n\n'''.join(__a     )     )


def     a   (    )						->			Dict:



					'''simple docstring'''






					UpperCamelCase__     :Optional[int]							      =				argparse.ArgumentParser()
					parser.add_argument(
					    '''--base-cmd'''				,      default=__a				,      type=__a				,      required=__a				,      help='''Base cmd'''				,      )
					parser.add_argument(
					    '''--variations'''				,      default=__a				,      type=__a				,      nargs='''+'''				,      required=__a				,      help='''Multi-dimensional variations, example: \'|--fp16|--bf16\' \'|--tf32\''''				,      )
					parser.add_argument(
					    '''--base-variation'''				,      default=__a				,      type=__a				,      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=__a				,      type=__a				,      required=__a				,      help='''Target metric key in output_dir/all_results.json, e.g., train_samples_per_second'''				,      )
					parser.add_argument(
					    '''--report-metric-keys'''				,      default=''''''				,      type=__a				,      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=__a				,      help='''How many times to re-run each variation - an average will be reported'''				,      )
					parser.add_argument(
					    '''--output_dir'''				,      default='''output_benchmark'''				,      type=__a				,      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=__a				,      action='''store_true'''				,      help='''Whether to show the outputs of each run or just the benchmark progress'''				,      )
					UpperCamelCase__     :Dict							      =				parser.parse_args()

					UpperCamelCase__     :Union[str, Any]							      =				args.output_dir
					Path(__a     ).mkdir(exist_ok=__a     )
					UpperCamelCase__     :Union[str, Any]							      =				get_base_command(__a				,      __a     )

					# split each dimension into its --foo variations
					UpperCamelCase__     :Optional[int]							      =				[list(map(str.strip				,      re.split(R'''\|'''				,      __a     )     )     ) 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
					UpperCamelCase__     :Union[str, Any]							      =				list(map(str.strip				,      map(''' '''.join				,      itertools.product(*__a     )     )     )     )
					UpperCamelCase__     :List[Any]							      =				max(len(__a     ) for x in variations     )

					# split wanted keys
					UpperCamelCase__     :Dict							      =				args.report_metric_keys.split()

					# capture prints into a log file for convenience
					UpperCamelCase__     :Tuple							      =				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}'''     )

					UpperCamelCase__     :Any							      =				Tee(__a     )

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

					UpperCamelCase__     :List[str]							      =				'''variation'''
					UpperCamelCase__     :Tuple							      =				[]
					for id, variation in enumerate(tqdm(__a				,      desc='''Total completion: '''				,      leave=__a     )     ):
										UpperCamelCase__     :Any							      =				base_cmd + variation.split()
										results.append(
										    process_run(
										        id + 1				,      __a				,      __a				,      __a				,      __a				,      args.target_metric_key				,      __a				,      args.repeat_times				,      __a				,      args.verbose				,      )     )

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


if __name__ == "__main__":
		main()



'''simple docstring'''
import qiskit


def     a   (    __a				,      __a     )						->			qiskit.result.counts.Counts:



					'''simple docstring'''






					UpperCamelCase__     :int							      =				qiskit.Aer.get_backend('''aer_simulator'''     )

					# Create a Quantum Circuit acting on the q register
					UpperCamelCase__     :Any							      =				qiskit.QuantumCircuit(__a				,      __a     )

					# Map the quantum measurement to the classical bits
					circuit.measure([0]				,      [0]     )

					# Execute the circuit on the simulator
					UpperCamelCase__     :Optional[int]							      =				qiskit.execute(__a				,      __a				,      shots=1000     )

					# Return the histogram data of the results of the experiment.
					return job.result().get_counts(__a     )


if __name__ == "__main__":
		print(F"""Total count for various states are: {single_qubit_measure(1, 1)}""")