
import json
import os
import re
import unicodedata
from typing import Optional, Tuple

from ...tokenization_utils import PreTrainedTokenizer, _is_control, _is_punctuation, _is_whitespace
from ...utils import logging


__UpperCAmelCase   						=     logging.get_logger(__name__)

__UpperCAmelCase   						=     {
    "vocab_file": "vocab.json",
    "merges_file": "merges.txt",
}

__UpperCAmelCase   						=     {
    "vocab_file": {"openai-gpt": "https://huggingface.co/openai-gpt/resolve/main/vocab.json"},
    "merges_file": {"openai-gpt": "https://huggingface.co/openai-gpt/resolve/main/merges.txt"},
}

__UpperCAmelCase   						=     {
    "openai-gpt": 5_12,
}


def  A__ (       __lowerCamelCase						):
   SCREAMING_SNAKE_CASE_	=      text.strip()
   if not text:
      return []
   SCREAMING_SNAKE_CASE_	=      text.split()
   return tokens





class 				UpperCamelCase__		(	__SCREAMING_SNAKE_CASE	):






       """simple docstring"""


       def __init__(							self ,     _A=True ,     _A=None ,     _A=True ,     _A=None ,     _A=True ,     )				->				Tuple:
          if never_split is None:
             SCREAMING_SNAKE_CASE_	=      []
          SCREAMING_SNAKE_CASE_	=      do_lower_case
          SCREAMING_SNAKE_CASE_	=      set(_A	)
          SCREAMING_SNAKE_CASE_	=      tokenize_chinese_chars
          SCREAMING_SNAKE_CASE_	=      strip_accents
          SCREAMING_SNAKE_CASE_	=      do_split_on_punc



       def     _UpperCamelCase	(							self ,     _A ,     _A=None	)				->				Dict:
          SCREAMING_SNAKE_CASE_	=      self.never_split.union(set(_A	)	) if never_split else self.never_split
          SCREAMING_SNAKE_CASE_	=      self._clean_text(_A	)

          # This was added on November 1st, 2018 for the multilingual and Chinese
          # models. This is also applied to the English models now, but it doesn't
          # matter since the English models were not trained on any Chinese data
          # and generally don't have any Chinese data in them (there are Chinese
          # characters in the vocabulary because Wikipedia does have some Chinese
          # words in the English Wikipedia.).
          if self.tokenize_chinese_chars:
             SCREAMING_SNAKE_CASE_	=      self._tokenize_chinese_chars(_A	)
          # prevents treating the same character with different unicode codepoints as different characters
          SCREAMING_SNAKE_CASE_	=      unicodedata.normalize('''NFC''' ,     _A	)
          SCREAMING_SNAKE_CASE_	=      whitespace_tokenize(_A	)
          SCREAMING_SNAKE_CASE_	=      []
          for token in orig_tokens:
             if token not in never_split:
                if self.do_lower_case:
                   SCREAMING_SNAKE_CASE_	=      token.lower()
                   if self.strip_accents is not False:
                      SCREAMING_SNAKE_CASE_	=      self._run_strip_accents(_A	)
                elif self.strip_accents:
                   SCREAMING_SNAKE_CASE_	=      self._run_strip_accents(_A	)
             split_tokens.extend(self._run_split_on_punc(_A ,     _A	)	)

          SCREAMING_SNAKE_CASE_	=      whitespace_tokenize(''' '''.join(_A	)	)
          return output_tokens



       def     _UpperCamelCase	(							self ,     _A	)				->				Any:
          SCREAMING_SNAKE_CASE_	=      unicodedata.normalize('''NFD''' ,     _A	)
          SCREAMING_SNAKE_CASE_	=      []
          for char in text:
             SCREAMING_SNAKE_CASE_	=      unicodedata.category(_A	)
             if cat == "Mn":
                continue
             output.append(_A	)
          return "".join(_A	)



       def     _UpperCamelCase	(							self ,     _A ,     _A=None	)				->				Optional[int]:
          if not self.do_split_on_punc or (never_split is not None and text in never_split):
             return [text]
          SCREAMING_SNAKE_CASE_	=      list(_A	)
          SCREAMING_SNAKE_CASE_	=      0
          SCREAMING_SNAKE_CASE_	=      True
          SCREAMING_SNAKE_CASE_	=      []
          while i < len(_A	):
             SCREAMING_SNAKE_CASE_	=      chars[i]
             if _is_punctuation(_A	):
                output.append([char]	)
                SCREAMING_SNAKE_CASE_	=      True
             else:
                if start_new_word:
                   output.append([]	)
                SCREAMING_SNAKE_CASE_	=      False
                output[-1].append(_A	)
             i += 1

          return ["".join(_A	) for x in output]



       def     _UpperCamelCase	(							self ,     _A	)				->				str:
          SCREAMING_SNAKE_CASE_	=      []
          for char in text:
             SCREAMING_SNAKE_CASE_	=      ord(_A	)
             if self._is_chinese_char(_A	):
                output.append(''' '''	)
                output.append(_A	)
                output.append(''' '''	)
             else:
                output.append(_A	)
          return "".join(_A	)



       def     _UpperCamelCase	(							self ,     _A	)				->				str:
          # This defines a "chinese character" as anything in the CJK Unicode block:
          #   https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block)
          #
          # Note that the CJK Unicode block is NOT all Japanese and Korean characters,
          # despite its name. The modern Korean Hangul alphabet is a different block,
          # as is Japanese Hiragana and Katakana. Those alphabets are used to write
          # space-separated words, so they are not treated specially and handled
          # like the all of the other languages.
          if (
              (cp >= 0X4E00 and cp <= 0X9FFF)
              or (cp >= 0X3400 and cp <= 0X4DBF)  #
              or (cp >= 0X2_0000 and cp <= 0X2_A6DF)  #
              or (cp >= 0X2_A700 and cp <= 0X2_B73F)  #
              or (cp >= 0X2_B740 and cp <= 0X2_B81F)  #
              or (cp >= 0X2_B820 and cp <= 0X2_CEAF)  #
              or (cp >= 0XF900 and cp <= 0XFAFF)
              or (cp >= 0X2_F800 and cp <= 0X2_FA1F)  #
          ):  #
             return True

          return False




       def     _UpperCamelCase	(							self ,     _A	)				->				Optional[Any]:
          SCREAMING_SNAKE_CASE_	=      []
          for char in text:
             SCREAMING_SNAKE_CASE_	=      ord(_A	)
             if cp == 0 or cp == 0XFFFD or _is_control(_A	):
                continue
             if _is_whitespace(_A	):
                output.append(''' '''	)
             else:
                output.append(_A	)
          return "".join(_A	)







