






from collections import OrderedDict
from typing import TYPE_CHECKING, Any, List, Mapping, Optional

from packaging import version


if TYPE_CHECKING:
     from ... import PreTrainedTokenizer, TensorType

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfigWithPast, PatchingSpec
from ...utils import is_torch_available, logging


UpperCAmelCase__				   =		logging.get_logger(__name__)

UpperCAmelCase__				   =		{
    "bigscience/bloom": "https://huggingface.co/bigscience/bloom/resolve/main/config.json",
    "bigscience/bloom-560m": "https://huggingface.co/bigscience/bloom-560m/blob/main/config.json",
    "bigscience/bloom-1b1": "https://huggingface.co/bigscience/bloom-1b1/blob/main/config.json",
    "bigscience/bloom-1b7": "https://huggingface.co/bigscience/bloom-1b7/blob/main/config.json",
    "bigscience/bloom-3b": "https://huggingface.co/bigscience/bloom-3b/blob/main/config.json",
    "bigscience/bloom-7b1": "https://huggingface.co/bigscience/bloom-7b1/blob/main/config.json",
}






class 		lowercase_					(	lowercase   ):






      '''simple docstring'''




      __snake_case       =  '''bloom'''
      __snake_case       =  ['''past_key_values''']
      __snake_case       =  {
          '''num_hidden_layers''': '''n_layer''',
          '''num_attention_heads''': '''n_head''',
      }







      def __init__(      self      :						Optional[Any] ,					__UpperCAmelCase      :						int=250_880 ,					__UpperCAmelCase      :						Tuple=64 ,					__UpperCAmelCase      :						Optional[int]=2 ,					__UpperCAmelCase      :						str=8 ,					__UpperCAmelCase      :						Union[str, Any]=1e-5 ,					__UpperCAmelCase      :						Union[str, Any]=0.02 ,					__UpperCAmelCase      :						str=True ,					__UpperCAmelCase      :						List[str]=1 ,					__UpperCAmelCase      :						Any=2 ,					__UpperCAmelCase      :						List[Any]=False ,					__UpperCAmelCase      :						Union[str, Any]=0.0 ,					__UpperCAmelCase      :						int=0.0 ,					__UpperCAmelCase      :						str=1 ,					__UpperCAmelCase      :						Optional[Any]=False ,					**__UpperCAmelCase      :						Any ,					)    ->Any:




       """simple docstring"""


       a		  =      vocab_size
       # Backward compatibility with n_embed kwarg
       a		  =      kwargs.pop('''n_embed''' ,					__UpperCAmelCase  )
       a		  =      hidden_size if n_embed is None else n_embed
       a		  =      n_layer
       a		  =      n_head
       a		  =      layer_norm_epsilon
       a		  =      initializer_range
       a		  =      use_cache
       a		  =      pretraining_tp
       a		  =      apply_residual_connection_post_layernorm
       a		  =      hidden_dropout
       a		  =      attention_dropout

       a		  =      bos_token_id
       a		  =      eos_token_id
       a		  =      slow_but_exact

       super().__init__(bos_token_id=__UpperCAmelCase ,					eos_token_id=__UpperCAmelCase ,					**__UpperCAmelCase  )






