




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


A_      =    float('''nan''')






class  lowercase:







 '''simple docstring'''





 def __init__(    self:		int,				a_:		Any		):




   '''simple docstring'''



   _snake_case							:		Union[str, Any]								=  sys.stdout
   _snake_case							:		int								=  open(a_,				"""a"""		)


 def __getattr__(    self:		List[str],				a_:		List[Any]		):




   '''simple docstring'''



   return getattr(self.stdout,				a_		)


 def 			UpperCamelCase_       (    self:		Union[str, Any],				a_:		List[Any]		):




   '''simple docstring'''



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







def  UpperCAmelCase__	(snake_case__							: Union[str, Any]=80		,       snake_case__							: Any=False   ):
  """simple docstring"""

  _snake_case							:		Optional[Any]								=  []

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

    # python executable (not always needed if the script is executable)
  _snake_case							:		Union[str, Any]								=  sys.executable if full_python_path else sys.executable.split("""/"""   )[-1]
  cmd.append(snake_case__   )

  # 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							:		str								=  []
  _snake_case							:		Any								=  """"""
  while len(snake_case__   ) > 0:
    current_line += F"{cmd.pop(0   )} "
    if len(snake_case__   ) == 0 or len(snake_case__   ) + len(cmd[0]   ) + 1 > max_width - 1:
      lines.append(snake_case__   )
      _snake_case							:		Optional[Any]								=  """"""
  return "\\\n".join(snake_case__   )




