"""simple docstring"""






from typing import List, Optional, Union

import numpy as np

from ...feature_extraction_sequence_utils import SequenceFeatureExtractor
from ...feature_extraction_utils import BatchFeature
from ...utils import PaddingStrategy, TensorType, logging


lowerCAmelCase__  :  List[str]											=     logging.get_logger(__name__)
class     snake_case	(			__UpperCAmelCase    ):




					"""simple docstring"""

					snake_case__       =			["input_values", "attention_mask"]







					def __init__(    self       :     Optional[int]   ,lowerCamelCase__       :     Union[str, Any]=1   ,lowerCamelCase__       :     Optional[Any]=16_000   ,lowerCamelCase__       :     Optional[int]=0.0   ,lowerCamelCase__       :     Any=False   ,lowerCamelCase__       :     List[Any]=True   ,**lowerCamelCase__       :     str   ,):
									super().__init__(feature_size=lowerCamelCase__   ,sampling_rate=lowerCamelCase__   ,padding_value=lowerCamelCase__   ,**lowerCamelCase__      )
									UpperCAmelCase__					=							return_attention_mask
									UpperCAmelCase__					=							do_normalize







					@staticmethod
					def 		__lowerCAmelCase						(    lowerCamelCase__       :     List[np.ndarray]   ,lowerCamelCase__       :     List[np.ndarray]   ,lowerCamelCase__       :     float = 0.0      ):
									if attention_mask is not None:
													UpperCAmelCase__					=							np.array(lowerCamelCase__   ,np.intaa      )
													UpperCAmelCase__					=							[]

													for vector, length in zip(lowerCamelCase__   ,attention_mask.sum(-1      )      ):
																	UpperCAmelCase__					=							(vector - vector[:length].mean()) / np.sqrt(vector[:length].var() + 1e-7      )
																	if length < normed_slice.shape[0]:
																					UpperCAmelCase__					=							padding_value

																	normed_input_values.append(lowerCamelCase__      )
									else:
													UpperCAmelCase__					=							[(x - x.mean()) / np.sqrt(x.var() + 1e-7      ) for x in input_values]

									return normed_input_values







					def __call__(    self       :     Dict   ,lowerCamelCase__       :     Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]]   ,lowerCamelCase__       :     Union[bool, str, PaddingStrategy] = False   ,lowerCamelCase__       :     Optional[int] = None   ,lowerCamelCase__       :     bool = False   ,lowerCamelCase__       :     Optional[int] = None   ,lowerCamelCase__       :     Optional[bool] = None   ,lowerCamelCase__       :     Optional[Union[str, TensorType]] = None   ,lowerCamelCase__       :     Optional[int] = None   ,**lowerCamelCase__       :     int   ,):

									if sampling_rate is not None:
													if sampling_rate != self.sampling_rate:
																	raise ValueError(
																	    f'''The model corresponding to this feature extractor: {self} was trained using a sampling rate of'''
																	    f''' {self.sampling_rate}. Please make sure that the provided `raw_speech` input was sampled with'''
																	    f''' {self.sampling_rate} and not {sampling_rate}.'''      )
									else:
													logger.warning(
													    'It is strongly recommended to pass the ``sampling_rate`` argument to this function. '
													    'Failing to do so can result in silent errors that might be hard to debug.'      )

									UpperCAmelCase__					=							isinstance(lowerCamelCase__   ,np.ndarray      ) and len(raw_speech.shape      ) > 1
									if is_batched_numpy and len(raw_speech.shape      ) > 2:
													raise ValueError(f'''Only mono-channel audio is supported for input to {self}'''      )
									UpperCAmelCase__					=							is_batched_numpy or (
									    isinstance(lowerCamelCase__   ,(list, tuple)      ) and (isinstance(raw_speech[0]   ,(np.ndarray, tuple, list)      ))
									)

									# always return batch
									if not is_batched:
													UpperCAmelCase__					=							[raw_speech]

									# convert into correct format for padding
									UpperCAmelCase__					=							BatchFeature({'input_values': raw_speech}      )

									UpperCAmelCase__					=							self.pad(
									    lowerCamelCase__   ,padding=lowerCamelCase__   ,max_length=lowerCamelCase__   ,truncation=lowerCamelCase__   ,pad_to_multiple_of=lowerCamelCase__   ,return_attention_mask=lowerCamelCase__   ,)

									# convert input values to correct format
									UpperCAmelCase__					=							padded_inputs['input_values']
									if not isinstance(input_values[0]   ,np.ndarray      ):
													UpperCAmelCase__					=							[np.asarray(lowerCamelCase__   ,dtype=np.floataa      ) for array in input_values]
									elif (
									    not isinstance(lowerCamelCase__   ,np.ndarray      )
									    and isinstance(input_values[0]   ,np.ndarray      )
									    and input_values[0].dtype is np.dtype(np.floataa      )
									):
													UpperCAmelCase__					=							[array.astype(np.floataa      ) for array in input_values]
									elif isinstance(lowerCamelCase__   ,np.ndarray      ) and input_values.dtype is np.dtype(np.floataa      ):
													UpperCAmelCase__					=							input_values.astype(np.floataa      )

									# convert attention_mask to correct format
									UpperCAmelCase__					=							padded_inputs.get('attention_mask'      )
									if attention_mask is not None:
													UpperCAmelCase__					=							[np.asarray(lowerCamelCase__   ,dtype=np.intaa      ) for array in attention_mask]

									# zero-mean and unit-variance normalization
									if self.do_normalize:
													UpperCAmelCase__					=							(
													    attention_mask
													    if self._get_padding_strategies(lowerCamelCase__   ,max_length=lowerCamelCase__      ) is not PaddingStrategy.DO_NOT_PAD
													    else None
													)
													UpperCAmelCase__					=							self.zero_mean_unit_var_norm(
													    padded_inputs['input_values']   ,attention_mask=lowerCamelCase__   ,padding_value=self.padding_value      )

									if return_tensors is not None:
													UpperCAmelCase__					=							padded_inputs.convert_to_tensors(lowerCamelCase__      )

									return padded_inputs




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



