"""simple docstring"""






import collections

from .utils import ExplicitEnum, is_torch_available, logging


if is_torch_available():
						import torch


lowerCAmelCase__  :  Optional[Any]											=     logging.get_logger(__name__)
class     snake_case	:




					"""simple docstring"""

					def __init__(    self       :     Optional[Any]   ,lowerCamelCase__       :     Dict   ,lowerCamelCase__       :     Optional[Any]=21   ,lowerCamelCase__       :     str=[]   ,lowerCamelCase__       :     Any=None      ):
									UpperCAmelCase__					=							model
									UpperCAmelCase__					=							trace_batch_nums
									UpperCAmelCase__					=							abort_after_batch_num

									# keep a LIFO buffer of frames to dump as soon as inf/nan is encountered to give context to the problem emergence
									UpperCAmelCase__					=							collections.deque([]   ,lowerCamelCase__      )
									UpperCAmelCase__					=							[]
									UpperCAmelCase__					=							0
									UpperCAmelCase__					=							0
									UpperCAmelCase__					=							False
									UpperCAmelCase__					=							'                 '

									self.analyse_model()

									self.register_forward_hook()







					def 		__lowerCAmelCase						(    self       :     Union[str, Any]   ,lowerCamelCase__       :     Tuple=None      ):
									if frame is not None:
													self.expand_frame(lowerCamelCase__      )
									self.frames.append('\n'.join(self.frame      )      )
									UpperCAmelCase__					=							[]  # start a new frame







					def 		__lowerCAmelCase						(    self       :     int   ,lowerCamelCase__       :     int      ):
									self.frame.append(lowerCamelCase__      )







					def 		__lowerCAmelCase						(    self       :     List[str]      ):
									print('\n'.join(self.frames      )      )
									UpperCAmelCase__					=							[]







					def 		__lowerCAmelCase						(    self       :     Tuple      ):
									UpperCAmelCase__					=							[]







					def 		__lowerCAmelCase						(    self       :     Dict      ):
									print(f'''\nDetected inf/nan during batch_number={self.batch_number}'''      )
									print(f'''Last {len(self.frames      )} forward frames:'''      )
									print(f'''{"abs min":8} {"abs max":8} metadata'''      )
									print('\n'.join(self.frames      )      )
									print('\n\n'      )
									UpperCAmelCase__					=							[]







					def 		__lowerCAmelCase						(    self       :     Tuple      ):
									# extract the fully qualified module names, to be able to report at run time. e.g.:
									# encoder.block.2.layer.0.SelfAttention.o
									#
									# for shared weights only the first shared module name will be registered
									UpperCAmelCase__					=							{m: name for name, m in self.model.named_modules()}
									# self.longest_module_name = max(len(v) for v in self.module_names.values())







					def 		__lowerCAmelCase						(    self       :     Optional[Any]   ,lowerCamelCase__       :     int   ,lowerCamelCase__       :     List[Any]      ):
									if torch.is_tensor(lowerCamelCase__      ):
													self.expand_frame(get_abs_min_max(lowerCamelCase__   ,lowerCamelCase__      )      )
													if detect_overflow(lowerCamelCase__   ,lowerCamelCase__      ):
																	UpperCAmelCase__					=							True
									elif var is None:
													self.expand_frame(f'''{"None":>17} {ctx}'''      )
									else:
													self.expand_frame(f'''{"not a tensor":>17} {ctx}'''      )







					def 		__lowerCAmelCase						(    self       :     Optional[int]      ):
									self.expand_frame(f'''\n\n{self.prefix} *** Starting batch number={self.batch_number} ***'''      )
									self.expand_frame(f'''{"abs min":8} {"abs max":8} metadata'''      )







					def 		__lowerCAmelCase						(    self       :     Optional[int]      ):
									self.expand_frame(f'''{self.prefix} *** Finished batch number={self.batch_number-1} ***\n\n'''      )







					def 		__lowerCAmelCase						(    self       :     List[str]   ,lowerCamelCase__       :     List[str]   ,lowerCamelCase__       :     List[Any]   ,lowerCamelCase__       :     Optional[Any]      ):
									self.expand_frame(f'''{self.prefix} {self.module_names[module]} {module.__class__.__name__}'''      )

									# params
									for name, p in module.named_parameters(recurse=lowerCamelCase__      ):
													self.analyse_variable(lowerCamelCase__   ,lowerCamelCase__      )

									# inputs
									if isinstance(lowerCamelCase__   ,lowerCamelCase__      ):
													for i, x in enumerate(lowerCamelCase__      ):
																	self.analyse_variable(lowerCamelCase__   ,f'''input[{i}]'''      )
									else:
													self.analyse_variable(lowerCamelCase__   ,'input'      )

									# outputs
									if isinstance(lowerCamelCase__   ,lowerCamelCase__      ):
													for i, x in enumerate(lowerCamelCase__      ):
																	# possibly a tuple of tuples
																	if isinstance(lowerCamelCase__   ,lowerCamelCase__      ):
																					for j, y in enumerate(lowerCamelCase__      ):
																									self.analyse_variable(lowerCamelCase__   ,f'''output[{i}][{j}]'''      )
																	else:
																					self.analyse_variable(lowerCamelCase__   ,f'''output[{i}]'''      )
									else:
													self.analyse_variable(lowerCamelCase__   ,'output'      )

									self.save_frame()







					def 		__lowerCAmelCase						(    self       :     Union[str, Any]      ):
									self.model.apply(self._register_forward_hook      )







					def 		__lowerCAmelCase						(    self       :     List[Any]   ,lowerCamelCase__       :     str      ):
									module.register_forward_hook(self.forward_hook      )







					def 		__lowerCAmelCase						(    self       :     Optional[Any]   ,lowerCamelCase__       :     Any   ,lowerCamelCase__       :     str   ,lowerCamelCase__       :     Union[str, Any]      ):
									# - input is a tuple of packed inputs (could be non-Tensors)
									# - output could be a Tensor or a tuple of Tensors and non-Tensors

									UpperCAmelCase__					=							False

									UpperCAmelCase__					=							True if self.batch_number in self.trace_batch_nums else False
									if trace_mode:
													self.reset_saved_frames()

									if self.total_calls == 0:
													self.batch_start_frame()
									self.total_calls += 1

									# count batch numbers - the very first forward hook of the batch will be called when the
									# batch completes - i.e. it gets called very last - we know this batch has finished
									if module == self.model:
													self.batch_number += 1
													UpperCAmelCase__					=							True

									self.create_frame(lowerCamelCase__   ,lowerCamelCase__   ,lowerCamelCase__      )

									# if last_frame_of_batch:
									#     self.batch_end_frame()

									if trace_mode:
													self.trace_frames()

									if last_frame_of_batch:
													self.batch_start_frame()

									if self.detected_overflow and not trace_mode:
													self.dump_saved_frames()

													# now we can abort, as it's pointless to continue running
													raise ValueError(
													    'DebugUnderflowOverflow: inf/nan detected, aborting as there is no point running further. '
													    'Please scroll up above this traceback to see the activation values prior to this event.'      )

									# abort after certain batch if requested to do so
									if self.abort_after_batch_num is not None and self.batch_number > self.abort_after_batch_num:
													raise ValueError(
													    f'''DebugUnderflowOverflow: aborting after {self.batch_number} batches due to'''
													    f''' `abort_after_batch_num={self.abort_after_batch_num}` arg'''      )






