





import collections

from .utils import ExplicitEnum, is_torch_available, logging


if is_torch_available():
				import torch


__A       :					Optional[int]     					=     logging.get_logger(__name__)

class 			A_ :
			def __init__(					self							,      _A							,      _A=2_1							,      _A=[]							,      _A=None	):






						'''simple docstring'''







						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   _lowercase       (					self							,      _A=None	):






						'''simple docstring'''







						if frame is not None:
									self.expand_frame(lowerCamelCase__	)
						self.frames.append('''\n'''.join(self.frame	)	)
						UpperCAmelCase     	=       []  # start a new frame
			def   _lowercase       (					self							,      _A	):






						'''simple docstring'''







						self.frame.append(lowerCamelCase__	)
			def   _lowercase       (					self	):






						'''simple docstring'''







						print('''\n'''.join(self.frames	)	)
						UpperCAmelCase     	=       []
			def   _lowercase       (					self	):






						'''simple docstring'''







						UpperCAmelCase     	=       []
			def   _lowercase       (					self	):






						'''simple docstring'''







						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   _lowercase       (					self	):






						'''simple docstring'''







						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   _lowercase       (					self							,      _A							,      _A	):






						'''simple docstring'''







						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   _lowercase       (					self	):






						'''simple docstring'''







						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   _lowercase       (					self	):






						'''simple docstring'''







						self.expand_frame(F"""{self.prefix} *** Finished batch number={self.batch_number-1} ***\n\n"""	)
			def   _lowercase       (					self							,      _A							,      _A							,      _A	):






						'''simple docstring'''







						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   _lowercase       (					self	):






						'''simple docstring'''







						self.model.apply(self._register_forward_hook	)
			def   _lowercase       (					self							,      _A	):






						'''simple docstring'''







						module.register_forward_hook(self.forward_hook	)







			def   _lowercase       (					self							,      _A							,      _A							,      _A	):






						'''simple docstring'''







						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 		__SCREAMING_SNAKE_CASE						(       UpperCamelCase__    ,    UpperCamelCase__				)						->       Optional[Any]:







			'''simple docstring'''

			UpperCAmelCase     	=       var.abs()
			return F"""{abs_var.min():8.2e} {abs_var.max():8.2e} {ctx}"""





def 		__SCREAMING_SNAKE_CASE						(       UpperCamelCase__    ,    UpperCamelCase__				)						->       List[str]:







			'''simple docstring'''

			UpperCAmelCase     	=       False
			if torch.isnan(UpperCamelCase__				).any().item():
						UpperCAmelCase     	=       True
						print(F"""{ctx} has nans"""				)
			if torch.isinf(UpperCamelCase__				).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()    ,    100				)]
						if naaa.numel() > 0:
									print(F"""{ctx}:  n100={naaa.numel()}"""				)
						UpperCAmelCase     	=       var[torch.ge(var.abs()    ,    1000				)]
						if naaaa.numel() > 0:
									print(F"""{ctx}: n1000={naaaa.numel()}"""				)
						UpperCAmelCase     	=       var[torch.ge(var.abs()    ,    1_0000				)]
						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 			A_ (UpperCAmelCase__    ):
			UpperCAmelCase__      =    'underflow_overflow'
			UpperCAmelCase__      =    'tpu_metrics_debug'










from ...configuration_utils import PretrainedConfig
from ...utils import logging


__A       :					Any     					=     logging.get_logger(__name__)

__A       :					Tuple     					=     {
    "google/pegasus-x-base": "https://huggingface.co/google/pegasus-x-base/resolve/main/config.json",
    "google/pegasus-x-large": "https://huggingface.co/google/pegasus-x-large/resolve/main/config.json",
    # See all PEGASUS-X models at https://huggingface.co/models?filter=pegasus-x
}

class 			A_ (a_    ):
	UpperCAmelCase__      =    '''pegasus_x'''
	UpperCAmelCase__      =    ['''past_key_values''']
	UpperCAmelCase__      =    {'''num_attention_heads''': '''encoder_attention_heads''', '''hidden_size''': '''d_model'''}
	def __init__(					self							,      _A=9_6_1_0_3							,      _A=1_6_3_8_4							,      _A=1_6							,      _A=4_0_9_6							,      _A=1_6							,      _A=1_6							,      _A=4_0_9_6							,      _A=1_6							,      _A=0.0							,      _A=0.0							,      _A=True							,      _A=True							,      _A="gelu"							,      _A=1_0_2_4							,      _A=0.1							,      _A=0.0							,      _A=0.0							,      _A=0.02							,      _A=0							,      _A=True							,      _A=0							,      _A=1							,      _A=1							,      _A=3_2							,      _A=5_1_2							,      _A=True							,      **_A							,      ):






				'''simple docstring'''







				UpperCAmelCase     	=       vocab_size
				UpperCAmelCase     	=       max_position_embeddings
				UpperCAmelCase     	=       d_model
				UpperCAmelCase     	=       encoder_ffn_dim
				UpperCAmelCase     	=       encoder_layers
				UpperCAmelCase     	=       encoder_attention_heads
				UpperCAmelCase     	=       decoder_ffn_dim
				UpperCAmelCase     	=       decoder_layers
				UpperCAmelCase     	=       decoder_attention_heads
				UpperCAmelCase     	=       dropout
				UpperCAmelCase     	=       attention_dropout
				UpperCAmelCase     	=       activation_dropout
				UpperCAmelCase     	=       activation_function
				UpperCAmelCase     	=       init_std
				UpperCAmelCase     	=       encoder_layerdrop
				UpperCAmelCase     	=       decoder_layerdrop
				UpperCAmelCase     	=       use_cache
				UpperCAmelCase     	=       encoder_layers
				UpperCAmelCase     	=       scale_embedding  # scale factor will be sqrt(d_model) if True

				UpperCAmelCase     	=       num_global_tokens
				UpperCAmelCase     	=       block_size
				UpperCAmelCase     	=       stagger_local_blocks

				super().__init__(
				    pad_token_id=_A							,      eos_token_id=_A							,      is_encoder_decoder=_A							,      decoder_start_token_id=_A							,      forced_eos_token_id=_A							,      **_A							,      )
	@property
	def   _lowercase       (					self	):






				'''simple docstring'''







				return self.encoder_attention_heads







	@property
	def   _lowercase       (					self	):






				'''simple docstring'''







				return self.d_model



