
"""simple docstring"""





# 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


UpperCamelCase_					:						Tuple				= float('''nan''')



class __lowerCAmelCase				:




			"""simple docstring"""







			def __init__(				self						:					Dict       ,   _snake_case						:					Dict	)      -> Union[str, Any]:







								"""simple docstring"""
								A_				 =						sys.stdout
								A_				 =						open(_snake_case       ,   "a"	)




			def __getattr__(				self						:					int       ,   _snake_case						:					Optional[int]	)      -> Optional[Any]:







								"""simple docstring"""
								return getattr(self.stdout       ,   _snake_case	)






			def      lowerCamelCase__     (				self						:					Tuple       ,   _snake_case						:					Optional[Any]	)      -> Optional[Any]:







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





def 							A_     (__a=80				,   __a=False				):

					'''simple docstring'''





					A_				 =						[]

					# deal with critical env vars
					A_				 =						["CUDA_VISIBLE_DEVICES"]
					for key in env_keys:
										A_				 =						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)
					A_				 =						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
					A_				 =						[]
					A_				 =						""
					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				)
															A_				 =						""
					return "\\\n".join(__a				)
def 							A_     (__a				,   __a				):

					'''simple docstring'''





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

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

					# ensure we have --overwrite_output_dir
					A_				 =						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				):

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

					A_				 =						subprocess.run(__a				,   capture_output=__a				,   text=__a				)

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

					# save the streams
					A_				 =						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:
										A_				 =						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				,   ):

					'''simple docstring'''





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

					'''simple docstring'''





					A_				 =						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 							A_     (__a				,   __a				,   __a				,   __a				,   __a				):

					'''simple docstring'''





					A_				 =						pd.DataFrame(__a				)
					A_				 =						"variation"
					A_				 =						"diff_%"

					A_				 =						nan
					if base_variation is not None and len(df[df[variation_key] == base_variation]				):
										# this may still return nan
										A_				 =						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
										A_				 =						df.loc[df[target_metric_key] != nan][target_metric_key].min()

					# create diff column if possible
					if not math.isnan(__a				):
										A_				 =						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
					A_				 =						[variation_key, target_metric_key, diff_key, *report_metric_keys]
					A_				 =						df.reindex(__a				,   axis="columns"				)  # reorder cols

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

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

					A_				 =						["", "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_     ():

					'''simple docstring'''





					A_				 =						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"				,   )
					A_				 =						parser.parse_args()

					A_				 =						args.output_dir
					Path(__a				).mkdir(exist_ok=__a				)
					A_				 =						get_base_command(__a				,   __a				)

					# split each dimension into its --foo variations
					A_				 =						[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
					A_				 =						list(map(str.strip				,   map(" ".join				,   itertools.product(*__a				)				)				)				)
					A_				 =						max(len(__a				) for x in variations				)

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

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

					A_				 =						Tee(__a				)

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

					A_				 =						"variation"
					A_				 =						[]
					for id, variation in enumerate(tqdm(__a				,   desc="Total completion: "				,   leave=__a				)				):
										A_				 =						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"""





from collections import deque



class __lowerCAmelCase				:




			"""simple docstring"""







			def __init__(				self						:					Optional[Any]       ,   _snake_case						:					str       ,   _snake_case						:					int       ,   _snake_case						:					int	)      -> None:







								"""simple docstring"""
								A_				 =						process_name  # process name
								A_				 =						arrival_time  # arrival time of the process
								# completion time of finished process or last interrupted time
								A_				 =						arrival_time
								A_				 =						burst_time  # remaining burst time
								A_				 =						0  # total time of the process wait in ready queue
								A_				 =						0  # time from arrival time to completion time





class __lowerCAmelCase				:




			"""simple docstring"""







			def __init__(				self						:					str       ,   _snake_case						:					int       ,   _snake_case						:					list[int]       ,   _snake_case						:					deque[Process]       ,   _snake_case						:					int       ,   )      -> None:







								"""simple docstring"""
								# total number of mlfq's queues
								A_				 =						number_of_queues
								# time slice of queues that round robin algorithm applied
								A_				 =						time_slices
								# unfinished process is in this ready_queue
								A_				 =						queue
								# current time
								A_				 =						current_time
								# finished process is in this sequence queue
								A_				 =						deque()




			def      lowerCamelCase__     (				self						:					List[str]	)      -> list[str]:







								"""simple docstring"""
								A_				 =						[]
								for i in range(len(self.finish_queue	)	):
													sequence.append(self.finish_queue[i].process_name	)
								return sequence




			def      lowerCamelCase__     (				self						:					str       ,   _snake_case						:					list[Process]	)      -> list[int]:







								"""simple docstring"""
								A_				 =						[]
								for i in range(len(_snake_case	)	):
													waiting_times.append(queue[i].waiting_time	)
								return waiting_times




			def      lowerCamelCase__     (				self						:					Tuple       ,   _snake_case						:					list[Process]	)      -> list[int]:







								"""simple docstring"""
								A_				 =						[]
								for i in range(len(_snake_case	)	):
													turnaround_times.append(queue[i].turnaround_time	)
								return turnaround_times




			def      lowerCamelCase__     (				self						:					Tuple       ,   _snake_case						:					list[Process]	)      -> list[int]:







								"""simple docstring"""
								A_				 =						[]
								for i in range(len(_snake_case	)	):
													completion_times.append(queue[i].stop_time	)
								return completion_times




			def      lowerCamelCase__     (				self						:					Optional[int]       ,   _snake_case						:					deque[Process]	)      -> list[int]:







								"""simple docstring"""
								return [q.burst_time for q in queue]




			def      lowerCamelCase__     (				self						:					int       ,   _snake_case						:					Process	)      -> int:







								"""simple docstring"""
								process.waiting_time += self.current_time - process.stop_time
								return process.waiting_time




			def      lowerCamelCase__     (				self						:					Dict       ,   _snake_case						:					deque[Process]	)      -> deque[Process]:







								"""simple docstring"""
								A_				 =						deque()  # sequence deque of finished process
								while len(_snake_case	) != 0:
													A_				 =						ready_queue.popleft()  # current process

													# if process's arrival time is later than current time, update current time
													if self.current_time < cp.arrival_time:
																		self.current_time += cp.arrival_time

													# update waiting time of current process
													self.update_waiting_time(_snake_case	)
													# update current time
													self.current_time += cp.burst_time
													# finish the process and set the process's burst-time 0
													A_				 =						0
													# set the process's turnaround time because it is finished
													A_				 =						self.current_time - cp.arrival_time
													# set the completion time
													A_				 =						self.current_time
													# add the process to queue that has finished queue
													finished.append(_snake_case	)

								self.finish_queue.extend(_snake_case	)  # add finished process to finish queue
								# FCFS will finish all remaining processes
								return finished




			def      lowerCamelCase__     (				self						:					List[str]       ,   _snake_case						:					deque[Process]       ,   _snake_case						:					int	)      -> tuple[deque[Process], deque[Process]]:







								"""simple docstring"""
								A_				 =						deque()  # sequence deque of terminated process
								# just for 1 cycle and unfinished processes will go back to queue
								for _ in range(len(_snake_case	)	):
													A_				 =						ready_queue.popleft()  # current process

													# if process's arrival time is later than current time, update current time
													if self.current_time < cp.arrival_time:
																		self.current_time += cp.arrival_time

													# update waiting time of unfinished processes
													self.update_waiting_time(_snake_case	)
													# if the burst time of process is bigger than time-slice
													if cp.burst_time > time_slice:
																		# use CPU for only time-slice
																		self.current_time += time_slice
																		# update remaining burst time
																		cp.burst_time -= time_slice
																		# update end point time
																		A_				 =						self.current_time
																		# locate the process behind the queue because it is not finished
																		ready_queue.append(_snake_case	)
													else:
																		# use CPU for remaining burst time
																		self.current_time += cp.burst_time
																		# set burst time 0 because the process is finished
																		A_				 =						0
																		# set the finish time
																		A_				 =						self.current_time
																		# update the process' turnaround time because it is finished
																		A_				 =						self.current_time - cp.arrival_time
																		# add the process to queue that has finished queue
																		finished.append(_snake_case	)

								self.finish_queue.extend(_snake_case	)  # add finished process to finish queue
								# return finished processes queue and remaining processes queue
								return finished, ready_queue






			def      lowerCamelCase__     (				self						:					Any	)      -> deque[Process]:







								"""simple docstring"""

								#  all queues except last one have round_robin algorithm
								for i in range(self.number_of_queues - 1	):
													A_ ,    A_				 =						self.round_robin(
													    self.ready_queue       ,   self.time_slices[i]	)
								#  the last queue has first_come_first_served algorithm
								self.first_come_first_served(self.ready_queue	)

								return self.finish_queue


if __name__ == "__main__":
		import doctest

		UpperCamelCase_					:						Tuple				= Process('''P1''', 0, 53)
		UpperCamelCase_					:						List[Any]				= Process('''P2''', 0, 17)
		UpperCamelCase_					:						Optional[int]				= Process('''P3''', 0, 68)
		UpperCamelCase_					:						Union[str, Any]				= Process('''P4''', 0, 24)
		UpperCamelCase_					:						Any				= 3
		UpperCamelCase_					:						List[str]				= [17, 25]
		UpperCamelCase_					:						List[str]				= deque([Pa, Pa, Pa, Pa])

		if len(time_slices) != number_of_queues - 1:
				raise SystemExit(0)

		doctest.testmod(extraglobs={'''queue''': deque([Pa, Pa, Pa, Pa])})

		UpperCamelCase_					:						str				= Process('''P1''', 0, 53)
		UpperCamelCase_					:						Dict				= Process('''P2''', 0, 17)
		UpperCamelCase_					:						List[Any]				= Process('''P3''', 0, 68)
		UpperCamelCase_					:						int				= Process('''P4''', 0, 24)
		UpperCamelCase_					:						Dict				= 3
		UpperCamelCase_					:						str				= [17, 25]
		UpperCamelCase_					:						Optional[int]				= deque([Pa, Pa, Pa, Pa])
		UpperCamelCase_					:						str				= MLFQ(number_of_queues, time_slices, queue, 0)
		UpperCamelCase_					:						int				= mlfq.multi_level_feedback_queue()

		# print total waiting times of processes(P1, P2, P3, P4)
		print(
		    F"""waiting time:\
        \t\t\t{MLFQ.calculate_waiting_time(mlfq, [Pa, Pa, Pa, Pa])}"""
		)
		# print completion times of processes(P1, P2, P3, P4)
		print(
		    F"""completion time:\
        \t\t{MLFQ.calculate_completion_time(mlfq, [Pa, Pa, Pa, Pa])}"""
		)
		# print total turnaround times of processes(P1, P2, P3, P4)
		print(
		    F"""turnaround time:\
        \t\t{MLFQ.calculate_turnaround_time(mlfq, [Pa, Pa, Pa, Pa])}"""
		)
		# print sequence of finished processes
		print(
		    F"""sequence of finished processes:\
        {mlfq.calculate_sequence_of_finish_queue()}"""
		)




