



"""simple docstring"""
import collections

from .utils import ExplicitEnum, is_torch_available, logging


if is_torch_available():
      import torch


_UpperCAmelCase       =     logging.get_logger(__name__)
class    a		:



  def __init__(  self	:   Tuple    ,						lowerCAmelCase	:   List[Any]    ,						lowerCAmelCase	:   List[Any]=21    ,						lowerCAmelCase	:   Union[str, Any]=[]    ,						lowerCAmelCase	:   str=None						)       ->   Any:


     '''simple docstring'''




     SCREAMING_SNAKE_CASE_:	Tuple            =model
     SCREAMING_SNAKE_CASE_:	Union[str, Any]            =trace_batch_nums
     SCREAMING_SNAKE_CASE_:	Any            =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
     SCREAMING_SNAKE_CASE_:	Optional[int]            =collections.deque([]    ,						lowerCAmelCase						)
     SCREAMING_SNAKE_CASE_:	Union[str, Any]            =[]
     SCREAMING_SNAKE_CASE_:	Optional[int]            =0
     SCREAMING_SNAKE_CASE_:	List[str]            =0
     SCREAMING_SNAKE_CASE_:	Any            =False
     SCREAMING_SNAKE_CASE_:	Dict            ="""                 """

     self.analyse_model()

     self.register_forward_hook()



  def 		lowerCamelCase__    (  self	:   Optional[Any]    ,						lowerCAmelCase	:   List[Any]=None						)       ->   Dict:


     '''simple docstring'''




     if frame is not None:
        self.expand_frame(lowerCAmelCase						)
     self.frames.append("""\n""".join(self.frame						)						)
     SCREAMING_SNAKE_CASE_:	Dict            =[]  # start a new frame



  def 		lowerCamelCase__    (  self	:   Optional[Any]    ,						lowerCAmelCase	:   List[str]						)       ->   Any:


     '''simple docstring'''




     self.frame.append(lowerCAmelCase						)



  def 		lowerCamelCase__    (  self	:   Union[str, Any]						)       ->   Union[str, Any]:


     '''simple docstring'''




     print("""\n""".join(self.frames						)						)
     SCREAMING_SNAKE_CASE_:	str            =[]



  def 		lowerCamelCase__    (  self	:   Optional[Any]						)       ->   Dict:


     '''simple docstring'''




     SCREAMING_SNAKE_CASE_:	Dict            =[]



  def 		lowerCamelCase__    (  self	:   Union[str, Any]						)       ->   List[str]:


     '''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"""						)
     SCREAMING_SNAKE_CASE_:	int            =[]



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


     '''simple docstring'''




     SCREAMING_SNAKE_CASE_:	Tuple            ={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[int]    ,						lowerCAmelCase	:   Any    ,						lowerCAmelCase	:   int						)       ->   Union[str, Any]:


     '''simple docstring'''




     if torch.is_tensor(lowerCAmelCase						):
        self.expand_frame(get_abs_min_max(lowerCAmelCase    ,						lowerCAmelCase						)						)
        if detect_overflow(lowerCAmelCase    ,						lowerCAmelCase						):
           SCREAMING_SNAKE_CASE_:	Dict            =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	:   List[str]						)       ->   Dict:


     '''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 		lowerCamelCase__    (  self	:   Optional[Any]						)       ->   int:


     '''simple docstring'''




     self.expand_frame(f'''{self.prefix} *** Finished batch number={self.batch_number-1} ***\n\n'''						)



  def 		lowerCamelCase__    (  self	:   str    ,						lowerCAmelCase	:   Tuple    ,						lowerCAmelCase	:   Optional[int]    ,						lowerCAmelCase	:   Optional[Any]						)       ->   List[Any]:


     '''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 		lowerCamelCase__    (  self	:   Union[str, Any]						)       ->   Tuple:


     '''simple docstring'''




     self.model.apply(self._register_forward_hook						)



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


     '''simple docstring'''




     module.register_forward_hook(self.forward_hook						)





  def 		lowerCamelCase__    (  self	:   List[str]    ,						lowerCAmelCase	:   Optional[int]    ,						lowerCAmelCase	:   Optional[Any]    ,						lowerCAmelCase	:   Dict						)       ->   str:


     '''simple docstring'''




     SCREAMING_SNAKE_CASE_:	Any            =False

     SCREAMING_SNAKE_CASE_:	List[Any]            =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
        SCREAMING_SNAKE_CASE_:	Union[str, Any]            =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        __magic_name__			(							lowercase							,     lowercase	):
   SCREAMING_SNAKE_CASE_:	int            =var.abs()
   return f'''{abs_var.min():8.2e} {abs_var.max():8.2e} {ctx}'''





def        __magic_name__			(							lowercase							,     lowercase	):
   SCREAMING_SNAKE_CASE_:	Tuple            =False
   if torch.isnan(lowercase	).any().item():
      SCREAMING_SNAKE_CASE_:	int            =True
      print(f'''{ctx} has nans'''	)
   if torch.isinf(lowercase	).any().item():
      SCREAMING_SNAKE_CASE_:	str            =True
      print(f'''{ctx} has infs'''	)

   # if needed to monitor large elements can enable the following
   if 0:  # and detected:
      SCREAMING_SNAKE_CASE_:	Optional[Any]            =var[torch.ge(var.abs()							,     100	)]
      if naaa.numel() > 0:
         print(f'''{ctx}:  n100={naaa.numel()}'''	)
      SCREAMING_SNAKE_CASE_:	Optional[int]            =var[torch.ge(var.abs()							,     1000	)]
      if naaaa.numel() > 0:
         print(f'''{ctx}: n1000={naaaa.numel()}'''	)
      SCREAMING_SNAKE_CASE_:	Union[str, Any]            =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		:			Dict         =   'underflow_overflow'
  UpperCamelCase		:			List[str]         =   'tpu_metrics_debug'








"""simple docstring"""
from typing import List

from tokenizers import NormalizedString, PreTokenizedString, normalizers
class    a		:



  def __init__(  self	:   Optional[Any]    ,						lowerCAmelCase	:   List[str]						)       ->   None:


     '''simple docstring'''




     SCREAMING_SNAKE_CASE_:	int            =vocab
     SCREAMING_SNAKE_CASE_:	Union[str, Any]            =normalizers.BertNormalizer(
         clean_text=lowerCAmelCase    ,						handle_chinese_chars=lowerCAmelCase    ,						strip_accents=lowerCAmelCase    ,						lowercase=lowerCAmelCase    ,						)
     try:
        import rjieba
     except ImportError:
        raise ImportError(
            """You need to install rjieba to use RoFormerTokenizer. """
            """See https://pypi.org/project/rjieba/ for installation."""						)
     SCREAMING_SNAKE_CASE_:	Dict            =rjieba



  def 		lowerCamelCase__    (  self	:   Tuple    ,						lowerCAmelCase	:   int    ,						lowerCAmelCase	:   NormalizedString						)       ->   List[NormalizedString]:


     '''simple docstring'''




     SCREAMING_SNAKE_CASE_:	Optional[int]            =[]

     # this code slice normalized_string is too slow (6s) but test_alignement_methods can pass
     for token, start, end in self.jieba.tokenize(str(lowerCAmelCase						)    ,						hmm=lowerCAmelCase						):
        if token in self.vocab:
           splits.append(normalized_string[start:end]						)
        else:
           SCREAMING_SNAKE_CASE_:	List[Any]            =self.normalizers.normalize_str(lowerCAmelCase						).split()
           for token in token_list:
              if token:
                 SCREAMING_SNAKE_CASE_:	Dict            =start + len(lowerCAmelCase						)
                 splits.append(normalized_string[start:end]						)
                 SCREAMING_SNAKE_CASE_:	Optional[Any]            =end

        # this code test_alignement_methods can't pass but fast (300ms)
        # for token in self.jieba.cut(str(normalized_string), False):
        #     if token in self.vocab:
        #         splits.append(NormalizedString(token))
        #     else:
        #         token_list = self.normalizers.normalize_str(token).split()
        #         for token in token_list:
        #             if token:
        #                 splits.append(NormalizedString(token))

     return splits





  def 		lowerCamelCase__    (  self	:   Union[str, Any]    ,						lowerCAmelCase	:   PreTokenizedString						)       ->   Tuple:


     '''simple docstring'''




     pretok.split(self.jieba_split						)



