



"""simple docstring"""






import csv
from collections import defaultdict
from dataclasses import dataclass, field
from typing import List, Optional

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.ticker import ScalarFormatter

from transformers import HfArgumentParser






def 	snake_case__  (						__lowerCamelCase							:       Optional[int]=None				,						__lowerCamelCase							:       Union[str, Any]=None      ):
			"""simple docstring"""
			return field(default_factory=lambda: default				,						metadata=__lowerCamelCase      )

@dataclass
class 			__SCREAMING_SNAKE_CASE      :


					'''simple docstring'''





					_a       =				field(
					    metadata={'help': 'The csv file to plot.'}						,  )
					_a       =				field(
					    default=lowerCAmelCase_						,  metadata={'help': 'Whether to plot along batch size or sequence length. Defaults to sequence length.'}						,  )
					_a       =				field(
					    default=lowerCAmelCase_						,  metadata={'help': 'Whether the csv file has time results or memory results. Defaults to memory results.'}						,  )
					_a       =				field(
					    default=lowerCAmelCase_						,  metadata={'help': 'Disable logarithmic scale when plotting'}						,  )
					_a       =				field(
					    default=lowerCAmelCase_						,  metadata={
					        'help': 'Whether the csv file has training results or inference results. Defaults to inference results.'
					    }						,  )
					_a       =				field(
					    default=lowerCAmelCase_						,  metadata={'help': 'Filename under which the plot will be saved. If unused no plot is saved.'}						,  )
					_a       =				list_field(
					    default=lowerCAmelCase_						,  metadata={'help': 'List of model names that are used instead of the ones in the csv file.'}  )






def 	snake_case__  (						__lowerCamelCase							:       Any      ):
			"""simple docstring"""
			try:
						int(__lowerCamelCase      )
						return True
			except ValueError:
						return False






def 	snake_case__  (						__lowerCamelCase							:       List[str]      ):
			"""simple docstring"""
			try:
						float(__lowerCamelCase      )
						return True
			except ValueError:
						return False

class 			__SCREAMING_SNAKE_CASE      :


					'''simple docstring'''





					def __init__(			self				:    Optional[Any],    lowerCamelCase				:    List[Any]	)->   Union[str, Any]:
								lowerCamelCase__						:						List[str]						      =args
								lowerCamelCase__						:						str						      =defaultdict(lambda: {"bsz": [], "seq_len": [], "result": {}}	)

								with open(self.args.csv_file,    newline=''''''	) as csv_file:
											lowerCamelCase__						:						Dict						      =csv.DictReader(lowerCamelCase	)
											for row in reader:
														lowerCamelCase__						:						Tuple						      =row['''model''']
														self.result_dict[model_name]["bsz"].append(int(row['''batch_size''']	)	)
														self.result_dict[model_name]["seq_len"].append(int(row['''sequence_length''']	)	)
														if can_convert_to_int(row['''result''']	):
																	# value is not None
																	lowerCamelCase__						:						Union[str, Any]						      =int(row['''result''']	)
														elif can_convert_to_float(row['''result''']	):
																	# value is not None
																	lowerCamelCase__						:						Tuple						      =float(row['''result''']	)




					def 						snake_case			(			self				:    Optional[int]	)->   Union[str, Any]:
								lowerCamelCase__      ,  lowerCamelCase__						:						Any						      =plt.subplots()
								lowerCamelCase__						:						Any						      ='''Time usage''' if self.args.is_time else '''Memory usage'''
								lowerCamelCase__						:						Tuple						      =title_str + ''' for training''' if self.args.is_train else title_str + ''' for inference'''

								if not self.args.no_log_scale:
											# set logarithm scales
											ax.set_xscale('''log'''	)
											ax.set_yscale('''log'''	)

								for axis in [ax.xaxis, ax.yaxis]:
											axis.set_major_formatter(ScalarFormatter()	)

								for model_name_idx, model_name in enumerate(self.result_dict.keys()	):
											lowerCamelCase__						:						Optional[Any]						      =sorted(set(self.result_dict[model_name]['''bsz''']	)	)
											lowerCamelCase__						:						List[str]						      =sorted(set(self.result_dict[model_name]['''seq_len''']	)	)
											lowerCamelCase__						:						List[str]						      =self.result_dict[model_name]['''result''']

											((lowerCamelCase__)      ,  (lowerCamelCase__))						:						str						      =(
											    (batch_sizes, sequence_lengths) if self.args.plot_along_batch else (sequence_lengths, batch_sizes)
											)

											lowerCamelCase__						:						Optional[int]						      =(
											    model_name if self.args.short_model_names is None else self.args.short_model_names[model_name_idx]
											)

											for inner_loop_value in inner_loop_array:
														if self.args.plot_along_batch:
																	lowerCamelCase__						:						List[str]						      =np.asarray(
																	    [results[(x, inner_loop_value)] for x in x_axis_array if (x, inner_loop_value) in results],    dtype=lowerCamelCase,    )
														else:
																	lowerCamelCase__						:						int						      =np.asarray(
																	    [results[(inner_loop_value, x)] for x in x_axis_array if (inner_loop_value, x) in results],    dtype=np.floataa,    )

														((lowerCamelCase__)      ,  (lowerCamelCase__))						:						Optional[Any]						      =(
														    ('''batch_size''', '''len''') if self.args.plot_along_batch else ('''in #tokens''', '''bsz''')
														)

														lowerCamelCase__						:						Any						      =np.asarray(lowerCamelCase,    lowerCamelCase	)[: len(lowerCamelCase	)]
														plt.scatter(
														    lowerCamelCase,    lowerCamelCase,    label=F'''{label_model_name} - {inner_loop_label}: {inner_loop_value}'''	)
														plt.plot(lowerCamelCase,    lowerCamelCase,    '''--'''	)

											title_str += F''' {label_model_name} vs.'''

								lowerCamelCase__						:						Dict						      =title_str[:-4]
								lowerCamelCase__						:						List[Any]						      ='''Time in s''' if self.args.is_time else '''Memory in MB'''

								# plot
								plt.title(lowerCamelCase	)
								plt.xlabel(lowerCamelCase	)
								plt.ylabel(lowerCamelCase	)
								plt.legend()

								if self.args.figure_png_file is not None:
											plt.savefig(self.args.figure_png_file	)
								else:
											plt.show()






