


import warnings

from ...configuration_utils import PretrainedConfig
from ...utils import logging


lowercase_    		=     logging.get_logger(__name__)

lowercase_    		=     {
    """xlnet-base-cased""": """https://huggingface.co/xlnet-base-cased/resolve/main/config.json""",
    """xlnet-large-cased""": """https://huggingface.co/xlnet-large-cased/resolve/main/config.json""",
}




class        _UpperCamelCase			(   SCREAMING_SNAKE_CASE_						):







							'''simple docstring'''
							_A						=	"xlnet"
							_A						=	["mems"]
							_A						=	{
							    "n_token": "vocab_size",  # Backward compatibility
							    "hidden_size": "d_model",
							    "num_attention_heads": "n_head",
							    "num_hidden_layers": "n_layer",
							}







							def __init__(		self	:					str		,					SCREAMING_SNAKE_CASE_	:					Tuple=3_2_0_0_0		,					SCREAMING_SNAKE_CASE_	:					int=1_0_2_4		,					SCREAMING_SNAKE_CASE_	:					str=2_4		,					SCREAMING_SNAKE_CASE_	:					Optional[int]=1_6		,					SCREAMING_SNAKE_CASE_	:					Tuple=4_0_9_6		,					SCREAMING_SNAKE_CASE_	:					Optional[int]="gelu"		,					SCREAMING_SNAKE_CASE_	:					Dict=True		,					SCREAMING_SNAKE_CASE_	:					int="bi"		,					SCREAMING_SNAKE_CASE_	:					Any=0.02		,					SCREAMING_SNAKE_CASE_	:					List[str]=1e-1_2		,					SCREAMING_SNAKE_CASE_	:					List[str]=0.1		,					SCREAMING_SNAKE_CASE_	:					Optional[Any]=5_1_2		,					SCREAMING_SNAKE_CASE_	:					str=None		,					SCREAMING_SNAKE_CASE_	:					Any=True		,					SCREAMING_SNAKE_CASE_	:					Union[str, Any]=False		,					SCREAMING_SNAKE_CASE_	:					Optional[Any]=False		,					SCREAMING_SNAKE_CASE_	:					Any=-1		,					SCREAMING_SNAKE_CASE_	:					str=False		,					SCREAMING_SNAKE_CASE_	:					str="last"		,					SCREAMING_SNAKE_CASE_	:					Union[str, Any]=True		,					SCREAMING_SNAKE_CASE_	:					Optional[Any]="tanh"		,					SCREAMING_SNAKE_CASE_	:					Dict=0.1		,					SCREAMING_SNAKE_CASE_	:					Any=5		,					SCREAMING_SNAKE_CASE_	:					Optional[Any]=5		,					SCREAMING_SNAKE_CASE_	:					Any=5		,					SCREAMING_SNAKE_CASE_	:					Dict=1		,					SCREAMING_SNAKE_CASE_	:					int=2		,					**SCREAMING_SNAKE_CASE_	:					Union[str, Any]		,					):
													_a     			=      vocab_size
													_a     			=      d_model
													_a     			=      n_layer
													_a     			=      n_head
													if d_model % n_head != 0:
																			raise ValueError(f"""\'d_model % n_head\' ({d_model % n_head}) should be equal to 0"""		)
													if "d_head" in kwargs:
																			if kwargs["d_head"] != d_model // n_head:
																									raise ValueError(
																									    f"""`d_head` ({kwargs['d_head']}) should be equal to `d_model // n_head` ({d_model // n_head})"""		)
													_a     			=      d_model // n_head
													_a     			=      ff_activation
													_a     			=      d_inner
													_a     			=      untie_r
													_a     			=      attn_type

													_a     			=      initializer_range
													_a     			=      layer_norm_eps

													_a     			=      dropout
													_a     			=      mem_len
													_a     			=      reuse_len
													_a     			=      bi_data
													_a     			=      clamp_len
													_a     			=      same_length

													_a     			=      summary_type
													_a     			=      summary_use_proj
													_a     			=      summary_activation
													_a     			=      summary_last_dropout
													_a     			=      start_n_top
													_a     			=      end_n_top

													_a     			=      bos_token_id
													_a     			=      pad_token_id
													_a     			=      eos_token_id

													if "use_cache" in kwargs:
																			warnings.warn(
																			    'The `use_cache` argument is deprecated and will be removed in a future version, use `use_mems_eval`'
																			    ' instead.'		,					snake_case__		,					)
																			_a     			=      kwargs['use_cache']

													_a     			=      use_mems_eval
													_a     			=      use_mems_train
													super().__init__(pad_token_id=snake_case__		,					bos_token_id=snake_case__		,					eos_token_id=snake_case__		,					**snake_case__		)







							@property
							def 		_UpperCAmelCase						(		self	:					Union[str, Any]		):
													logger.info(f"""The model {self.model_type} is one of the few models that has no sequence length limit."""		)
													return -1







							@max_position_embeddings.setter
							def 		_UpperCAmelCase						(		self	:					int		,					SCREAMING_SNAKE_CASE_	:					Tuple		):
													raise NotImplementedError(
													    f"""The model {self.model_type} is one of the few models that has no sequence length limit."""		)






