
import os
import sys
import tempfile
import unittest
import unittest.mock as mock
from pathlib import Path

from huggingface_hub import HfFolder, delete_repo
from huggingface_hub.file_download import http_get
from requests.exceptions import HTTPError

from transformers import (
    AlbertTokenizer,
    AutoTokenizer,
    BertTokenizer,
    BertTokenizerFast,
    GPTaTokenizerFast,
    is_tokenizers_available,
)
from transformers.testing_utils import TOKEN, USER, is_staging_test, require_tokenizers
from transformers.tokenization_utils import Trie


sys.path.append(str(Path(__file__).parent.parent / """utils"""))

from test_module.custom_tokenization import CustomTokenizer  # noqa E402


if is_tokenizers_available():
     from test_module.custom_tokenization_fast import CustomTokenizerFast



class    _snake_case (						unittest.TestCase				):


 def   lowercase__  (       self):


   '''simple docstring'''




   lowercase__	: Dict     		=   mock.Mock()
   lowercase__	: Union[str, Any]     		=   5_00
   lowercase__	: List[str]     		=   {}
   lowercase__	: Optional[Any]     		=   HTTPError
   lowercase__	: Tuple     		=   {}

   # Download this model to make sure it's in the cache.
   lowercase__	: int     		=   BertTokenizer.from_pretrained("""hf-internal-testing/tiny-random-bert""")

   # Under the mock environment we get a 500 error when trying to reach the tokenizer.
   with mock.patch("""requests.Session.request"""       ,	return_value=_lowerCamelCase) as mock_head:
     lowercase__	: int     		=   BertTokenizer.from_pretrained("""hf-internal-testing/tiny-random-bert""")
     # This check we did call the fake head request
     mock_head.assert_called()


 @require_tokenizers
 def   lowercase__  (       self):


   '''simple docstring'''




   lowercase__	: List[str]     		=   mock.Mock()
   lowercase__	: Optional[int]     		=   5_00
   lowercase__	: Any     		=   {}
   lowercase__	: Any     		=   HTTPError
   lowercase__	: str     		=   {}

   # Download this model to make sure it's in the cache.
   lowercase__	: int     		=   GPTaTokenizerFast.from_pretrained("""gpt2""")

   # Under the mock environment we get a 500 error when trying to reach the tokenizer.
   with mock.patch("""requests.Session.request"""       ,	return_value=_lowerCamelCase) as mock_head:
     lowercase__	: str     		=   GPTaTokenizerFast.from_pretrained("""gpt2""")
     # This check we did call the fake head request
     mock_head.assert_called()


 def   lowercase__  (       self):


   '''simple docstring'''




   try:
     lowercase__	: Any     		=   tempfile.mktemp()
     with open(_lowerCamelCase       ,	"""wb""") as f:
       http_get("""https://huggingface.co/albert-base-v1/resolve/main/spiece.model"""       ,	_lowerCamelCase)

     lowercase__	: Optional[Any]     		=   AlbertTokenizer.from_pretrained(_lowerCamelCase)
   finally:
     os.remove(_lowerCamelCase)

   # Supporting this legacy load introduced a weird bug where the tokenizer would load local files if they are in
   # the current folder and have the right name.
   if os.path.isfile("""tokenizer.json"""):
     # We skip the test if the user has a `tokenizer.json` in this folder to avoid deleting it.
     return
   try:
     with open("""tokenizer.json"""       ,	"""wb""") as f:
       http_get("""https://huggingface.co/hf-internal-testing/tiny-random-bert/blob/main/tokenizer.json"""       ,	_lowerCamelCase)
     lowercase__	: List[Any]     		=   AutoTokenizer.from_pretrained("""hf-internal-testing/tiny-random-gpt2""")
     # The tiny random BERT has a vocab size of 1024, tiny gpt2 as a vocab size of 1000
     self.assertEqual(tokenizer.vocab_size       ,	10_00)
     # Tokenizer should depend on the remote checkpoint, not the local tokenizer.json file.

   finally:
     os.remove("""tokenizer.json""")



 def   lowercase__  (       self):


   '''simple docstring'''




   lowercase__	: List[str]     		=   AlbertTokenizer.from_pretrained("""https://huggingface.co/albert-base-v1/resolve/main/spiece.model""")



