






'''simple docstring'''



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

import black


SCREAMING_SNAKE_CASE							=						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							=						'    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 UpperCAmelCase_       (     unittest.TestCase					):




      """simple docstring"""




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


       '''simple docstring'''

       lowercase       : Dict						=tempfile.mkdtemp()
       os.makedirs(os.path.join(self.transformer_dir  ,   '''models/bert/'''		)		)
       lowercase       : Any						=self.transformer_dir
       shutil.copy(
           os.path.join(UpperCAmelCase  ,   '''src/transformers/models/bert/modeling_bert.py'''		)  ,   os.path.join(self.transformer_dir  ,   '''models/bert/modeling_bert.py'''		)  ,   )






      def 					A__   (			self      :		Any		)	->	str:


       '''simple docstring'''

       lowercase       : Union[str, Any]						='''src/transformers'''
       shutil.rmtree(self.transformer_dir		)






      def 					A__   (			self      :		str  ,   UpperCAmelCase      :		str  ,   UpperCAmelCase      :		Any  ,   UpperCAmelCase      :		List[Any]  ,   UpperCAmelCase      :		Tuple=None		)	->	str:


       '''simple docstring'''

       lowercase       : str						=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       : Any						=black.Mode(target_versions={black.TargetVersion.PYaa}  ,   line_length=119		)
       lowercase       : Optional[int]						=black.format_str(UpperCAmelCase  ,   mode=UpperCAmelCase		)
       lowercase       : Optional[Any]						=os.path.join(self.transformer_dir  ,   '''new_code.py'''		)
       with open(UpperCAmelCase  ,   '''w'''  ,   newline='''\n'''		) as f:
        f.write(UpperCAmelCase		)
       if overwrite_result is None:
        self.assertTrue(len(check_copies.is_copy_consistent(UpperCAmelCase		)		) == 0		)
       else:
        check_copies.is_copy_consistent(f.name  ,   overwrite=UpperCAmelCase		)
        with open(UpperCAmelCase  ,   '''r'''		) as f:
         self.assertTrue(f.read()  ,   UpperCAmelCase		)






      def 					A__   (			self      :		Dict		)	->	List[Any]:


       '''simple docstring'''

       lowercase       : Union[str, Any]						=check_copies.find_code_in_transformers('''models.bert.modeling_bert.BertLMPredictionHead'''		)
       self.assertEqual(UpperCAmelCase  ,   UpperCAmelCase		)






      def 					A__   (			self      :		Optional[int]		)	->	str:


       '''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'''  ,   UpperCAmelCase  ,   )

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

       # Copy consistency with a really long name
       lowercase       : Optional[int]						='''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'''  ,   UpperCAmelCase  ,   UpperCAmelCase		)  ,   )

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






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


       '''simple docstring'''

       lowercase       : Optional[int]						=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       : Optional[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 发布。\n'''
       )
       lowercase       : Union[str, 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       : Union[str, Any]						=check_copies.convert_to_localized_md(
           UpperCAmelCase  ,   UpperCAmelCase  ,   localized_readme['''format_model_list''']		)

       self.assertFalse(UpperCAmelCase		)
       self.assertEqual(UpperCAmelCase  ,   UpperCAmelCase		)

       lowercase	,		lowercase       : int						=check_copies.convert_to_localized_md(
           UpperCAmelCase  ,   UpperCAmelCase  ,   localized_readme['''format_model_list''']		)

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

       lowercase       : str						=(
           '''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       : str						=(
           '''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       : Optional[int]						=check_copies.convert_to_localized_md(
           UpperCAmelCase  ,   UpperCAmelCase  ,   localized_readme['''format_model_list''']		)

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











'''simple docstring'''



import os
from shutil import copyfile
from typing import List, Optional, Tuple

from ...tokenization_utils import AddedToken
from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import is_sentencepiece_available, logging


if is_sentencepiece_available():
      from .tokenization_xlnet import XLNetTokenizer
else:
      SCREAMING_SNAKE_CASE							=						None


SCREAMING_SNAKE_CASE							=						logging.get_logger(__name__)

SCREAMING_SNAKE_CASE							=						{'vocab_file': 'spiece.model', 'tokenizer_file': 'tokenizer.json'}

SCREAMING_SNAKE_CASE							=						{
    'vocab_file': {
        'xlnet-base-cased': 'https://huggingface.co/xlnet-base-cased/resolve/main/spiece.model',
        'xlnet-large-cased': 'https://huggingface.co/xlnet-large-cased/resolve/main/spiece.model',
    },
    'tokenizer_file': {
        'xlnet-base-cased': 'https://huggingface.co/xlnet-base-cased/resolve/main/tokenizer.json',
        'xlnet-large-cased': 'https://huggingface.co/xlnet-large-cased/resolve/main/tokenizer.json',
    },
}

SCREAMING_SNAKE_CASE							=						{
    'xlnet-base-cased': None,
    'xlnet-large-cased': None,
}

SCREAMING_SNAKE_CASE							=						'▁'

# Segments (not really needed)
SCREAMING_SNAKE_CASE							=						0
SCREAMING_SNAKE_CASE							=						1
SCREAMING_SNAKE_CASE							=						2
SCREAMING_SNAKE_CASE							=						3
SCREAMING_SNAKE_CASE							=						4
class UpperCAmelCase_       (     __A					):




      """simple docstring"""




      UpperCamelCase_             =      VOCAB_FILES_NAMES
      UpperCamelCase_             =      PRETRAINED_VOCAB_FILES_MAP
      UpperCamelCase_             =      PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
      UpperCamelCase_             =      '''left'''
      UpperCamelCase_             =      XLNetTokenizer






      def __init__(			self      :		int  ,   UpperCAmelCase      :		Dict=None  ,   UpperCAmelCase      :		str=None  ,   UpperCAmelCase      :		str=False  ,   UpperCAmelCase      :		List[Any]=True  ,   UpperCAmelCase      :		Optional[Any]=False  ,   UpperCAmelCase      :		int="<s>"  ,   UpperCAmelCase      :		Optional[int]="</s>"  ,   UpperCAmelCase      :		str="<unk>"  ,   UpperCAmelCase      :		Optional[Any]="<sep>"  ,   UpperCAmelCase      :		Optional[int]="<pad>"  ,   UpperCAmelCase      :		Optional[Any]="<cls>"  ,   UpperCAmelCase      :		Dict="<mask>"  ,   UpperCAmelCase      :		int=["<eop>", "<eod>"]  ,   **UpperCAmelCase      :		List[Any]  ,   )	->	List[str]:


       '''simple docstring'''

       lowercase       : Dict						=AddedToken(UpperCAmelCase  ,   lstrip=UpperCAmelCase  ,   rstrip=UpperCAmelCase		) if isinstance(UpperCAmelCase  ,   UpperCAmelCase		) else mask_token

       super().__init__(
           vocab_file=UpperCAmelCase  ,   tokenizer_file=UpperCAmelCase  ,   do_lower_case=UpperCAmelCase  ,   remove_space=UpperCAmelCase  ,   keep_accents=UpperCAmelCase  ,   bos_token=UpperCAmelCase  ,   eos_token=UpperCAmelCase  ,   unk_token=UpperCAmelCase  ,   sep_token=UpperCAmelCase  ,   pad_token=UpperCAmelCase  ,   cls_token=UpperCAmelCase  ,   mask_token=UpperCAmelCase  ,   additional_special_tokens=UpperCAmelCase  ,   **UpperCAmelCase  ,   )

       lowercase       : Tuple						=3
       lowercase       : Union[str, Any]						=do_lower_case
       lowercase       : Any						=remove_space
       lowercase       : int						=keep_accents
       lowercase       : int						=vocab_file
       lowercase       : Union[str, Any]						=False if not self.vocab_file else True






      def 					A__   (			self      :		Any  ,   UpperCAmelCase      :		List[int]  ,   UpperCAmelCase      :		Optional[List[int]] = None		)	->	List[int]:


       '''simple docstring'''

       lowercase       : Union[str, Any]						=[self.sep_token_id]
       lowercase       : Optional[Any]						=[self.cls_token_id]
       if token_ids_a is None:
        return token_ids_a + sep + cls
       return token_ids_a + sep + token_ids_a + sep + cls






      def 					A__   (			self      :		str  ,   UpperCAmelCase      :		List[int]  ,   UpperCAmelCase      :		Optional[List[int]] = None		)	->	List[int]:


       '''simple docstring'''

       lowercase       : Optional[int]						=[self.sep_token_id]
       lowercase       : Union[str, Any]						=[2]

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






      def 					A__   (			self      :		str  ,   UpperCAmelCase      :		str  ,   UpperCAmelCase      :		Optional[str] = None		)	->	Tuple[str]:


       '''simple docstring'''

       if not self.can_save_slow_tokenizer:
        raise ValueError(
            '''Your fast tokenizer does not have the necessary information to save the vocabulary for a slow '''
            '''tokenizer.'''		)

       if not os.path.isdir(UpperCAmelCase		):
        logger.error(f'Vocabulary path ({save_directory}) should be a directory'		)
        return
       lowercase       : Dict						=os.path.join(
           UpperCAmelCase  ,   (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file''']		)

       if os.path.abspath(self.vocab_file		) != os.path.abspath(UpperCAmelCase		):
        copyfile(self.vocab_file  ,   UpperCAmelCase		)

       return (out_vocab_file,)



