


import os
import re
import shutil
import sys
import tempfile
import unittest

import black


SCREAMING_SNAKE_CASE			: List[Any]				   =					os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
sys.path.append(os.path.join(git_repo_path, "utils"))

import check_copies  # noqa: E402


# This is the reference code that will be used in the tests.
# If BertLMPredictionHead is changed in modeling_bert.py, this code needs to be manually updated.
SCREAMING_SNAKE_CASE			: Optional[Any]				   =					"    def __init__(self, config):\n        super().__init__()\n        self.transform = BertPredictionHeadTransform(config)\n\n        # The output weights are the same as the input embeddings, but there is\n        # an output-only bias for each token.\n        self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=False)\n\n        self.bias = nn.Parameter(torch.zeros(config.vocab_size))\n\n        # Need a link between the two variables so that the bias is correctly resized with `resize_token_embeddings`\n        self.decoder.bias = self.bias\n\n    def forward(self, hidden_states):\n        hidden_states = self.transform(hidden_states)\n        hidden_states = self.decoder(hidden_states)\n        return hidden_states\n"






class _lowerCamelCase(		unittest.TestCase  ):
       def      UpperCamelCase	(   self)			->  str:




           """simple docstring"""

           _lowercase			:				Optional[Any] 						=						tempfile.mkdtemp()
           os.makedirs(os.path.join(self.transformer_dir, 'models/bert/'))
           _lowercase			:				List[Any] 						=						self.transformer_dir
           shutil.copy(
               os.path.join(lowerCamelCase, 'src/transformers/models/bert/modeling_bert.py'), os.path.join(self.transformer_dir, 'models/bert/modeling_bert.py'), )
       def      UpperCamelCase	(   self)			->  Any:




           """simple docstring"""

           _lowercase			:				Optional[Any] 						=						'src/transformers'
           shutil.rmtree(self.transformer_dir)
       def      UpperCamelCase	(   self, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase=None)			->  str:




           """simple docstring"""

           _lowercase			:				Optional[Any] 						=						comment + F'''\nclass {class_name}(nn.Module):\n''' + class_code
           if overwrite_result is not None:
               _lowercase			:				Optional[int] 						=						comment + F'''\nclass {class_name}(nn.Module):\n''' + overwrite_result
           _lowercase			:				Dict 						=						black.Mode(target_versions={black.TargetVersion.PYaa}, line_length=1_19)
           _lowercase			:				Union[str, Any] 						=						black.format_str(lowerCamelCase, mode=lowerCamelCase)
           _lowercase			:				Optional[int] 						=						os.path.join(self.transformer_dir, 'new_code.py')
           with open(lowerCamelCase, 'w', newline='\n') as f:
               f.write(lowerCamelCase)
           if overwrite_result is None:
               self.assertTrue(len(check_copies.is_copy_consistent(lowerCamelCase)) == 0)
           else:
               check_copies.is_copy_consistent(f.name, overwrite=lowerCamelCase)
               with open(lowerCamelCase, 'r') as f:
                   self.assertTrue(f.read(), lowerCamelCase)
       def      UpperCamelCase	(   self)			->  Dict:




           """simple docstring"""

           _lowercase			:				Tuple 						=						check_copies.find_code_in_transformers('models.bert.modeling_bert.BertLMPredictionHead')
           self.assertEqual(lowerCamelCase, lowerCamelCase)
       def      UpperCamelCase	(   self)			->  Optional[Any]:




           """simple docstring"""

           self.check_copy_consistency(
               '# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead', 'BertLMPredictionHead', REFERENCE_CODE + '\n', )

           # With no empty line at the end
           self.check_copy_consistency(
               '# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead', 'BertLMPredictionHead', lowerCamelCase, )

           # Copy consistency with rename
           self.check_copy_consistency(
               '# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead with Bert->TestModel', 'TestModelLMPredictionHead', re.sub('Bert', 'TestModel', lowerCamelCase), )

           # Copy consistency with a really long name
           _lowercase			:				Tuple 						=						'TestModelWithAReallyLongNameBecauseSomePeopleLikeThatForSomeReason'
           self.check_copy_consistency(
               F'''# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead with Bert->{long_class_name}''', F'''{long_class_name}LMPredictionHead''', re.sub('Bert', lowerCamelCase, lowerCamelCase), )

           # Copy consistency with overwrite
           self.check_copy_consistency(
               '# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead with Bert->TestModel', 'TestModelLMPredictionHead', lowerCamelCase, overwrite_result=re.sub('Bert', 'TestModel', lowerCamelCase), )




       def      UpperCamelCase	(   self)			->  Any:




           """simple docstring"""

           _lowercase			:				Tuple 						=						check_copies.LOCALIZED_READMES['README_zh-hans.md']

           _lowercase			:				List[Any] 						=						(
               '1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (from Google Research and the'
               ' Toyota Technological Institute at Chicago) released with the paper [ALBERT: A Lite BERT for'
               ' Self-supervised Learning of Language Representations](https://arxiv.org/abs/1909.11942), by Zhenzhong'
               ' Lan, Mingda Chen, Sebastian Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut.\n1.'
               ' **[DistilBERT](https://huggingface.co/transformers/model_doc/distilbert.html)** (from HuggingFace),'
               ' released together with the paper [DistilBERT, a distilled version of BERT: smaller, faster, cheaper and'
               ' lighter](https://arxiv.org/abs/1910.01108) by Victor Sanh, Lysandre Debut and Thomas Wolf. The same'
               ' method has been applied to compress GPT2 into'
               ' [DistilGPT2](https://github.com/huggingface/transformers/tree/main/examples/distillation), RoBERTa into'
               ' [DistilRoBERTa](https://github.com/huggingface/transformers/tree/main/examples/distillation),'
               ' Multilingual BERT into'
               ' [DistilmBERT](https://github.com/huggingface/transformers/tree/main/examples/distillation) and a German'
               ' version of DistilBERT.\n1. **[ELECTRA](https://huggingface.co/transformers/model_doc/electra.html)**'
               ' (from Google Research/Stanford University) released with the paper [ELECTRA: Pre-training text encoders'
               ' as discriminators rather than generators](https://arxiv.org/abs/2003.10555) by Kevin Clark, Minh-Thang'
               ' Luong, Quoc V. Le, Christopher D. Manning.'
           )
           _lowercase			:				Tuple 						=						(
               '1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (来自 Google Research and the'
               ' Toyota Technological Institute at Chicago) 伴随论文 [ALBERT: A Lite BERT for Self-supervised Learning of'
               ' Language Representations](https://arxiv.org/abs/1909.11942), 由 Zhenzhong Lan, Mingda Chen, Sebastian'
               ' Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut 发布。\n'
           )
           _lowercase			:				List[Any] 						=						(
               '1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (来自 Google Research and the'
               ' Toyota Technological Institute at Chicago) 伴随论文 [ALBERT: A Lite BERT for Self-supervised Learning of'
               ' Language Representations](https://arxiv.org/abs/1909.11942), 由 Zhenzhong Lan, Mingda Chen, Sebastian'
               ' Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut 发布。\n1.'
               ' **[DistilBERT](https://huggingface.co/transformers/model_doc/distilbert.html)** (来自 HuggingFace) 伴随论文'
               ' [DistilBERT, a distilled version of BERT: smaller, faster, cheaper and'
               ' lighter](https://arxiv.org/abs/1910.01108) 由 Victor Sanh, Lysandre Debut and Thomas Wolf 发布。 The same'
               ' method has been applied to compress GPT2 into'
               ' [DistilGPT2](https://github.com/huggingface/transformers/tree/main/examples/distillation), RoBERTa into'
               ' [DistilRoBERTa](https://github.com/huggingface/transformers/tree/main/examples/distillation),'
               ' Multilingual BERT into'
               ' [DistilmBERT](https://github.com/huggingface/transformers/tree/main/examples/distillation) and a German'
               ' version of DistilBERT.\n1. **[ELECTRA](https://huggingface.co/transformers/model_doc/electra.html)** (来自'
               ' Google Research/Stanford University) 伴随论文 [ELECTRA: Pre-training text encoders as discriminators rather'
               ' than generators](https://arxiv.org/abs/2003.10555) 由 Kevin Clark, Minh-Thang Luong, Quoc V. Le,'
               ' Christopher D. Manning 发布。\n'
           )

           _lowercase						,							_lowercase			:				List[Any] 						=						check_copies.convert_to_localized_md(
               lowerCamelCase, lowerCamelCase, localized_readme['format_model_list'])

           self.assertFalse(lowerCamelCase)
           self.assertEqual(lowerCamelCase, lowerCamelCase)

           _lowercase						,							_lowercase			:				List[str] 						=						check_copies.convert_to_localized_md(
               lowerCamelCase, lowerCamelCase, localized_readme['format_model_list'])

           # Check whether the number of models is equal to README.md after conversion.
           self.assertTrue(lowerCamelCase)

           _lowercase			:				Union[str, Any] 						=						(
               '1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (from Google Research and the'
               ' Toyota Technological Institute at Chicago) released with the paper [ALBERT: A Lite BERT for'
               ' Self-supervised Learning of Language Representations](https://arxiv.org/abs/1909.11942), by Zhenzhong'
               ' Lan, Mingda Chen, Sebastian Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut.'
           )
           _lowercase			:				Tuple 						=						(
               '1. **[ALBERT](https://huggingface.co/transformers/main/model_doc/albert.html)** (来自 Google Research and'
               ' the Toyota Technological Institute at Chicago) 伴随论文 [ALBERT: A Lite BERT for Self-supervised Learning of'
               ' Language Representations](https://arxiv.org/abs/1909.11942), 由 Zhenzhong Lan, Mingda Chen, Sebastian'
               ' Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut 发布。\n'
           )
           _lowercase			:				Optional[int] 						=						(
               '1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (来自 Google Research and the'
               ' Toyota Technological Institute at Chicago) 伴随论文 [ALBERT: A Lite BERT for Self-supervised Learning of'
               ' Language Representations](https://arxiv.org/abs/1909.11942), 由 Zhenzhong Lan, Mingda Chen, Sebastian'
               ' Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut 发布。\n'
           )

           _lowercase						,							_lowercase			:				Dict 						=						check_copies.convert_to_localized_md(
               lowerCamelCase, lowerCamelCase, localized_readme['format_model_list'])

           # Check if the model link is synchronized.
           self.assertEqual(lowerCamelCase, lowerCamelCase)