def  A__ (       __lowerCamelCase						):
   SCREAMING_SNAKE_CASE_	=      set()
   SCREAMING_SNAKE_CASE_	=      word[0]
   for char in word[1:]:
      pairs.add((prev_char, char)						)
      SCREAMING_SNAKE_CASE_	=      char
   return pairs


def  A__ (       __lowerCamelCase						):
   SCREAMING_SNAKE_CASE_	=      text.replace('''—''',  '''-'''						)
   SCREAMING_SNAKE_CASE_	=      text.replace('''–''',  '''-'''						)
   SCREAMING_SNAKE_CASE_	=      text.replace('''―''',  '''-'''						)
   SCREAMING_SNAKE_CASE_	=      text.replace('''…''',  '''...'''						)
   SCREAMING_SNAKE_CASE_	=      text.replace('''´''',  '''\''''						)
   SCREAMING_SNAKE_CASE_	=      re.sub(r'''(-+|~+|!+|"+|;+|\?+|\++|,+|\)+|\(+|\\+|\/+|\*+|\[+|\]+|}+|{+|\|+|_+)''',  r''' \1 ''',  __lowerCamelCase						)
   SCREAMING_SNAKE_CASE_	=      re.sub(r'''\s*\n\s*''',  ''' \n ''',  __lowerCamelCase						)
   SCREAMING_SNAKE_CASE_	=      re.sub(r'''[^\S\n]+''',  ''' ''',  __lowerCamelCase						)
   return text.strip()