def   a_						( lowerCamelCase ,      lowerCamelCase	):
				UpperCAmelCase__					=							var.abs()
				return f'''{abs_var.min():8.2e} {abs_var.max():8.2e} {ctx}'''



def   a_						( lowerCamelCase ,      lowerCamelCase	):
				UpperCAmelCase__					=							False
				if torch.isnan(lowerCamelCase	).any().item():
								UpperCAmelCase__					=							True
								print(f'''{ctx} has nans'''	)
				if torch.isinf(lowerCamelCase	).any().item():
								UpperCAmelCase__					=							True
								print(f'''{ctx} has infs'''	)

				# if needed to monitor large elements can enable the following
				if 0:  # and detected:
								UpperCAmelCase__					=							var[torch.ge(var.abs() ,      1_0_0	)]
								if naaa.numel() > 0:
												print(f'''{ctx}:  n100={naaa.numel()}'''	)
								UpperCAmelCase__					=							var[torch.ge(var.abs() ,      1_0_0_0	)]
								if naaaa.numel() > 0:
												print(f'''{ctx}: n1000={naaaa.numel()}'''	)
								UpperCAmelCase__					=							var[torch.ge(var.abs() ,      1_0_0_0_0	)]
								if naaaaa.numel() > 0:
												print(f'''{ctx}: n10000={naaaaa.numel()}'''	)

				if 0:
								print(f'''min={var.min():9.2e} max={var.max():9.2e}'''	)

				if 0:
								print(f'''min={var.min():9.2e} max={var.max():9.2e} var={var.var():9.2e} mean={var.mean():9.2e} ({ctx})'''	)

				return detected







