





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


UpperCAmelCase__						:Tuple          =			float("""nan""")







class 	SCREAMING_SNAKE_CASE	:




       def __init__(					self      : Union[str, Any]	,    A__      : Dict					):


            """simple docstring"""







            __lowerCamelCase						:       Optional[int]				   =				sys.stdout
            __lowerCamelCase						:       Optional[int]				   =				open(A__	,    """a"""					)




       def __getattr__(					self      : Dict	,    A__      : Tuple					):


            """simple docstring"""







            return getattr(self.stdout	,    A__					)




       def 					a_					(					self      : Dict	,    A__      : int					):


            """simple docstring"""







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

def     __lowercase  (_lowercase=80,						_lowercase=False     )   ->     Optional[Any]:


     """simple docstring"""
     __lowerCamelCase						:       Any				   =				[]

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

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

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

     # split up into up to MAX_WIDTH lines with shell multi-line escapes
     __lowerCamelCase						:       str				   =				[]
     __lowerCamelCase						:       Tuple				   =				""""""
     while len(_lowercase     ) > 0:
          current_line += f"{cmd.pop(0     )} "
          if len(_lowercase     ) == 0 or len(_lowercase     ) + len(cmd[0]     ) + 1 > max_width - 1:
               lines.append(_lowercase     )
               __lowerCamelCase						:       Optional[int]				   =				""""""
     return "\\\n".join(_lowercase     )
def     __lowercase  (_lowercase,						_lowercase     )   ->     List[Any]:


     """simple docstring"""
     __lowerCamelCase						:       str				   =				re.sub(R"""[\\\n]+""",						""" """,						args.base_cmd     )

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

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

     return [sys.executable] + shlex.split(args.base_cmd     )
def     __lowercase  (_lowercase,						_lowercase,						_lowercase,						_lowercase,						_lowercase,						_lowercase,						_lowercase     )   ->     Optional[Any]:


     """simple docstring"""
     # Enable to debug everything but the run itself, to do it fast and see the progress.
     # This is useful for debugging the output formatting quickly - we can remove it later once
     # everybody is happy with the output
     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.2222_2222]     )},						)

     __lowerCamelCase						:       Optional[Any]				   =				subprocess.run(_lowercase,						capture_output=_lowercase,						text=_lowercase     )

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

     # save the streams
     __lowerCamelCase						:       Any				   =				variation.replace(""" """,						"""-"""     )
     with open(Path(_lowercase     ) / f"log.{prefix}.stdout.txt",						"""w"""     ) as f:
          f.write(result.stdout     )
     with open(Path(_lowercase     ) / 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:
          __lowerCamelCase						:       Tuple				   =				json.load(_lowercase     )

     # filter out just the keys we want
     return {k: v for k, v in metrics.items() if k in metric_keys}
def     __lowercase  (_lowercase,						_lowercase,						_lowercase,						_lowercase,						_lowercase,						_lowercase,						_lowercase,						_lowercase,						_lowercase,						_lowercase,						)   ->     Optional[Any]:


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


     """simple docstring"""
     __lowerCamelCase						:       List[Any]				   =				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     __lowercase  (_lowercase,						_lowercase,						_lowercase,						_lowercase,						_lowercase     )   ->     Union[str, Any]:


     """simple docstring"""
     __lowerCamelCase						:       Tuple				   =				pd.DataFrame(_lowercase     )
     __lowerCamelCase						:       Dict				   =				"""variation"""
     __lowerCamelCase						:       str				   =				"""diff_%"""

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

     # create diff column if possible
     if not math.isnan(_lowercase     ):
          __lowerCamelCase						:       List[str]				   =				df.apply(
              lambda _lowercase     : 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
     __lowerCamelCase						:       int				   =				[variation_key, target_metric_key, diff_key, *report_metric_keys]
     __lowerCamelCase						:       Dict				   =				df.reindex(_lowercase,						axis="""columns"""     )  # reorder cols

     # capitalize
     __lowerCamelCase						:       Optional[Any]				   =				df.rename(str.capitalize,						axis="""columns"""     )

     # make the cols as narrow as possible
     __lowerCamelCase						:       List[str]				   =				df.rename(lambda _lowercase     : c.replace("""_""",						"""<br>"""     ),						axis="""columns"""     )
     __lowerCamelCase						:       str				   =				df.rename(lambda _lowercase     : c.replace("""_""",						"""\n"""     ),						axis="""columns"""     )

     __lowerCamelCase						:       Tuple				   =				["""""", """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=_lowercase,						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=_lowercase,						floatfmt=""".2f"""     )]

     print("""\n\n""".join(_lowercase     )     )
def     __lowercase  ()   ->     List[Any]:


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

     __lowerCamelCase						:       Union[str, Any]				   =				args.output_dir
     Path(_lowercase     ).mkdir(exist_ok=_lowercase     )
     __lowerCamelCase						:       List[Any]				   =				get_base_command(_lowercase,						_lowercase     )

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

     # split wanted keys
     __lowerCamelCase						:       Union[str, Any]				   =				args.report_metric_keys.split()

     # capture prints into a log file for convenience
     __lowerCamelCase						:       Optional[int]				   =				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}"     )

     __lowerCamelCase						:       Union[str, Any]				   =				Tee(_lowercase     )

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

     __lowerCamelCase						:       Optional[int]				   =				"""variation"""
     __lowerCamelCase						:       Tuple				   =				[]
     for id, variation in enumerate(tqdm(_lowercase,						desc="""Total completion: """,						leave=_lowercase     )     ):
          __lowerCamelCase						:       Any				   =				base_cmd + variation.split()
          results.append(
              process_run(
                  id + 1,						_lowercase,						_lowercase,						_lowercase,						_lowercase,						args.target_metric_key,						_lowercase,						args.repeat_times,						_lowercase,						args.verbose,						)     )

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


if __name__ == "__main__":
   main()











'''simple docstring'''

import argparse
import json

from tqdm import tqdm
def     __lowercase  ()   ->     Tuple:


     """simple docstring"""
     __lowerCamelCase						:       Union[str, Any]				   =				argparse.ArgumentParser()

     # Required parameters
     parser.add_argument(
         """--src_path""",						type=_lowercase,						default="""biencoder-nq-dev.json""",						help="""Path to raw DPR training data""",						)
     parser.add_argument(
         """--evaluation_set""",						type=_lowercase,						help="""where to store parsed evaluation_set file""",						)
     parser.add_argument(
         """--gold_data_path""",						type=_lowercase,						help="""where to store parsed gold_data_path file""",						)
     __lowerCamelCase						:       Tuple				   =				parser.parse_args()

     with open(args.src_path,						"""r"""     ) as src_file, open(args.evaluation_set,						"""w"""     ) as eval_file, open(
         args.gold_data_path,						"""w"""     ) as gold_file:
          __lowerCamelCase						:       int				   =				json.load(_lowercase     )
          for dpr_record in tqdm(_lowercase     ):
               __lowerCamelCase						:       List[Any]				   =				dpr_record["""question"""]
               __lowerCamelCase						:       List[str]				   =				[context["""title"""] for context in dpr_record["""positive_ctxs"""]]
               eval_file.write(question + """\n"""     )
               gold_file.write("""\t""".join(_lowercase     ) + """\n"""     )


if __name__ == "__main__":
   main()