@is_staging_test
class    _snake_case (						unittest.TestCase				):
 __lowerCAmelCase	:  str	   =      ['[UNK]', '[CLS]', '[SEP]', '[PAD]', '[MASK]', 'bla', 'blou']


 @classmethod
 def   lowercase__  (       cls):


   '''simple docstring'''




   lowercase__	: List[str]     		=   TOKEN
   HfFolder.save_token(_lowerCamelCase)


 @classmethod
 def   lowercase__  (       cls):


   '''simple docstring'''




   try:
     delete_repo(token=cls._token       ,	repo_id="""test-tokenizer""")
   except HTTPError:
     pass

   try:
     delete_repo(token=cls._token       ,	repo_id="""valid_org/test-tokenizer-org""")
   except HTTPError:
     pass

   try:
     delete_repo(token=cls._token       ,	repo_id="""test-dynamic-tokenizer""")
   except HTTPError:
     pass


 def   lowercase__  (       self):


   '''simple docstring'''




   with tempfile.TemporaryDirectory() as tmp_dir:
     lowercase__	: Optional[int]     		=   os.path.join(_lowerCamelCase       ,	"""vocab.txt""")
     with open(_lowerCamelCase       ,	"""w"""       ,	encoding="""utf-8""") as vocab_writer:
       vocab_writer.write("""""".join([x + """\n""" for x in self.vocab_tokens]))
     lowercase__	: Optional[int]     		=   BertTokenizer(_lowerCamelCase)

   tokenizer.push_to_hub("""test-tokenizer"""       ,	use_auth_token=self._token)
   lowercase__	: List[Any]     		=   BertTokenizer.from_pretrained(f'{USER}/test-tokenizer')
   self.assertDictEqual(new_tokenizer.vocab       ,	tokenizer.vocab)

   # Reset repo
   delete_repo(token=self._token       ,	repo_id="""test-tokenizer""")

   # Push to hub via save_pretrained
   with tempfile.TemporaryDirectory() as tmp_dir:
     tokenizer.save_pretrained(_lowerCamelCase       ,	repo_id="""test-tokenizer"""       ,	push_to_hub=_lowerCamelCase       ,	use_auth_token=self._token)

   lowercase__	: List[str]     		=   BertTokenizer.from_pretrained(f'{USER}/test-tokenizer')
   self.assertDictEqual(new_tokenizer.vocab       ,	tokenizer.vocab)


 def   lowercase__  (       self):


   '''simple docstring'''




   with tempfile.TemporaryDirectory() as tmp_dir:
     lowercase__	: int     		=   os.path.join(_lowerCamelCase       ,	"""vocab.txt""")
     with open(_lowerCamelCase       ,	"""w"""       ,	encoding="""utf-8""") as vocab_writer:
       vocab_writer.write("""""".join([x + """\n""" for x in self.vocab_tokens]))
     lowercase__	: Optional[int]     		=   BertTokenizer(_lowerCamelCase)

   tokenizer.push_to_hub("""valid_org/test-tokenizer-org"""       ,	use_auth_token=self._token)
   lowercase__	: Any     		=   BertTokenizer.from_pretrained("""valid_org/test-tokenizer-org""")
   self.assertDictEqual(new_tokenizer.vocab       ,	tokenizer.vocab)

   # Reset repo
   delete_repo(token=self._token       ,	repo_id="""valid_org/test-tokenizer-org""")

   # Push to hub via save_pretrained
   with tempfile.TemporaryDirectory() as tmp_dir:
     tokenizer.save_pretrained(
         _lowerCamelCase       ,	repo_id="""valid_org/test-tokenizer-org"""       ,	push_to_hub=_lowerCamelCase       ,	use_auth_token=self._token)

   lowercase__	: int     		=   BertTokenizer.from_pretrained("""valid_org/test-tokenizer-org""")
   self.assertDictEqual(new_tokenizer.vocab       ,	tokenizer.vocab)



 @require_tokenizers
 def   lowercase__  (       self):


   '''simple docstring'''




   CustomTokenizer.register_for_auto_class()
   with tempfile.TemporaryDirectory() as tmp_dir:
     lowercase__	: int     		=   os.path.join(_lowerCamelCase       ,	"""vocab.txt""")
     with open(_lowerCamelCase       ,	"""w"""       ,	encoding="""utf-8""") as vocab_writer:
       vocab_writer.write("""""".join([x + """\n""" for x in self.vocab_tokens]))
     lowercase__	: Optional[Any]     		=   CustomTokenizer(_lowerCamelCase)

   # No fast custom tokenizer
   tokenizer.push_to_hub("""test-dynamic-tokenizer"""       ,	use_auth_token=self._token)

   lowercase__	: List[Any]     		=   AutoTokenizer.from_pretrained(f'{USER}/test-dynamic-tokenizer'       ,	trust_remote_code=_lowerCamelCase)
   # Can't make an isinstance check because the new_model.config is from the CustomTokenizer class of a dynamic module
   self.assertEqual(tokenizer.__class__.__name__       ,	"""CustomTokenizer""")

   # Fast and slow custom tokenizer
   CustomTokenizerFast.register_for_auto_class()
   with tempfile.TemporaryDirectory() as tmp_dir:
     lowercase__	: int     		=   os.path.join(_lowerCamelCase       ,	"""vocab.txt""")
     with open(_lowerCamelCase       ,	"""w"""       ,	encoding="""utf-8""") as vocab_writer:
       vocab_writer.write("""""".join([x + """\n""" for x in self.vocab_tokens]))

     lowercase__	: Union[str, Any]     		=   BertTokenizerFast.from_pretrained(_lowerCamelCase)
     bert_tokenizer.save_pretrained(_lowerCamelCase)
     lowercase__	: Dict     		=   CustomTokenizerFast.from_pretrained(_lowerCamelCase)

   tokenizer.push_to_hub("""test-dynamic-tokenizer"""       ,	use_auth_token=self._token)

   lowercase__	: Union[str, Any]     		=   AutoTokenizer.from_pretrained(f'{USER}/test-dynamic-tokenizer'       ,	trust_remote_code=_lowerCamelCase)
   # Can't make an isinstance check because the new_model.config is from the FakeConfig class of a dynamic module
   self.assertEqual(tokenizer.__class__.__name__       ,	"""CustomTokenizerFast""")
   lowercase__	: Tuple     		=   AutoTokenizer.from_pretrained(
       f'{USER}/test-dynamic-tokenizer'       ,	use_fast=_lowerCamelCase       ,	trust_remote_code=_lowerCamelCase)
   # Can't make an isinstance check because the new_model.config is from the FakeConfig class of a dynamic module
   self.assertEqual(tokenizer.__class__.__name__       ,	"""CustomTokenizer""")