class     snake_case	(			__UpperCAmelCase    ):




					"""simple docstring"""

					snake_case__       =			"underflow_overflow"
					snake_case__       =			"tpu_metrics_debug"




"""simple docstring"""






import unittest

from transformers import load_tool

from .test_tools_common import ToolTesterMixin


lowerCAmelCase__  :  List[Any]											=     '\nHugging Face was founded in 2016 by French entrepreneurs Clément Delangue, Julien Chaumond, and Thomas Wolf originally as a company that developed a chatbot app targeted at teenagers.[2] After open-sourcing the model behind the chatbot, the company pivoted to focus on being a platform for machine learning.\n\nIn March 2021, Hugging Face raised $40 million in a Series B funding round.[3]\n\nOn April 28, 2021, the company launched the BigScience Research Workshop in collaboration with several other research groups to release an open large language model.[4] In 2022, the workshop concluded with the announcement of BLOOM, a multilingual large language model with 176 billion parameters.[5]\n'
class     snake_case	(			unittest.TestCase				,   __UpperCAmelCase    ):




					"""simple docstring"""

					def 		__lowerCAmelCase						(    self       :     Tuple      ):
									UpperCAmelCase__					=							load_tool('summarization'      )
									self.tool.setup()
									UpperCAmelCase__					=							load_tool('summarization'   ,remote=lowerCamelCase__      )







					def 		__lowerCAmelCase						(    self       :     Union[str, Any]      ):
									UpperCAmelCase__					=							self.tool(lowerCamelCase__      )
									self.assertEqual(
									    lowerCamelCase__   ,'Hugging Face was founded in 2016 by French entrepreneurs Clément Delangue, Julien Chaumond, and Thomas Wolf. In March 2021, Hugging Face raised $40 million in a Series B funding round. On April 28, 2021, the company launched the BigScience Research Workshop in collaboration with several other research groups to release an open large language model. In 2022, the workshop concluded with the announcement of BLOOM.'   ,)







					def 		__lowerCAmelCase						(    self       :     Tuple      ):
									UpperCAmelCase__					=							self.remote_tool(lowerCamelCase__      )
									self.assertEqual(
									    lowerCamelCase__   ,'Hugging Face was founded in 2016 by French entrepreneurs Clément Delangue, Julien Chaumond, and Thomas Wolf. In March 2021, Hugging Face raised $40 million in a Series B funding round. On April 28, 2021, the company launched the BigScience Research Workshop in collaboration with several other research groups to release an open large language model. In 2022, the workshop concluded with the announcement of BLOOM.'   ,)







					def 		__lowerCAmelCase						(    self       :     List[Any]      ):
									UpperCAmelCase__					=							self.tool(text=lowerCamelCase__      )
									self.assertEqual(
									    lowerCamelCase__   ,'Hugging Face was founded in 2016 by French entrepreneurs Clément Delangue, Julien Chaumond, and Thomas Wolf. In March 2021, Hugging Face raised $40 million in a Series B funding round. On April 28, 2021, the company launched the BigScience Research Workshop in collaboration with several other research groups to release an open large language model. In 2022, the workshop concluded with the announcement of BLOOM.'   ,)







					def 		__lowerCAmelCase						(    self       :     Tuple      ):
									UpperCAmelCase__					=							self.remote_tool(text=lowerCamelCase__      )
									self.assertEqual(
									    lowerCamelCase__   ,'Hugging Face was founded in 2016 by French entrepreneurs Clément Delangue, Julien Chaumond, and Thomas Wolf. In March 2021, Hugging Face raised $40 million in a Series B funding round. On April 28, 2021, the company launched the BigScience Research Workshop in collaboration with several other research groups to release an open large language model. In 2022, the workshop concluded with the announcement of BLOOM.'   ,)