class 				UpperCamelCase__		(	__SCREAMING_SNAKE_CASE	):






       """simple docstring"""


       UpperCAmelCase_				       =VOCAB_FILES_NAMES
       UpperCAmelCase_				       =PRETRAINED_VOCAB_FILES_MAP
       UpperCAmelCase_				       =PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
       UpperCAmelCase_				       =["input_ids", "attention_mask"]



       def __init__(							self ,     _A ,     _A ,     _A="<unk>" ,     **_A	)				->				Optional[Any]:
          super().__init__(unk_token=_A ,     **_A	)

          try:
             import ftfy
             from spacy.lang.en import English

             SCREAMING_SNAKE_CASE_	=      English()
             SCREAMING_SNAKE_CASE_	=      _nlp.tokenizer
             SCREAMING_SNAKE_CASE_	=      ftfy.fix_text
          except ImportError:
             logger.warning('''ftfy or spacy is not installed using BERT BasicTokenizer instead of SpaCy & ftfy.'''	)
             SCREAMING_SNAKE_CASE_	=      BasicTokenizer(do_lower_case=_A	)
             SCREAMING_SNAKE_CASE_	=      None

          with open(_A ,     encoding='''utf-8'''	) as vocab_handle:
             SCREAMING_SNAKE_CASE_	=      json.load(_A	)
          SCREAMING_SNAKE_CASE_	=      {v: k for k, v in self.encoder.items()}
          with open(_A ,     encoding='''utf-8'''	) as merges_handle:
             SCREAMING_SNAKE_CASE_	=      merges_handle.read().split('''\n'''	)[1:-1]
          SCREAMING_SNAKE_CASE_	=      [tuple(merge.split()	) for merge in merges]
          SCREAMING_SNAKE_CASE_	=      dict(zip(_A ,     range(len(_A	)	)	)	)
          SCREAMING_SNAKE_CASE_	=      {}



       @property
       def     _UpperCamelCase	(							self	)				->				Dict:
          return True



       @property
       def     _UpperCamelCase	(							self	)				->				List[str]:
          return len(self.encoder	)



       def     _UpperCamelCase	(							self	)				->				Optional[int]:
          return dict(self.encoder ,     **self.added_tokens_encoder	)



       def     _UpperCamelCase	(							self ,     _A	)				->				List[str]:
          SCREAMING_SNAKE_CASE_	=      tuple(token[:-1]	) + (token[-1] + '''</w>''',)
          if token in self.cache:
             return self.cache[token]
          SCREAMING_SNAKE_CASE_	=      get_pairs(_A	)

          if not pairs:
             return token + "</w>"

          while True:
             SCREAMING_SNAKE_CASE_	=      min(_A ,     key=lambda _A	: self.bpe_ranks.get(_A ,     float('''inf'''	)	)	)
             if bigram not in self.bpe_ranks:
                break
             SCREAMING_SNAKE_CASE_	, SCREAMING_SNAKE_CASE_	=      bigram
             SCREAMING_SNAKE_CASE_	=      []
             SCREAMING_SNAKE_CASE_	=      0
             while i < len(_A	):
                try:
                   SCREAMING_SNAKE_CASE_	=      word.index(_A ,     _A	)
                except ValueError:
                   new_word.extend(word[i:]	)
                   break
                else:
                   new_word.extend(word[i:j]	)
                   SCREAMING_SNAKE_CASE_	=      j

                if word[i] == first and i < len(_A	) - 1 and word[i + 1] == second:
                   new_word.append(first + second	)
                   i += 2
                else:
                   new_word.append(word[i]	)
                   i += 1
             SCREAMING_SNAKE_CASE_	=      tuple(_A	)
             SCREAMING_SNAKE_CASE_	=      new_word
             if len(_A	) == 1:
                break
             else:
                SCREAMING_SNAKE_CASE_	=      get_pairs(_A	)
          SCREAMING_SNAKE_CASE_	=      ''' '''.join(_A	)
          if word == "\n  </w>":
             SCREAMING_SNAKE_CASE_	=      '''\n</w>'''
          SCREAMING_SNAKE_CASE_	=      word
          return word



       def     _UpperCamelCase	(							self ,     _A	)				->				str:
          SCREAMING_SNAKE_CASE_	=      []
          if self.fix_text is None:
             # Using BERT's BasicTokenizer
             SCREAMING_SNAKE_CASE_	=      self.nlp.tokenize(_A	)
             for token in text:
                split_tokens.extend(list(self.bpe(_A	).split(''' '''	)	)	)
          else:
             # Using SpaCy & ftfy (original tokenization process of OpenAI GPT)
             SCREAMING_SNAKE_CASE_	=      self.nlp(text_standardize(self.fix_text(_A	)	)	)
             for token in text:
                split_tokens.extend(list(self.bpe(token.text.lower()	).split(''' '''	)	)	)
          return split_tokens



       def     _UpperCamelCase	(							self ,     _A	)				->				Optional[int]:
          return self.encoder.get(_A ,     self.encoder.get(self.unk_token	)	)



       def     _UpperCamelCase	(							self ,     _A	)				->				List[str]:
          return self.decoder.get(_A ,     self.unk_token	)



       def     _UpperCamelCase	(							self ,     _A	)				->				str:
          SCREAMING_SNAKE_CASE_	=      ''''''.join(_A	).replace('''</w>''' ,     ''' '''	).strip()
          return out_string




       def     _UpperCamelCase	(							self ,     _A ,     _A = None	)				->				Tuple[str]:
          if not os.path.isdir(_A	):
             logger.error(F'''Vocabulary path ({save_directory}) should be a directory'''	)
             return
          SCREAMING_SNAKE_CASE_	=      os.path.join(
              _A ,     (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file''']	)
          SCREAMING_SNAKE_CASE_	=      os.path.join(
              _A ,     (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''merges_file''']	)

          with open(_A ,     '''w''' ,     encoding='''utf-8'''	) as f:
             f.write(json.dumps(self.encoder ,     indent=2 ,     sort_keys=_A ,     ensure_ascii=_A	) + '''\n'''	)

          SCREAMING_SNAKE_CASE_	=      0
          with open(_A ,     '''w''' ,     encoding='''utf-8'''	) as writer:
             writer.write('''#version: 0.2\n'''	)
             for bpe_tokens, token_index in sorted(self.bpe_ranks.items() ,     key=lambda _A	: kv[1]	):
                if index != token_index:
                   logger.warning(
                       F'''Saving vocabulary to {merge_file}: BPE merge indices are not consecutive.'''
                       ''' Please check that the tokenizer is not corrupted!'''	)
                   SCREAMING_SNAKE_CASE_	=      token_index
                writer.write(''' '''.join(_A	) + '''\n'''	)
                index += 1

          return vocab_file, merge_file