'''simple docstring'''

import json
from typing import List, Optional, Tuple

from tokenizers import pre_tokenizers, processors

from ...tokenization_utils_base import AddedToken, BatchEncoding
from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import logging
from .tokenization_bart import BartTokenizer


SCREAMING_SNAKE_CASE__     :						List[str]	=  logging.get_logger(__name__)


SCREAMING_SNAKE_CASE__     :						Optional[Any]	=  {'''vocab_file''': '''vocab.json''', '''merges_file''': '''merges.txt''', '''tokenizer_file''': '''tokenizer.json'''}

# See all BART models at https://huggingface.co/models?filter=bart
SCREAMING_SNAKE_CASE__     :						Dict	=  {
    '''vocab_file''': {
        '''facebook/bart-base''': '''https://huggingface.co/facebook/bart-base/resolve/main/vocab.json''',
        '''facebook/bart-large''': '''https://huggingface.co/facebook/bart-large/resolve/main/vocab.json''',
        '''facebook/bart-large-mnli''': '''https://huggingface.co/facebook/bart-large-mnli/resolve/main/vocab.json''',
        '''facebook/bart-large-cnn''': '''https://huggingface.co/facebook/bart-large-cnn/resolve/main/vocab.json''',
        '''facebook/bart-large-xsum''': '''https://huggingface.co/facebook/bart-large-xsum/resolve/main/vocab.json''',
        '''yjernite/bart_eli5''': '''https://huggingface.co/yjernite/bart_eli5/resolve/main/vocab.json''',
    },
    '''merges_file''': {
        '''facebook/bart-base''': '''https://huggingface.co/facebook/bart-base/resolve/main/merges.txt''',
        '''facebook/bart-large''': '''https://huggingface.co/facebook/bart-large/resolve/main/merges.txt''',
        '''facebook/bart-large-mnli''': '''https://huggingface.co/facebook/bart-large-mnli/resolve/main/merges.txt''',
        '''facebook/bart-large-cnn''': '''https://huggingface.co/facebook/bart-large-cnn/resolve/main/merges.txt''',
        '''facebook/bart-large-xsum''': '''https://huggingface.co/facebook/bart-large-xsum/resolve/main/merges.txt''',
        '''yjernite/bart_eli5''': '''https://huggingface.co/yjernite/bart_eli5/resolve/main/merges.txt''',
    },
    '''tokenizer_file''': {
        '''facebook/bart-base''': '''https://huggingface.co/facebook/bart-base/resolve/main/tokenizer.json''',
        '''facebook/bart-large''': '''https://huggingface.co/facebook/bart-large/resolve/main/tokenizer.json''',
        '''facebook/bart-large-mnli''': '''https://huggingface.co/facebook/bart-large-mnli/resolve/main/tokenizer.json''',
        '''facebook/bart-large-cnn''': '''https://huggingface.co/facebook/bart-large-cnn/resolve/main/tokenizer.json''',
        '''facebook/bart-large-xsum''': '''https://huggingface.co/facebook/bart-large-xsum/resolve/main/tokenizer.json''',
        '''yjernite/bart_eli5''': '''https://huggingface.co/yjernite/bart_eli5/resolve/main/tokenizer.json''',
    },
}