class    _snake_case (						unittest.TestCase				):


 def   lowercase__  (       self):


   '''simple docstring'''




   lowercase__	: Optional[int]     		=   Trie()
   trie.add("""Hello 友達""")
   self.assertEqual(trie.data       ,	{"""H""": {"""e""": {"""l""": {"""l""": {"""o""": {""" """: {"""友""": {"""達""": {"""""": 1}}}}}}}}})
   trie.add("""Hello""")
   trie.data
   self.assertEqual(trie.data       ,	{"""H""": {"""e""": {"""l""": {"""l""": {"""o""": {"""""": 1, """ """: {"""友""": {"""達""": {"""""": 1}}}}}}}}})


 def   lowercase__  (       self):


   '''simple docstring'''




   lowercase__	: Optional[int]     		=   Trie()
   self.assertEqual(trie.split("""[CLS] This is a extra_id_100""")       ,	["""[CLS] This is a extra_id_100"""])
   trie.add("""[CLS]""")
   trie.add("""extra_id_1""")
   trie.add("""extra_id_100""")
   self.assertEqual(trie.split("""[CLS] This is a extra_id_100""")       ,	["""[CLS]""", """ This is a """, """extra_id_100"""])


 def   lowercase__  (       self):


   '''simple docstring'''




   lowercase__	: Tuple     		=   Trie()
   trie.add("""A""")
   self.assertEqual(trie.split("""ABC""")       ,	["""A""", """BC"""])
   self.assertEqual(trie.split("""BCA""")       ,	["""BC""", """A"""])


 def   lowercase__  (       self):


   '''simple docstring'''




   lowercase__	: Any     		=   Trie()
   trie.add("""TOKEN]""")
   trie.add("""[SPECIAL_TOKEN]""")
   self.assertEqual(trie.split("""This is something [SPECIAL_TOKEN]""")       ,	["""This is something """, """[SPECIAL_TOKEN]"""])


 def   lowercase__  (       self):


   '''simple docstring'''




   lowercase__	: Optional[Any]     		=   Trie()
   trie.add("""A""")
   trie.add("""P""")
   trie.add("""[SPECIAL_TOKEN]""")
   self.assertEqual(trie.split("""This is something [SPECIAL_TOKEN]""")       ,	["""This is something """, """[SPECIAL_TOKEN]"""])


 def   lowercase__  (       self):


   '''simple docstring'''




   lowercase__	: Any     		=   Trie()
   trie.add("""AB""")
   trie.add("""B""")
   trie.add("""C""")
   self.assertEqual(trie.split("""ABC""")       ,	["""AB""", """C"""])


 def   lowercase__  (       self):


   '''simple docstring'''




   lowercase__	: List[str]     		=   Trie()
   trie.add("""ABC""")
   trie.add("""B""")
   trie.add("""CD""")
   self.assertEqual(trie.split("""ABCD""")       ,	["""ABC""", """D"""])



 def   lowercase__  (       self):


   '''simple docstring'''




   lowercase__	: Any     		=   Trie()
   lowercase__	: List[str]     		=   trie.cut_text("""ABC"""       ,	[0, 0, 2, 1, 2, 3])
   self.assertEqual(_lowerCamelCase       ,	["""AB""", """C"""])