class 		lowercase_					(	lowercase   ):






      '''simple docstring'''




      __snake_case       =  version.parse('''1.12'''   )







      def __init__(      self      :						Optional[int] ,					__UpperCAmelCase      :						PretrainedConfig ,					__UpperCAmelCase      :						str = "default" ,					__UpperCAmelCase      :						List[PatchingSpec] = None ,					__UpperCAmelCase      :						bool = False ,					)    ->List[str]:




       """simple docstring"""


       super().__init__(__UpperCAmelCase ,					task=__UpperCAmelCase ,					patching_specs=__UpperCAmelCase ,					use_past=__UpperCAmelCase  )
       if not getattr(self._config ,					'''pad_token_id''' ,					__UpperCAmelCase  ):
        # TODO: how to do that better?
        a		  =      0







      @property
      def       __lowerCAmelCase					(      self      :						Dict  )    ->Mapping[str, Mapping[int, str]]:




       """simple docstring"""


       a		  =      OrderedDict({'''input_ids''': {0: '''batch''', 1: '''sequence'''}}  )
       if self.use_past:
        # BLOOM stores values on dynamic axis 2. For more details see: https://github.com/huggingface/transformers/pull/18344
        self.fill_with_past_key_values_(__UpperCAmelCase ,					direction='''inputs''' ,					inverted_values_shape=__UpperCAmelCase  )
        a		  =      {0: '''batch''', 1: '''past_sequence + sequence'''}
       else:
        a		  =      {0: '''batch''', 1: '''sequence'''}

       return common_inputs







      @property
      def       __lowerCAmelCase					(      self      :						Any  )    ->int:




       """simple docstring"""


       return self._config.n_layer







      @property
      def       __lowerCAmelCase					(      self      :						int  )    ->int:




       """simple docstring"""


       return self._config.n_head







      @property
      def       __lowerCAmelCase					(      self      :						Any  )    ->float:




       """simple docstring"""


       return 1e-3







      def       __lowerCAmelCase					(      self      :						List[str] ,					__UpperCAmelCase      :						"PreTrainedTokenizer" ,					__UpperCAmelCase      :						int = -1 ,					__UpperCAmelCase      :						int = -1 ,					__UpperCAmelCase      :						bool = False ,					__UpperCAmelCase      :						Optional["TensorType"] = None ,					)    ->Mapping[str, Any]:




       """simple docstring"""


       a		  =      super(__UpperCAmelCase ,					self  ).generate_dummy_inputs(
           __UpperCAmelCase ,					batch_size=__UpperCAmelCase ,					seq_length=__UpperCAmelCase ,					is_pair=__UpperCAmelCase ,					framework=__UpperCAmelCase  )

       # We need to order the input in the way they appears in the forward()
       a		  =      OrderedDict({'''input_ids''': common_inputs['''input_ids''']}  )

       # Need to add the past_keys
       if self.use_past:
        if not is_torch_available():
         raise ValueError('''Cannot generate dummy past_keys inputs without PyTorch installed.'''  )
        else:
         import torch

         a  ,     a		  =      common_inputs['''input_ids'''].shape
         # Not using the same length for past_key_values
         a		  =      seqlen + 2
         a		  =      self._config.hidden_size // self.num_attention_heads
         a		  =      (
             batch * self.num_attention_heads,
             head_dim,
             past_key_values_length,
         )
         a		  =      (
             batch * self.num_attention_heads,
             past_key_values_length,
             head_dim,
         )
         a		  =      [
             (torch.zeros(__UpperCAmelCase  ), torch.zeros(__UpperCAmelCase  )) for _ in range(self.num_layers  )
         ]

       a		  =      common_inputs['''attention_mask''']
       if self.use_past:
        a		  =      ordered_inputs['''attention_mask'''].dtype
        a		  =      torch.cat(
            [ordered_inputs['''attention_mask'''], torch.ones(__UpperCAmelCase ,					__UpperCAmelCase ,					dtype=__UpperCAmelCase  )] ,					dim=1  )

       return ordered_inputs







      @property
      def       __lowerCAmelCase					(      self      :						Tuple  )    ->int:




       """simple docstring"""


       return 13










import os
import unittest

from transformers import BatchEncoding
from transformers.models.bert.tokenization_bert import (
    BasicTokenizer,
    WordpieceTokenizer,
    _is_control,
    _is_punctuation,
    _is_whitespace,
)
from transformers.models.prophetnet.tokenization_prophetnet import VOCAB_FILES_NAMES, ProphetNetTokenizer
from transformers.testing_utils import require_torch, slow

from ...test_tokenization_common import TokenizerTesterMixin