import collections

from .utils import ExplicitEnum, is_torch_available, logging


if is_torch_available():
   import torch


__UpperCAmelCase   						=     logging.get_logger(__name__)





class 				UpperCamelCase__		:






       """simple docstring"""


       def __init__(							self ,     _A ,     _A=21 ,     _A=[] ,     _A=None	)				->				List[Any]:
          SCREAMING_SNAKE_CASE_	=      model
          SCREAMING_SNAKE_CASE_	=      trace_batch_nums
          SCREAMING_SNAKE_CASE_	=      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_	=      collections.deque([] ,     _A	)
          SCREAMING_SNAKE_CASE_	=      []
          SCREAMING_SNAKE_CASE_	=      0
          SCREAMING_SNAKE_CASE_	=      0
          SCREAMING_SNAKE_CASE_	=      False
          SCREAMING_SNAKE_CASE_	=      '''                 '''

          self.analyse_model()

          self.register_forward_hook()



       def     _UpperCamelCase	(							self ,     _A=None	)				->				Any:
          if frame is not None:
             self.expand_frame(_A	)
          self.frames.append('''\n'''.join(self.frame	)	)
          SCREAMING_SNAKE_CASE_	=      []  # start a new frame



       def     _UpperCamelCase	(							self ,     _A	)				->				List[Any]:
          self.frame.append(_A	)



       def     _UpperCamelCase	(							self	)				->				Optional[Any]:
          print('''\n'''.join(self.frames	)	)
          SCREAMING_SNAKE_CASE_	=      []



       def     _UpperCamelCase	(							self	)				->				int:
          SCREAMING_SNAKE_CASE_	=      []



       def     _UpperCamelCase	(							self	)				->				List[str]:
          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_	=      []



       def     _UpperCamelCase	(							self	)				->				Optional[int]:
          # 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
          SCREAMING_SNAKE_CASE_	=      {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     _UpperCamelCase	(							self ,     _A ,     _A	)				->				Union[str, Any]:
          if torch.is_tensor(_A	):
             self.expand_frame(get_abs_min_max(_A ,     _A	)	)
             if detect_overflow(_A ,     _A	):
                SCREAMING_SNAKE_CASE_	=      True
          elif var is None:
             self.expand_frame(F'''{"None":>17} {ctx}'''	)
          else:
             self.expand_frame(F'''{"not a tensor":>17} {ctx}'''	)



       def     _UpperCamelCase	(							self	)				->				List[str]:
          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     _UpperCamelCase	(							self	)				->				List[Any]:
          self.expand_frame(F'''{self.prefix} *** Finished batch number={self.batch_number-1} ***\n\n'''	)



       def     _UpperCamelCase	(							self ,     _A ,     _A ,     _A	)				->				Union[str, Any]:
          self.expand_frame(F'''{self.prefix} {self.module_names[module]} {module.__class__.__name__}'''	)

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

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

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

          self.save_frame()



       def     _UpperCamelCase	(							self	)				->				List[Any]:
          self.model.apply(self._register_forward_hook	)



       def     _UpperCamelCase	(							self ,     _A	)				->				Tuple:
          module.register_forward_hook(self.forward_hook	)




       def     _UpperCamelCase	(							self ,     _A ,     _A ,     _A	)				->				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

          SCREAMING_SNAKE_CASE_	=      False

          SCREAMING_SNAKE_CASE_	=      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_	=      True

          self.create_frame(_A ,     _A ,     _A	)

          # 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						):
   SCREAMING_SNAKE_CASE_	=      var.abs()
   return F'''{abs_var.min():8.2e} {abs_var.max():8.2e} {ctx}'''


def  A__ (       __lowerCamelCase,  __lowerCamelCase						):
   SCREAMING_SNAKE_CASE_	=      False
   if torch.isnan(__lowerCamelCase						).any().item():
      SCREAMING_SNAKE_CASE_	=      True
      print(F'''{ctx} has nans'''						)
   if torch.isinf(__lowerCamelCase						).any().item():
      SCREAMING_SNAKE_CASE_	=      True
      print(F'''{ctx} has infs'''						)

   # if needed to monitor large elements can enable the following
   if 0:  # and detected:
      SCREAMING_SNAKE_CASE_	=      var[torch.ge(var.abs(),  1_00						)]
      if naaa.numel() > 0:
         print(F'''{ctx}:  n100={naaa.numel()}'''						)
      SCREAMING_SNAKE_CASE_	=      var[torch.ge(var.abs(),  10_00						)]
      if naaaa.numel() > 0:
         print(F'''{ctx}: n1000={naaaa.numel()}'''						)
      SCREAMING_SNAKE_CASE_	=      var[torch.ge(var.abs(),  1_00_00						)]
      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 				UpperCamelCase__		(	__SCREAMING_SNAKE_CASE	):






       """simple docstring"""


       UpperCAmelCase_				       ="underflow_overflow"
       UpperCAmelCase_				       ="tpu_metrics_debug"