"""simple docstring"""
import warnings
from collections import OrderedDict
from typing import Any, Mapping, Optional

from ... import PreTrainedTokenizer
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig, OnnxConfigWithPast, OnnxSeqaSeqConfigWithPast
from ...onnx.utils import compute_effective_axis_dimension
from ...utils import TensorType, is_torch_available, logging


_A							=  logging.get_logger(__name__)

_A							=  {
    """facebook/bart-large""": """https://huggingface.co/facebook/bart-large/resolve/main/config.json""",
    # See all BART models at https://huggingface.co/models?filter=bart
}

class       lowerCamelCase	(       lowerCAmelCase__   ):


  '''simple docstring'''







  SCREAMING_SNAKE_CASE					      =  'bart'
  SCREAMING_SNAKE_CASE					      =  ['past_key_values']
  SCREAMING_SNAKE_CASE					      =  {'num_attention_heads': 'encoder_attention_heads', 'hidden_size': 'd_model'}



  def __init__(self							,       _lowerCamelCase=50265							,       _lowerCamelCase=1024							,       _lowerCamelCase=12							,       _lowerCamelCase=4096							,       _lowerCamelCase=16							,       _lowerCamelCase=12							,       _lowerCamelCase=4096							,       _lowerCamelCase=16							,       _lowerCamelCase=0.0							,       _lowerCamelCase=0.0							,       _lowerCamelCase="gelu"							,       _lowerCamelCase=1024							,       _lowerCamelCase=0.1							,       _lowerCamelCase=0.0							,       _lowerCamelCase=0.0							,       _lowerCamelCase=0.02							,       _lowerCamelCase=0.0							,       _lowerCamelCase=False							,       _lowerCamelCase=True							,       _lowerCamelCase=3							,       _lowerCamelCase=1							,       _lowerCamelCase=0							,       _lowerCamelCase=2							,       _lowerCamelCase=True							,       _lowerCamelCase=2							,       _lowerCamelCase=2							,       **_lowerCamelCase							,       ):


        """simple docstring"""

        UpperCAmelCase__			:							str							=    vocab_size
        UpperCAmelCase__			:							Optional[Any]							=    max_position_embeddings
        UpperCAmelCase__			:							int							=    d_model
        UpperCAmelCase__			:							str							=    encoder_ffn_dim
        UpperCAmelCase__			:							List[str]							=    encoder_layers
        UpperCAmelCase__			:							Optional[int]							=    encoder_attention_heads
        UpperCAmelCase__			:							Optional[int]							=    decoder_ffn_dim
        UpperCAmelCase__			:							Dict							=    decoder_layers
        UpperCAmelCase__			:							int							=    decoder_attention_heads
        UpperCAmelCase__			:							Optional[Any]							=    dropout
        UpperCAmelCase__			:							int							=    attention_dropout
        UpperCAmelCase__			:							str							=    activation_dropout
        UpperCAmelCase__			:							Optional[int]							=    activation_function
        UpperCAmelCase__			:							List[str]							=    init_std
        UpperCAmelCase__			:							Dict							=    encoder_layerdrop
        UpperCAmelCase__			:							Any							=    decoder_layerdrop
        UpperCAmelCase__			:							List[str]							=    classifier_dropout
        UpperCAmelCase__			:							Any							=    use_cache
        UpperCAmelCase__			:							Union[str, Any]							=    encoder_layers
        UpperCAmelCase__			:							List[Any]							=    scale_embedding  # scale factor will be sqrt(d_model) if True

        super().__init__(
            num_labels=_lowerCamelCase							,       pad_token_id=_lowerCamelCase							,       bos_token_id=_lowerCamelCase							,       eos_token_id=_lowerCamelCase							,       is_encoder_decoder=_lowerCamelCase							,       decoder_start_token_id=_lowerCamelCase							,       forced_eos_token_id=_lowerCamelCase							,       **_lowerCamelCase							,       )

        # ensure backward compatibility for BART CNN models
        if self.forced_bos_token_id is None and kwargs.get("""force_bos_token_to_be_generated"""							,       _lowerCamelCase	):
              UpperCAmelCase__			:							List[Any]							=    self.bos_token_id
              warnings.warn(
                  F"""Please make sure the config includes `forced_bos_token_id={self.bos_token_id}` in future versions. """
                  """The config can simply be saved and uploaded again to be fixed."""	)