SCREAMING_SNAKE_CASE__     :						Optional[int]	=  {
    '''facebook/bart-base''': 1_0_2_4,
    '''facebook/bart-large''': 1_0_2_4,
    '''facebook/bart-large-mnli''': 1_0_2_4,
    '''facebook/bart-large-cnn''': 1_0_2_4,
    '''facebook/bart-large-xsum''': 1_0_2_4,
    '''yjernite/bart_eli5''': 1_0_2_4,
}

class 							a__( snake_case__     ):
			a_	: Dict									=      VOCAB_FILES_NAMES
			a_	: Tuple									=      PRETRAINED_VOCAB_FILES_MAP
			a_	: Tuple									=      PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
			a_	: List[Any]									=      ['''input_ids''', '''attention_mask''']
			a_	: Union[str, Any]									=      BartTokenizer






			def __init__(     self					,   _UpperCAmelCase=None					,   _UpperCAmelCase=None					,   _UpperCAmelCase=None					,   _UpperCAmelCase="replace"					,   _UpperCAmelCase="<s>"					,   _UpperCAmelCase="</s>"					,   _UpperCAmelCase="</s>"					,   _UpperCAmelCase="<s>"					,   _UpperCAmelCase="<unk>"					,   _UpperCAmelCase="<pad>"					,   _UpperCAmelCase="<mask>"					,   _UpperCAmelCase=False					,   _UpperCAmelCase=True					,   **_UpperCAmelCase					,   )							->							int:
					super().__init__(
					    _UpperCAmelCase					,   _UpperCAmelCase					,   tokenizer_file=_UpperCAmelCase					,   errors=_UpperCAmelCase					,   bos_token=_UpperCAmelCase					,   eos_token=_UpperCAmelCase					,   sep_token=_UpperCAmelCase					,   cls_token=_UpperCAmelCase					,   unk_token=_UpperCAmelCase					,   pad_token=_UpperCAmelCase					,   mask_token=_UpperCAmelCase					,   add_prefix_space=_UpperCAmelCase					,   trim_offsets=_UpperCAmelCase					,   **_UpperCAmelCase					,   )

					snake_case__	     =json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__()						)
					if pre_tok_state.get('add_prefix_space'					,   _UpperCAmelCase						) != add_prefix_space:
							snake_case__	     =getattr(_UpperCAmelCase					,   pre_tok_state.pop('type'						)						)
							snake_case__	     =add_prefix_space
							snake_case__	     =pre_tok_class(**_UpperCAmelCase						)

					snake_case__	     =add_prefix_space

					# the pre_tokenizer is already updated in the GPT2TokenizerFast `__init__`
					snake_case__	     ='post_processor'
					snake_case__	     =getattr(self.backend_tokenizer					,   _UpperCAmelCase					,   _UpperCAmelCase						)
					if tokenizer_component_instance:
							snake_case__	     =json.loads(tokenizer_component_instance.__getstate__()						)

							# The lists 'sep' and 'cls' must be cased in tuples for the object `post_processor_class`
							if "sep" in state:
									snake_case__	     =tuple(state['sep']						)
							if "cls" in state:
									snake_case__	     =tuple(state['cls']						)

							snake_case__	     =False

							if state.get('add_prefix_space'					,   _UpperCAmelCase						) != add_prefix_space:
									snake_case__	     =add_prefix_space
									snake_case__	     =True

							if state.get('trim_offsets'					,   _UpperCAmelCase						) != trim_offsets:
									snake_case__	     =trim_offsets
									snake_case__	     =True

							if changes_to_apply:
									snake_case__	     =getattr(_UpperCAmelCase					,   state.pop('type'						)						)
									snake_case__	     =component_class(**_UpperCAmelCase						)
									setattr(self.backend_tokenizer					,   _UpperCAmelCase					,   _UpperCAmelCase						)






			@property
			def 						_lowercase  (     self						)							->							str:
					if self._mask_token is None:
							if self.verbose:
									logger.error('Using mask_token, but it is not set yet.'						)
							return None
					return str(self._mask_token						)






			@mask_token.setter
			def 						_lowercase  (     self					,   _UpperCAmelCase						)							->							int:
					snake_case__	     =AddedToken(_UpperCAmelCase					,   lstrip=_UpperCAmelCase					,   rstrip=_UpperCAmelCase						) if isinstance(_UpperCAmelCase					,   _UpperCAmelCase						) else value
					snake_case__	     =value






			def 						_lowercase  (     self					,   *_UpperCAmelCase					,   **_UpperCAmelCase						)							->							BatchEncoding:
					snake_case__	     =kwargs.get('is_split_into_words'					,   _UpperCAmelCase						)

					if is_split_into_words and not self.add_prefix_space:
							raise ValueError(
							    f"""You need to instantiate {self.__class__.__name__} with add_prefix_space=True """
							    'to use it with pretokenized inputs.'						)

					return super()._batch_encode_plus(*_UpperCAmelCase					,   **_UpperCAmelCase						)






			def 						_lowercase  (     self					,   *_UpperCAmelCase					,   **_UpperCAmelCase						)							->							BatchEncoding:
					snake_case__	     =kwargs.get('is_split_into_words'					,   _UpperCAmelCase						)

					if is_split_into_words and not self.add_prefix_space:
							raise ValueError(
							    f"""You need to instantiate {self.__class__.__name__} with add_prefix_space=True """
							    'to use it with pretokenized inputs.'						)

					return super()._encode_plus(*_UpperCAmelCase					,   **_UpperCAmelCase						)






			def 						_lowercase  (     self					,   _UpperCAmelCase					,   _UpperCAmelCase = None						)							->							Tuple[str]:
					snake_case__	     =self._tokenizer.model.save(_UpperCAmelCase					,   name=_UpperCAmelCase						)
					return tuple(_UpperCAmelCase						)






			def 						_lowercase  (     self					,   _UpperCAmelCase					,   _UpperCAmelCase=None						)							->							Optional[int]:
					snake_case__	     =[self.bos_token_id] + token_ids_a + [self.eos_token_id]
					if token_ids_a is None:
							return output

					return output + [self.eos_token_id] + token_ids_a + [self.eos_token_id]






			def 						_lowercase  (     self					,   _UpperCAmelCase					,   _UpperCAmelCase = None						)							->							List[int]:
					snake_case__	     =[self.sep_token_id]
					snake_case__	     =[self.cls_token_id]

					if token_ids_a is None:
							return len(cls + token_ids_a + sep						) * [0]
					return len(cls + token_ids_a + sep + sep + token_ids_a + sep						) * [0]