'''simple docstring'''







import json
import re
from typing import TYPE_CHECKING, List, Optional, Tuple, Union

import numpy as np

from ...utils import is_tf_available, is_torch_available, logging


if TYPE_CHECKING:
       if is_torch_available():
              import torch
       if is_tf_available():
              import tensorflow as tf

from tokenizers import pre_tokenizers

from ...tokenization_utils_base import BatchEncoding
from ...tokenization_utils_fast import PreTrainedTokenizerFast
from .tokenization_codegen import CodeGenTokenizer


lowerCAmelCase     :  Optional[int]											=    logging.get_logger(__name__)

lowerCAmelCase     :  Union[str, Any]											=    {"""vocab_file""": """vocab.json""", """merges_file""": """merges.txt""", """tokenizer_file""": """tokenizer.json"""}

lowerCAmelCase     :  Optional[Any]											=    {
    """vocab_file""": {
        """Salesforce/codegen-350M-mono""": """https://huggingface.co/Salesforce/codegen-350M-mono/resolve/main/vocab.json""",
    },
    """merges_file""": {
        """Salesforce/codegen-350M-mono""": """https://huggingface.co/Salesforce/codegen-350M-mono/resolve/main/merges.txt""",
    },
    """tokenizer_file""": {
        """Salesforce/codegen-350M-mono""": (
            """https://huggingface.co/Salesforce/codegen-350M-mono/resolve/main/tokenizer.json"""
        ),
    },
}