def  UpperCAmelCase__	(snake_case__							: str		,       snake_case__							: List[Any]   ):
  """simple docstring"""

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

  # remove --output_dir if any and set our own
  _snake_case							:		str								=  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							:		Union[str, 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  UpperCAmelCase__	(snake_case__							: Dict		,       snake_case__							: List[Any]		,       snake_case__							: Dict		,       snake_case__							: List[Any]		,       snake_case__							: List[Any]		,       snake_case__							: List[Any]		,       snake_case__							: Optional[Any]   ):
  """simple docstring"""

  if 0:
    import random
    from time import sleep

    sleep(0   )
    return dict(
        {k: random.uniform(0		,       1_00   ) 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							:		Optional[Any]								=  subprocess.run(snake_case__		,       capture_output=snake_case__		,       text=snake_case__   )

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

  # save the streams
  _snake_case							:		int								=  variation.replace(""" """		,       """-"""   )
  with open(Path(snake_case__   ) / F"log.{prefix}.stdout.txt"		,       """w"""   ) as f:
    f.write(result.stdout   )
  with open(Path(snake_case__   ) / 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							:		Optional[int]								=  json.load(snake_case__   )

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




def  UpperCAmelCase__	(snake_case__							: Tuple		,       snake_case__							: List[str]		,       snake_case__							: List[Any]		,       snake_case__							: Optional[Any]		,       snake_case__							: List[str]		,       snake_case__							: str		,       snake_case__							: Optional[int]		,       snake_case__							: List[Any]		,       snake_case__							: str		,       snake_case__							: Optional[int]		,       ):
  """simple docstring"""

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




def  UpperCAmelCase__	():
  """simple docstring"""

  _snake_case							:		str								=  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  UpperCAmelCase__	(snake_case__							: Optional[int]		,       snake_case__							: Union[str, Any]		,       snake_case__							: Optional[Any]		,       snake_case__							: List[str]		,       snake_case__							: Dict   ):
  """simple docstring"""

  _snake_case							:		str								=  pd.DataFrame(snake_case__   )
  _snake_case							:		Dict								=  """variation"""
  _snake_case							:		Any								=  """diff_%"""

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

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

  # capitalize
  _snake_case							:		Dict								=  df.rename(str.capitalize		,       axis="""columns"""   )

  # make the cols as narrow as possible
  _snake_case							:		Optional[int]								=  df.rename(lambda snake_case__   : c.replace("""_"""		,       """<br>"""   )		,       axis="""columns"""   )
  _snake_case							:		int								=  df.rename(lambda snake_case__   : c.replace("""_"""		,       """\n"""   )		,       axis="""columns"""   )

  _snake_case							:		Dict								=  ["""""", """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=snake_case__		,       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=snake_case__		,       floatfmt=""".2f"""   )]

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




def  UpperCAmelCase__	():
  """simple docstring"""

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

  _snake_case							:		List[Any]								=  args.output_dir
  Path(snake_case__   ).mkdir(exist_ok=snake_case__   )
  _snake_case							:		Optional[int]								=  get_base_command(snake_case__		,       snake_case__   )

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

  # split wanted keys
  _snake_case							:		List[Any]								=  args.report_metric_keys.split()

  # capture prints into a log file for convenience
  _snake_case							:		Optional[Any]								=  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							:		Optional[int]								=  Tee(snake_case__   )

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

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

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


if __name__ == "__main__":
     main()








"""simple docstring"""


from collections.abc import Generator
from math import sin


def  UpperCAmelCase__	(snake_case__							: bytes   ):
  """simple docstring"""

  if len(snake_case__   ) != 32:
    raise ValueError("""Input must be of length 32"""   )

  _snake_case							:		Optional[int]								=  B""""""
  for i in [3, 2, 1, 0]:
    little_endian += string_aa[8 * i : 8 * i + 8]
  return little_endian


def  UpperCAmelCase__	(snake_case__							: int   ):
  """simple docstring"""

  if i < 0:
    raise ValueError("""Input must be non-negative"""   )

  _snake_case							:		Optional[Any]								=  format(snake_case__		,       """08x"""   )[-8:]
  _snake_case							:		Optional[Any]								=  B""""""
  for i in [3, 2, 1, 0]:
    little_endian_hex += hex_rep[2 * i : 2 * i + 2].encode("""utf-8"""   )
  return little_endian_hex


def  UpperCAmelCase__	(snake_case__							: bytes   ):
  """simple docstring"""

  _snake_case							:		Union[str, Any]								=  B""""""
  for char in message:
    bit_string += format(snake_case__		,       """08b"""   ).encode("""utf-8"""   )
  _snake_case							:		List[Any]								=  format(len(snake_case__   )		,       """064b"""   ).encode("""utf-8"""   )

  # Pad bit_string to a multiple of 512 chars
  bit_string += b"1"
  while len(snake_case__   ) % 5_12 != 4_48:
    bit_string += b"0"
  bit_string += to_little_endian(start_len[32:]   ) + to_little_endian(start_len[:32]   )

  return bit_string


def  UpperCAmelCase__	(snake_case__							: bytes   ):
  """simple docstring"""

  if len(snake_case__   ) % 5_12 != 0:
    raise ValueError("""Input must have length that's a multiple of 512"""   )

  for pos in range(0		,       len(snake_case__   )		,       5_12   ):
    _snake_case							:		List[str]								=  bit_string[pos : pos + 5_12]
    _snake_case							:		List[str]								=  []
    for i in range(0		,       5_12		,       32   ):
      block_words.append(int(to_little_endian(block[i : i + 32]   )		,       2   )   )
    yield block_words


def  UpperCAmelCase__	(snake_case__							: int   ):
  """simple docstring"""

  if i < 0:
    raise ValueError("""Input must be non-negative"""   )

  _snake_case							:		Optional[int]								=  format(snake_case__		,       """032b"""   )
  _snake_case							:		str								=  """"""
  for c in i_str:
    new_str += "1" if c == "0" else "0"
  return int(snake_case__		,       2   )


def  UpperCAmelCase__	(snake_case__							: int		,       snake_case__							: int   ):
  """simple docstring"""

  return (a + b) % 2**32


def  UpperCAmelCase__	(snake_case__							: int		,       snake_case__							: int   ):
  """simple docstring"""

  if i < 0:
    raise ValueError("""Input must be non-negative"""   )
  if shift < 0:
    raise ValueError("""Shift must be non-negative"""   )
  return ((i << shift) ^ (i >> (32 - shift))) % 2**32


def  UpperCAmelCase__	(snake_case__							: bytes   ):
  """simple docstring"""

  _snake_case							:		Any								=  preprocess(snake_case__   )

  _snake_case							:		Optional[Any]								=  [int(2**32 * abs(sin(i + 1   )   )   ) for i in range(64   )]

  # Starting states
  _snake_case							:		Union[str, Any]								=  0x6745_2301
  _snake_case							:		List[Any]								=  0xEFCD_AB89
  _snake_case							:		Optional[Any]								=  0x98BA_DCFE
  _snake_case							:		Optional[int]								=  0x1032_5476

  _snake_case							:		Tuple								=  [
      7,
      12,
      17,
      22,
      7,
      12,
      17,
      22,
      7,
      12,
      17,
      22,
      7,
      12,
      17,
      22,
      5,
      9,
      14,
      20,
      5,
      9,
      14,
      20,
      5,
      9,
      14,
      20,
      5,
      9,
      14,
      20,
      4,
      11,
      16,
      23,
      4,
      11,
      16,
      23,
      4,
      11,
      16,
      23,
      4,
      11,
      16,
      23,
      6,
      10,
      15,
      21,
      6,
      10,
      15,
      21,
      6,
      10,
      15,
      21,
      6,
      10,
      15,
      21,
  ]

  # Process bit string in chunks, each with 16 32-char words
  for block_words in get_block_words(snake_case__   ):
    _snake_case							:		Tuple								=  aa
    _snake_case							:		str								=  ba
    _snake_case							:		int								=  ca
    _snake_case							:		Dict								=  da

    # Hash current chunk
    for i in range(64   ):
      if i <= 15:
        # f = (b & c) | (not_32(b) & d)     # Alternate definition for f
        _snake_case							:		int								=  d ^ (b & (c ^ d))
        _snake_case							:		Dict								=  i
      elif i <= 31:
        # f = (d & b) | (not_32(d) & c)     # Alternate definition for f
        _snake_case							:		Tuple								=  c ^ (d & (b ^ c))
        _snake_case							:		int								=  (5 * i + 1) % 16
      elif i <= 47:
        _snake_case							:		List[Any]								=  b ^ c ^ d
        _snake_case							:		Union[str, Any]								=  (3 * i + 5) % 16
      else:
        _snake_case							:		Tuple								=  c ^ (b | not_aa(snake_case__   ))
        _snake_case							:		Optional[int]								=  (7 * i) % 16
      _snake_case							:		Dict								=  (f + a + added_consts[i] + block_words[g]) % 2**32
      _snake_case							:		List[str]								=  d
      _snake_case							:		List[Any]								=  c
      _snake_case							:		str								=  b
      _snake_case							:		List[str]								=  sum_aa(snake_case__		,       left_rotate_aa(snake_case__		,       shift_amounts[i]   )   )

    # Add hashed chunk to running total
    _snake_case							:		Union[str, Any]								=  sum_aa(snake_case__		,       snake_case__   )
    _snake_case							:		str								=  sum_aa(snake_case__		,       snake_case__   )
    _snake_case							:		Any								=  sum_aa(snake_case__		,       snake_case__   )
    _snake_case							:		List[str]								=  sum_aa(snake_case__		,       snake_case__   )

  _snake_case							:		Any								=  reformat_hex(snake_case__   ) + reformat_hex(snake_case__   ) + reformat_hex(snake_case__   ) + reformat_hex(snake_case__   )
  return digest


if __name__ == "__main__":
     import doctest

     doctest.testmod()