class 		lowercase_					(	lowercase ,  unittest.TestCase   ):






      '''simple docstring'''




      __snake_case       =  ProphetNetTokenizer
      __snake_case       =  False







      def       __lowerCAmelCase					(      self      :						Optional[int]  )    ->Optional[Any]:




       """simple docstring"""


       super().setUp()

       a		  =      [
           '''[UNK]''',
           '''[CLS]''',
           '''[SEP]''',
           '''[PAD]''',
           '''[MASK]''',
           '''want''',
           '''##want''',
           '''##ed''',
           '''wa''',
           '''un''',
           '''runn''',
           '''##ing''',
           ''',''',
           '''low''',
           '''lowest''',
       ]
       a		  =      os.path.join(self.tmpdirname ,					VOCAB_FILES_NAMES['''vocab_file''']  )
       with open(self.vocab_file ,					'''w''' ,					encoding='''utf-8'''  ) as vocab_writer:
        vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens]  )  )







      def       __lowerCAmelCase					(      self      :						List[str] ,					__UpperCAmelCase      :						str  )    ->Dict:




       """simple docstring"""


       a		  =      '''UNwant\u00E9d,running'''
       a		  =      '''unwanted, running'''
       return input_text, output_text







      def       __lowerCAmelCase					(      self      :						Optional[int]  )    ->Optional[Any]:




       """simple docstring"""


       a		  =      self.tokenizer_class(self.vocab_file  )

       a		  =      tokenizer.tokenize('''UNwant\u00E9d,running'''  )
       self.assertListEqual(__UpperCAmelCase ,					['''un''', '''##want''', '''##ed''', ''',''', '''runn''', '''##ing''']  )
       self.assertListEqual(tokenizer.convert_tokens_to_ids(__UpperCAmelCase  ) ,					[9, 6, 7, 12, 10, 11]  )







      def       __lowerCAmelCase					(      self      :						int  )    ->Any:




       """simple docstring"""


       a		  =      BasicTokenizer()

       self.assertListEqual(tokenizer.tokenize('''ah\u535A\u63A8zz'''  ) ,					['''ah''', '''\u535A''', '''\u63A8''', '''zz''']  )







      def       __lowerCAmelCase					(      self      :						Any  )    ->int:




       """simple docstring"""


       a		  =      BasicTokenizer(do_lower_case=__UpperCAmelCase  )

       self.assertListEqual(
           tokenizer.tokenize(''' \tHeLLo!how  \n Are yoU?  '''  ) ,					['''hello''', '''!''', '''how''', '''are''', '''you''', '''?''']  )
       self.assertListEqual(tokenizer.tokenize('''H\u00E9llo'''  ) ,					['''hello''']  )







      def       __lowerCAmelCase					(      self      :						Union[str, Any]  )    ->Optional[int]:




       """simple docstring"""


       a		  =      BasicTokenizer(do_lower_case=__UpperCAmelCase ,					strip_accents=__UpperCAmelCase  )

       self.assertListEqual(
           tokenizer.tokenize(''' \tHäLLo!how  \n Are yoU?  '''  ) ,					['''hällo''', '''!''', '''how''', '''are''', '''you''', '''?''']  )
       self.assertListEqual(tokenizer.tokenize('''H\u00E9llo'''  ) ,					['''h\u00E9llo''']  )







      def       __lowerCAmelCase					(      self      :						Dict  )    ->str:




       """simple docstring"""


       a		  =      BasicTokenizer(do_lower_case=__UpperCAmelCase ,					strip_accents=__UpperCAmelCase  )

       self.assertListEqual(
           tokenizer.tokenize(''' \tHäLLo!how  \n Are yoU?  '''  ) ,					['''hallo''', '''!''', '''how''', '''are''', '''you''', '''?''']  )
       self.assertListEqual(tokenizer.tokenize('''H\u00E9llo'''  ) ,					['''hello''']  )







      def       __lowerCAmelCase					(      self      :						Any  )    ->Dict:




       """simple docstring"""


       a		  =      BasicTokenizer(do_lower_case=__UpperCAmelCase  )

       self.assertListEqual(
           tokenizer.tokenize(''' \tHäLLo!how  \n Are yoU?  '''  ) ,					['''hallo''', '''!''', '''how''', '''are''', '''you''', '''?''']  )
       self.assertListEqual(tokenizer.tokenize('''H\u00E9llo'''  ) ,					['''hello''']  )







      def       __lowerCAmelCase					(      self      :						Tuple  )    ->Optional[Any]:




       """simple docstring"""


       a		  =      BasicTokenizer(do_lower_case=__UpperCAmelCase  )

       self.assertListEqual(
           tokenizer.tokenize(''' \tHeLLo!how  \n Are yoU?  '''  ) ,					['''HeLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?''']  )







      def       __lowerCAmelCase					(      self      :						Tuple  )    ->Tuple:




       """simple docstring"""


       a		  =      BasicTokenizer(do_lower_case=__UpperCAmelCase ,					strip_accents=__UpperCAmelCase  )

       self.assertListEqual(
           tokenizer.tokenize(''' \tHäLLo!how  \n Are yoU?  '''  ) ,					['''HäLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?''']  )







      def       __lowerCAmelCase					(      self      :						int  )    ->Optional[int]:




       """simple docstring"""


       a		  =      BasicTokenizer(do_lower_case=__UpperCAmelCase ,					strip_accents=__UpperCAmelCase  )

       self.assertListEqual(
           tokenizer.tokenize(''' \tHäLLo!how  \n Are yoU?  '''  ) ,					['''HaLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?''']  )







      def       __lowerCAmelCase					(      self      :						Any  )    ->int:




       """simple docstring"""


       a		  =      BasicTokenizer(do_lower_case=__UpperCAmelCase ,					never_split=['''[UNK]''']  )

       self.assertListEqual(
           tokenizer.tokenize(''' \tHeLLo!how  \n Are yoU? [UNK]'''  ) ,					['''HeLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?''', '''[UNK]''']  )







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




       """simple docstring"""


       a		  =      ['''[UNK]''', '''[CLS]''', '''[SEP]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''']

       a		  =      {}
       for i, token in enumerate(__UpperCAmelCase  ):
        a		  =      i
       a		  =      WordpieceTokenizer(vocab=__UpperCAmelCase ,					unk_token='''[UNK]'''  )

       self.assertListEqual(tokenizer.tokenize(''''''  ) ,					[]  )

       self.assertListEqual(tokenizer.tokenize('''unwanted running'''  ) ,					['''un''', '''##want''', '''##ed''', '''runn''', '''##ing''']  )

       self.assertListEqual(tokenizer.tokenize('''unwantedX running'''  ) ,					['''[UNK]''', '''runn''', '''##ing''']  )







      @require_torch
      def       __lowerCAmelCase					(      self      :						int  )    ->int:




       """simple docstring"""


       a		  =      self.tokenizer_class.from_pretrained('''microsoft/prophetnet-large-uncased'''  )

       a		  =      ['''A long paragraph for summarization.''', '''Another paragraph for summarization.''']
       a		  =      [1_037, 2_146, 20_423, 2_005, 7_680, 7_849, 3_989, 1_012, 102]
       a		  =      tokenizer(__UpperCAmelCase ,					padding=__UpperCAmelCase ,					return_tensors='''pt'''  )
       self.assertIsInstance(__UpperCAmelCase ,					__UpperCAmelCase  )
       a		  =      list(batch.input_ids.numpy()[0]  )
       self.assertListEqual(__UpperCAmelCase ,					__UpperCAmelCase  )

       self.assertEqual((2, 9) ,					batch.input_ids.shape  )
       self.assertEqual((2, 9) ,					batch.attention_mask.shape  )







      def       __lowerCAmelCase					(      self      :						Optional[Any]  )    ->List[str]:




       """simple docstring"""


       self.assertTrue(_is_whitespace(''' '''  )  )
       self.assertTrue(_is_whitespace('''\t'''  )  )
       self.assertTrue(_is_whitespace('''\r'''  )  )
       self.assertTrue(_is_whitespace('''\n'''  )  )
       self.assertTrue(_is_whitespace('''\u00A0'''  )  )

       self.assertFalse(_is_whitespace('''A'''  )  )
       self.assertFalse(_is_whitespace('''-'''  )  )







      def       __lowerCAmelCase					(      self      :						Any  )    ->List[str]:




       """simple docstring"""


       self.assertTrue(_is_control('''\u0005'''  )  )

       self.assertFalse(_is_control('''A'''  )  )
       self.assertFalse(_is_control(''' '''  )  )
       self.assertFalse(_is_control('''\t'''  )  )
       self.assertFalse(_is_control('''\r'''  )  )







      def       __lowerCAmelCase					(      self      :						List[Any]  )    ->List[str]:




       """simple docstring"""


       self.assertTrue(_is_punctuation('''-'''  )  )
       self.assertTrue(_is_punctuation('''$'''  )  )
       self.assertTrue(_is_punctuation('''`'''  )  )
       self.assertTrue(_is_punctuation('''.'''  )  )

       self.assertFalse(_is_punctuation('''A'''  )  )
       self.assertFalse(_is_punctuation(''' '''  )  )







      @slow
      def       __lowerCAmelCase					(      self      :						List[str]  )    ->List[str]:




       """simple docstring"""


       a		  =      self.tokenizer_class.from_pretrained('''microsoft/prophetnet-large-uncased'''  )

       a		  =      tokenizer.encode('''sequence builders''' ,					add_special_tokens=__UpperCAmelCase  )
       a		  =      tokenizer.encode('''multi-sequence build''' ,					add_special_tokens=__UpperCAmelCase  )

       a		  =      tokenizer.build_inputs_with_special_tokens(__UpperCAmelCase  )
       a		  =      tokenizer.build_inputs_with_special_tokens(__UpperCAmelCase ,					__UpperCAmelCase  )

       assert encoded_sentence == text + [102]
       assert encoded_pair == text + [102] + text_a + [102]