def 	snake_case__  (						):
			"""simple docstring"""
			lowerCamelCase__						:						int						      =HfArgumentParser(__lowerCamelCase      )
			lowerCamelCase__						:						int						      =parser.parse_args_into_dataclasses()[0]
			lowerCamelCase__						:						Optional[int]						      =Plot(args=__lowerCamelCase      )
			plot.plot()


if __name__ == "__main__":
		main()












"""simple docstring"""
import torch.nn as nn

from .imports import is_fpa_available


if is_fpa_available():
      import transformer_engine.pytorch as te






def 			lowerCamelCase_    (		_lowerCamelCase     ,  _lowerCamelCase=True     ,  _lowerCamelCase=True     ,  _lowerCamelCase=True							):
 if not is_fpa_available():
  raise ImportError('Using `convert_model` requires transformer_engine to be installed.'							)
 for name, module in model.named_children():
  if isinstance(_lowerCamelCase     ,  nn.Linear							) and to_transformer_engine and _convert_linear:
   # Return early if the linear layer weights are not multiples of 16
   if any(p % 16 != 0 for p in module.weight.shape							):
    return
   lowerCamelCase__	:     List[Any]								=		module.bias is not None
   lowerCamelCase__	:     Tuple								=		te.Linear(
       module.in_features     ,  module.out_features     ,  bias=_lowerCamelCase     ,  params_dtype=module.weight.dtype							)
   lowerCamelCase__	:     Optional[Any]								=		module.weight.data.clone()
   if has_bias:
    lowerCamelCase__	:     List[str]								=		module.bias.data.clone()

   setattr(_lowerCamelCase     ,  _lowerCamelCase     ,  _lowerCamelCase							)
  elif isinstance(_lowerCamelCase     ,  nn.LayerNorm							) and to_transformer_engine and _convert_ln:
   lowerCamelCase__	:     Tuple								=		te.LayerNorm(module.normalized_shape[0]     ,  eps=module.eps     ,  params_dtype=module.weight.dtype							)
   lowerCamelCase__	:     Tuple								=		module.weight.data.clone()
   lowerCamelCase__	:     Optional[Any]								=		module.bias.data.clone()

   setattr(_lowerCamelCase     ,  _lowerCamelCase     ,  _lowerCamelCase							)
  elif isinstance(_lowerCamelCase     ,  te.Linear							) and not to_transformer_engine and _convert_linear:
   lowerCamelCase__	:     Optional[Any]								=		module.bias is not None
   lowerCamelCase__	:     Union[str, Any]								=		nn.Linear(
       module.in_features     ,  module.out_features     ,  bias=_lowerCamelCase     ,  params_dtype=module.weight.dtype							)
   lowerCamelCase__	:     str								=		module.weight.data.clone()
   if has_bias:
    lowerCamelCase__	:     Optional[int]								=		module.bias.data.clone()

   setattr(_lowerCamelCase     ,  _lowerCamelCase     ,  _lowerCamelCase							)
  elif isinstance(_lowerCamelCase     ,  te.LayerNorm							) and not to_transformer_engine and _convert_ln:
   lowerCamelCase__	:     str								=		nn.LayerNorm(module.normalized_shape[0]     ,  eps=module.eps     ,  params_dtype=module.weight.dtype							)
   lowerCamelCase__	:     Dict								=		module.weight.data.clone()
   lowerCamelCase__	:     Dict								=		module.bias.data.clone()

   setattr(_lowerCamelCase     ,  _lowerCamelCase     ,  _lowerCamelCase							)
  else:
   convert_model(
       _lowerCamelCase     ,  to_transformer_engine=_lowerCamelCase     ,  _convert_linear=_convert_linear     ,  _convert_ln=_convert_ln     ,  )






def 			lowerCamelCase_    (		_lowerCamelCase							):
 if not is_fpa_available():
  raise ImportError('Using `has_transformer_engine_layers` requires transformer_engine to be installed.'							)
 for m in model.modules():
  if isinstance(_lowerCamelCase     ,  (te.LayerNorm, te.Linear)							):
   return True
 return False