lowerCAmelCase     :  List[str]											=    {
    """Salesforce/codegen-350M-mono""": 20_48,
}
class 						UpperCamelCase__       (			SCREAMING_SNAKE_CASE_						):



     """simple docstring"""






     __magic_name__           =     VOCAB_FILES_NAMES
     __magic_name__           =     PRETRAINED_VOCAB_FILES_MAP
     __magic_name__           =     PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
     __magic_name__           =     ["input_ids", "attention_mask"]
     __magic_name__           =     CodeGenTokenizer







     def __init__(			self   ,						snake_case__=None   ,						snake_case__=None   ,						snake_case__=None   ,						snake_case__="<|endoftext|>"   ,						snake_case__="<|endoftext|>"   ,						snake_case__="<|endoftext|>"   ,						snake_case__=False   ,						**snake_case__   ,						):

            '''simple docstring'''

            super().__init__(
                snake_case__   ,						snake_case__   ,						tokenizer_file=snake_case__   ,						unk_token=snake_case__   ,						bos_token=snake_case__   ,						eos_token=snake_case__   ,						add_prefix_space=snake_case__   ,						**snake_case__   ,						)

            if kwargs.pop('add_bos_token'   ,						snake_case__ ):
                   _lowerCAmelCase     :				Tuple       =							kwargs.pop('name_or_path'   ,						'' )
                   raise ValueError(
                       'Currenty GPT2\'s fast tokenizer does NOT support adding a BOS token.'
                       'Instead you should use GPT2\'s slow tokenizer class `CodeGenTokenizer` as follows: \n'
                       F'`CodeGenTokenizer.from_pretrained(\'{model_id}\')`\nor\n'
                       F'`AutoTokenizer.from_pretrained(\'{model_id}\', use_fast=False)`\n'
                       'This issue will be fixed soon, see: https://github.com/huggingface/tokenizers/pull/1005.'
                       ' so that the fast tokenizer works correctly.' )

            _lowerCAmelCase     :				List[str]       =							json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() )
            if pre_tok_state.get('add_prefix_space'   ,						snake_case__ ) != add_prefix_space:
                   _lowerCAmelCase     :				List[Any]       =							getattr(snake_case__   ,						pre_tok_state.pop('type' ) )
                   _lowerCAmelCase     :				Dict       =							add_prefix_space
                   _lowerCAmelCase     :				List[Any]       =							pre_tok_class(**snake_case__ )

            _lowerCAmelCase     :				Tuple       =							add_prefix_space







     def a						(			self   ,						*snake_case__   ,						**snake_case__ ):

            '''simple docstring'''

            _lowerCAmelCase     :				Union[str, Any]       =							kwargs.get('is_split_into_words'   ,						snake_case__ )
            assert self.add_prefix_space or not is_split_into_words, (
                F'You need to instantiate {self.__class__.__name__} with add_prefix_space=True '
                "to use it with pretokenized inputs."
            )

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







     def a						(			self   ,						*snake_case__   ,						**snake_case__ ):

            '''simple docstring'''

            _lowerCAmelCase     :				List[str]       =							kwargs.get('is_split_into_words'   ,						snake_case__ )

            assert self.add_prefix_space or not is_split_into_words, (
                F'You need to instantiate {self.__class__.__name__} with add_prefix_space=True '
                "to use it with pretokenized inputs."
            )

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







     def a						(			self   ,						snake_case__   ,						snake_case__ = None ):

            '''simple docstring'''

            _lowerCAmelCase     :				List[str]       =							self._tokenizer.model.save(snake_case__   ,						name=snake_case__ )
            return tuple(snake_case__ )







     def a						(			self   ,						snake_case__   ,						snake_case__ = False   ,						snake_case__ = None   ,						snake_case__ = None   ,						**snake_case__   ,						):

            '''simple docstring'''

            _lowerCAmelCase     :				Dict       =							super().decode(
                token_ids=snake_case__   ,						skip_special_tokens=snake_case__   ,						clean_up_tokenization_spaces=snake_case__   ,						**snake_case__   ,						)

            if truncate_before_pattern is not None and len(snake_case__ ) > 0:
                   _lowerCAmelCase     :				Optional[int]       =							self.truncate(snake_case__   ,						snake_case__ )

            return decoded_text







     def a						(			self   ,						snake_case__   ,						snake_case__ ):

            '''simple docstring'''

            def find_re(snake_case__   ,						snake_case__   ,						snake_case__ ):
                   _lowerCAmelCase     :				List[Any]       =							pattern.search(snake_case__   ,						snake_case__ )
                   return m.start() if m else -1

            _lowerCAmelCase     :				Any       =							[re.compile(snake_case__   ,						re.MULTILINE ) for pattern in truncate_before_pattern]

            _lowerCAmelCase     :				Dict       =							list(re.finditer('^print'   ,						snake_case__   ,						re.MULTILINE ) )

            if len(snake_case__ ) > 1:
                   _lowerCAmelCase     :				Optional[int]       =							completion[: prints[1].start()]

            _lowerCAmelCase     :				Optional[int]       =							list(re.finditer('^def'   ,						snake_case__   ,						re.MULTILINE ) )

            if len(snake_case__ ) > 1:
                   _lowerCAmelCase     :				Optional[Any]       =							completion[: defs[1].start()]

            _lowerCAmelCase     :				int       =							0

            _lowerCAmelCase     :				Tuple       =							[
                pos for pos in [find_re(snake_case__   ,						snake_case__   ,						snake_case__ ) for terminal in terminals] if pos != -1
            ]

            if len(snake_case__ ) > 0:
                   return completion[: min(snake_case__ )]
            else:
                   return completion