class       lowerCamelCase	(       lowerCAmelCase__   ):


  '''simple docstring'''







  @property
  def  _a      (self	):


        """simple docstring"""

        if self.task in ["default", "seq2seq-lm"]:
              UpperCAmelCase__			:							int							=    OrderedDict(
                  [
                      ("""input_ids""", {0: """batch""", 1: """encoder_sequence"""}),
                      ("""attention_mask""", {0: """batch""", 1: """encoder_sequence"""}),
                  ]	)

              if self.use_past:
                    UpperCAmelCase__			:							Dict							=    {0: """batch"""}
                    UpperCAmelCase__			:							Tuple							=    {0: """batch""", 1: """past_decoder_sequence + sequence"""}
              else:
                    UpperCAmelCase__			:							Dict							=    {0: """batch""", 1: """decoder_sequence"""}
                    UpperCAmelCase__			:							List[str]							=    {0: """batch""", 1: """decoder_sequence"""}

              if self.use_past:
                    self.fill_with_past_key_values_(_lowerCamelCase							,       direction="""inputs"""	)
        elif self.task == "causal-lm":
              # TODO: figure this case out.
              UpperCAmelCase__			:							str							=    OrderedDict(
                  [
                      ("""input_ids""", {0: """batch""", 1: """encoder_sequence"""}),
                      ("""attention_mask""", {0: """batch""", 1: """encoder_sequence"""}),
                  ]	)
              if self.use_past:
                    UpperCAmelCase__					,		UpperCAmelCase__			:							List[str]							=    self.num_layers
                    for i in range(_lowerCamelCase	):
                          UpperCAmelCase__			:							Optional[int]							=    {0: """batch""", 2: """past_sequence + sequence"""}
                          UpperCAmelCase__			:							int							=    {0: """batch""", 2: """past_sequence + sequence"""}
        else:
              UpperCAmelCase__			:							Union[str, Any]							=    OrderedDict(
                  [
                      ("""input_ids""", {0: """batch""", 1: """encoder_sequence"""}),
                      ("""attention_mask""", {0: """batch""", 1: """encoder_sequence"""}),
                      ("""decoder_input_ids""", {0: """batch""", 1: """decoder_sequence"""}),
                      ("""decoder_attention_mask""", {0: """batch""", 1: """decoder_sequence"""}),
                  ]	)

        return common_inputs



  @property
  def  _a      (self	):


        """simple docstring"""

        if self.task in ["default", "seq2seq-lm"]:
              UpperCAmelCase__			:							Any							=    super().outputs
        else:
              UpperCAmelCase__			:							Union[str, Any]							=    super(_lowerCamelCase							,       self	).outputs
              if self.use_past:
                    UpperCAmelCase__					,		UpperCAmelCase__			:							Dict							=    self.num_layers
                    for i in range(_lowerCamelCase	):
                          UpperCAmelCase__			:							List[str]							=    {0: """batch""", 2: """past_sequence + sequence"""}
                          UpperCAmelCase__			:							int							=    {0: """batch""", 2: """past_sequence + sequence"""}
        return common_outputs



  def  _a      (self							,       _lowerCamelCase							,       _lowerCamelCase = -1							,       _lowerCamelCase = -1							,       _lowerCamelCase = False							,       _lowerCamelCase = None							,       ):


        """simple docstring"""

        UpperCAmelCase__			:							int							=    self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
            _lowerCamelCase							,       _lowerCamelCase							,       _lowerCamelCase							,       _lowerCamelCase							,       _lowerCamelCase	)

        # Generate decoder inputs
        UpperCAmelCase__			:							int							=    seq_length if not self.use_past else 1
        UpperCAmelCase__			:							str							=    self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
            _lowerCamelCase							,       _lowerCamelCase							,       _lowerCamelCase							,       _lowerCamelCase							,       _lowerCamelCase	)
        UpperCAmelCase__			:							str							=    {F"""decoder_{name}""": tensor for name, tensor in decoder_inputs.items()}
        UpperCAmelCase__			:							Union[str, Any]							=    dict(**_lowerCamelCase							,       **_lowerCamelCase	)

        if self.use_past:
              if not is_torch_available():
                    raise ValueError("""Cannot generate dummy past_keys inputs without PyTorch installed."""	)
              else:
                    import torch
              UpperCAmelCase__					,		UpperCAmelCase__			:							str							=    common_inputs["""input_ids"""].shape
              UpperCAmelCase__			:							int							=    common_inputs["""decoder_input_ids"""].shape[1]
              UpperCAmelCase__					,		UpperCAmelCase__			:							List[str]							=    self.num_attention_heads
              UpperCAmelCase__			:							str							=    (
                  batch,
                  num_encoder_attention_heads,
                  encoder_seq_length,
                  self._config.hidden_size // num_encoder_attention_heads,
              )
              UpperCAmelCase__			:							Optional[int]							=    decoder_seq_length + 3
              UpperCAmelCase__			:							Any							=    (
                  batch,
                  num_decoder_attention_heads,
                  decoder_past_length,
                  self._config.hidden_size // num_decoder_attention_heads,
              )

              UpperCAmelCase__			:							str							=    torch.cat(
                  [common_inputs["""decoder_attention_mask"""], torch.ones(_lowerCamelCase							,       _lowerCamelCase	)]							,       dim=1	)

              UpperCAmelCase__			:							List[str]							=    []
              # If the number of encoder and decoder layers are present in the model configuration, both are considered
              UpperCAmelCase__					,		UpperCAmelCase__			:							Dict							=    self.num_layers
              UpperCAmelCase__			:							Union[str, Any]							=    min(_lowerCamelCase							,       _lowerCamelCase	)
              UpperCAmelCase__			:							str							=    max(_lowerCamelCase							,       _lowerCamelCase	) - min_num_layers
              UpperCAmelCase__			:							Dict							=    """encoder""" if num_encoder_layers > num_decoder_layers else """decoder"""

              for _ in range(_lowerCamelCase	):
                    common_inputs["past_key_values"].append(
                        (
                            torch.zeros(_lowerCamelCase	),
                            torch.zeros(_lowerCamelCase	),
                            torch.zeros(_lowerCamelCase	),
                            torch.zeros(_lowerCamelCase	),
                        )	)
              # TODO: test this.
              UpperCAmelCase__			:							Dict							=    encoder_shape if remaining_side_name == """encoder""" else decoder_shape
              for _ in range(_lowerCamelCase							,       _lowerCamelCase	):
                    common_inputs["past_key_values"].append((torch.zeros(_lowerCamelCase	), torch.zeros(_lowerCamelCase	))	)
        return common_inputs



  def  _a      (self							,       _lowerCamelCase							,       _lowerCamelCase = -1							,       _lowerCamelCase = -1							,       _lowerCamelCase = False							,       _lowerCamelCase = None							,       ):


        """simple docstring"""

        UpperCAmelCase__			:							Any							=    self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
            _lowerCamelCase							,       _lowerCamelCase							,       _lowerCamelCase							,       _lowerCamelCase							,       _lowerCamelCase	)

        if self.use_past:
              if not is_torch_available():
                    raise ValueError("""Cannot generate dummy past_keys inputs without PyTorch installed."""	)
              else:
                    import torch
              UpperCAmelCase__					,		UpperCAmelCase__			:							Optional[int]							=    common_inputs["""input_ids"""].shape
              # Not using the same length for past_key_values
              UpperCAmelCase__			:							int							=    seqlen + 2
              UpperCAmelCase__					,		UpperCAmelCase__			:							Optional[int]							=    self.num_layers
              UpperCAmelCase__					,		UpperCAmelCase__			:							str							=    self.num_attention_heads
              UpperCAmelCase__			:							Tuple							=    (
                  batch,
                  num_encoder_attention_heads,
                  past_key_values_length,
                  self._config.hidden_size // num_encoder_attention_heads,
              )

              UpperCAmelCase__			:							Optional[int]							=    common_inputs["""attention_mask"""].dtype
              UpperCAmelCase__			:							List[str]							=    torch.cat(
                  [common_inputs["""attention_mask"""], torch.ones(_lowerCamelCase							,       _lowerCamelCase							,       dtype=_lowerCamelCase	)]							,       dim=1	)
              UpperCAmelCase__			:							Tuple							=    [
                  (torch.zeros(_lowerCamelCase	), torch.zeros(_lowerCamelCase	)) for _ in range(_lowerCamelCase	)
              ]
        return common_inputs



  def  _a      (self							,       _lowerCamelCase							,       _lowerCamelCase = -1							,       _lowerCamelCase = -1							,       _lowerCamelCase = False							,       _lowerCamelCase = None							,       ):


        """simple docstring"""

        UpperCAmelCase__			:							Tuple							=    compute_effective_axis_dimension(
            _lowerCamelCase							,       fixed_dimension=OnnxConfig.default_fixed_batch							,       num_token_to_add=0	)

        # If dynamic axis (-1) we forward with a fixed dimension of 8 tokens to avoid optimizations made by ONNX
        UpperCAmelCase__			:							Optional[int]							=    tokenizer.num_special_tokens_to_add(_lowerCamelCase	)
        UpperCAmelCase__			:							int							=    compute_effective_axis_dimension(
            _lowerCamelCase							,       fixed_dimension=OnnxConfig.default_fixed_sequence							,       num_token_to_add=_lowerCamelCase	)

        # Generate dummy inputs according to compute batch and sequence
        UpperCAmelCase__			:							List[Any]							=    [""" """.join([tokenizer.unk_token]	) * seq_length] * batch_size
        UpperCAmelCase__			:							Optional[int]							=    dict(tokenizer(_lowerCamelCase							,       return_tensors=_lowerCamelCase	)	)
        return common_inputs



  def  _a      (self							,       _lowerCamelCase							,       _lowerCamelCase = -1							,       _lowerCamelCase = -1							,       _lowerCamelCase = False							,       _lowerCamelCase = None							,       ):


        """simple docstring"""

        if self.task in ["default", "seq2seq-lm"]:
              UpperCAmelCase__			:							Tuple							=    self._generate_dummy_inputs_for_default_and_seqaseq_lm(
                  _lowerCamelCase							,       batch_size=_lowerCamelCase							,       seq_length=_lowerCamelCase							,       is_pair=_lowerCamelCase							,       framework=_lowerCamelCase	)

        elif self.task == "causal-lm":
              UpperCAmelCase__			:							Optional[int]							=    self._generate_dummy_inputs_for_causal_lm(
                  _lowerCamelCase							,       batch_size=_lowerCamelCase							,       seq_length=_lowerCamelCase							,       is_pair=_lowerCamelCase							,       framework=_lowerCamelCase	)
        else:
              UpperCAmelCase__			:							Dict							=    self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
                  _lowerCamelCase							,       batch_size=_lowerCamelCase							,       seq_length=_lowerCamelCase							,       is_pair=_lowerCamelCase							,       framework=_lowerCamelCase	)

        return common_inputs




  def  _a      (self							,       _lowerCamelCase							,       _lowerCamelCase							,       _lowerCamelCase							,       _lowerCamelCase	):


        """simple docstring"""

        if self.task in ["default", "seq2seq-lm"]:
              UpperCAmelCase__			:							Union[str, Any]							=    super()._flatten_past_key_values_(_lowerCamelCase							,       _lowerCamelCase							,       _lowerCamelCase							,       _lowerCamelCase	)
        else:
              UpperCAmelCase__			:							Optional[int]							=    super(_lowerCamelCase							,       self	)._flatten_past_key_values_(
                  _lowerCamelCase							,       _lowerCamelCase							,       _lowerCamelCase							,       _lowerCamelCase	)

