



import os
import unicodedata
from shutil import copyfile
from typing import Any, Dict, List, Optional, Tuple

import sentencepiece as spm

from ...tokenization_utils import AddedToken, PreTrainedTokenizer
from ...utils import logging


UpperCAmelCase_		 =					logging.get_logger(__name__)
UpperCAmelCase_		 =					{"""vocab_file""": """spiece.model"""}

UpperCAmelCase_		 =					{
    """vocab_file""": {
        """albert-base-v1""": """https://huggingface.co/albert-base-v1/resolve/main/spiece.model""",
        """albert-large-v1""": """https://huggingface.co/albert-large-v1/resolve/main/spiece.model""",
        """albert-xlarge-v1""": """https://huggingface.co/albert-xlarge-v1/resolve/main/spiece.model""",
        """albert-xxlarge-v1""": """https://huggingface.co/albert-xxlarge-v1/resolve/main/spiece.model""",
        """albert-base-v2""": """https://huggingface.co/albert-base-v2/resolve/main/spiece.model""",
        """albert-large-v2""": """https://huggingface.co/albert-large-v2/resolve/main/spiece.model""",
        """albert-xlarge-v2""": """https://huggingface.co/albert-xlarge-v2/resolve/main/spiece.model""",
        """albert-xxlarge-v2""": """https://huggingface.co/albert-xxlarge-v2/resolve/main/spiece.model""",
    }
}

UpperCAmelCase_		 =					{
    """albert-base-v1""": 5_1_2,
    """albert-large-v1""": 5_1_2,
    """albert-xlarge-v1""": 5_1_2,
    """albert-xxlarge-v1""": 5_1_2,
    """albert-base-v2""": 5_1_2,
    """albert-large-v2""": 5_1_2,
    """albert-xlarge-v2""": 5_1_2,
    """albert-xxlarge-v2""": 5_1_2,
}

UpperCAmelCase_		 =					"""▁"""


class 	lowerCamelCase__	(       _A):



 """simple docstring"""

 a__					: Tuple =  VOCAB_FILES_NAMES
 a__					: str =  PRETRAINED_VOCAB_FILES_MAP
 a__					: int =  PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES

 def __init__(    self					:					Dict			,						__lowerCAmelCase					:					List[str]			,						__lowerCAmelCase					:					Optional[int]=True			,						__lowerCAmelCase					:					Tuple=True			,						__lowerCAmelCase					:					Optional[Any]=False			,						__lowerCAmelCase					:					Optional[Any]="[CLS]"			,						__lowerCAmelCase					:					List[Any]="[SEP]"			,						__lowerCAmelCase					:					List[str]="<unk>"			,						__lowerCAmelCase					:					str="[SEP]"			,						__lowerCAmelCase					:					Optional[Any]="<pad>"			,						__lowerCAmelCase					:					int="[CLS]"			,						__lowerCAmelCase					:					List[str]="[MASK]"			,						__lowerCAmelCase					:					Optional[Dict[str, Any]] = None			,						**__lowerCAmelCase					:					List[Any]			,						)   ->	None:
    # Mask token behave like a normal word, i.e. include the space before it and
    # is included in the raw text, there should be a match in a non-normalized sentence.
    _A      =       (
        AddedToken(__lowerCAmelCase			,						lstrip=__lowerCAmelCase			,						rstrip=__lowerCAmelCase			,						normalized=__lowerCAmelCase      )
        if isinstance(__lowerCAmelCase			,						__lowerCAmelCase      )
        else mask_token
    )

    _A      =       {} if sp_model_kwargs is None else sp_model_kwargs

    super().__init__(
        do_lower_case=__lowerCAmelCase			,						remove_space=__lowerCAmelCase			,						keep_accents=__lowerCAmelCase			,						bos_token=__lowerCAmelCase			,						eos_token=__lowerCAmelCase			,						unk_token=__lowerCAmelCase			,						sep_token=__lowerCAmelCase			,						pad_token=__lowerCAmelCase			,						cls_token=__lowerCAmelCase			,						mask_token=__lowerCAmelCase			,						sp_model_kwargs=self.sp_model_kwargs			,						**__lowerCAmelCase			,						)

    _A      =       do_lower_case
    _A      =       remove_space
    _A      =       keep_accents
    _A      =       vocab_file

    _A      =       spm.SentencePieceProcessor(**self.sp_model_kwargs      )
    self.sp_model.Load(__lowerCAmelCase      )

 @property
 def     snake_case_      (    self					:					List[Any]      )   ->	int:
    return len(self.sp_model      )

 def     snake_case_      (    self					:					Optional[int]      )   ->	List[str]:
    _A      =       {self.convert_ids_to_tokens(__lowerCAmelCase      ): i for i in range(self.vocab_size      )}
    vocab.update(self.added_tokens_encoder      )
    return vocab

 def __getstate__(    self					:					str      )   ->	str:
    _A      =       self.__dict__.copy()
    _A      =       None
    return state

 def __setstate__(    self					:					Dict			,						__lowerCAmelCase					:					Dict      )   ->	Tuple:
    _A      =       d

    # for backward compatibility
    if not hasattr(self			,						'''sp_model_kwargs'''      ):
       _A      =       {}

    _A      =       spm.SentencePieceProcessor(**self.sp_model_kwargs      )
    self.sp_model.Load(self.vocab_file      )

 def     snake_case_      (    self					:					str			,						__lowerCAmelCase					:					str      )   ->	Any:
    if self.remove_space:
       _A      =       ''' '''.join(inputs.strip().split()      )
    else:
       _A      =       inputs
    _A      =       outputs.replace('''``'''			,						'''"'''      ).replace('''\'\''''			,						'''"'''      )

    if not self.keep_accents:
       _A      =       unicodedata.normalize('''NFKD'''			,						__lowerCAmelCase      )
       _A      =       ''''''.join([c for c in outputs if not unicodedata.combining(__lowerCAmelCase      )]      )
    if self.do_lower_case:
       _A      =       outputs.lower()

    return outputs

 def     snake_case_      (    self					:					Union[str, Any]			,						__lowerCAmelCase					:					str      )   ->	List[str]:
    _A      =       self.preprocess_text(__lowerCAmelCase      )
    _A      =       self.sp_model.encode(__lowerCAmelCase			,						out_type=__lowerCAmelCase      )
    _A      =       []
    for piece in pieces:
       if len(__lowerCAmelCase      ) > 1 and piece[-1] == str(''','''      ) and piece[-2].isdigit():
          _A      =       self.sp_model.EncodeAsPieces(piece[:-1].replace(__lowerCAmelCase			,						''''''      )      )
          if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE:
             if len(cur_pieces[0]      ) == 1:
                _A      =       cur_pieces[1:]
             else:
                _A      =       cur_pieces[0][1:]
          cur_pieces.append(piece[-1]      )
          new_pieces.extend(__lowerCAmelCase      )
       else:
          new_pieces.append(__lowerCAmelCase      )

    return new_pieces

 def     snake_case_      (    self					:					str			,						__lowerCAmelCase					:					Optional[int]      )   ->	Dict:
    return self.sp_model.PieceToId(__lowerCAmelCase      )

 def     snake_case_      (    self					:					Optional[Any]			,						__lowerCAmelCase					:					Optional[int]      )   ->	List[Any]:
    return self.sp_model.IdToPiece(__lowerCAmelCase      )

 def     snake_case_      (    self					:					Dict			,						__lowerCAmelCase					:					Optional[Any]      )   ->	Optional[Any]:
    _A      =       []
    _A      =       ''''''
    _A      =       False
    for token in tokens:
       # make sure that special tokens are not decoded using sentencepiece model
       if token in self.all_special_tokens:
          if not prev_is_special:
             out_string += " "
          out_string += self.sp_model.decode(__lowerCAmelCase      ) + token
          _A      =       True
          _A      =       []
       else:
          current_sub_tokens.append(__lowerCAmelCase      )
          _A      =       False
    out_string += self.sp_model.decode(__lowerCAmelCase      )
    return out_string.strip()

 def     snake_case_      (    self					:					Dict			,						__lowerCAmelCase					:					List[int]			,						__lowerCAmelCase					:					Optional[List[int]] = None      )   ->	List[int]:
    _A      =       [self.sep_token_id]
    _A      =       [self.cls_token_id]
    if token_ids_a is None:
       return cls + token_ids_a + sep
    return cls + token_ids_a + sep + token_ids_a + sep

 def     snake_case_      (    self					:					Dict			,						__lowerCAmelCase					:					List[int]			,						__lowerCAmelCase					:					Optional[List[int]] = None			,						__lowerCAmelCase					:					bool = False      )   ->	List[int]:

    if already_has_special_tokens:
       return super().get_special_tokens_mask(
           token_ids_a=__lowerCAmelCase			,						token_ids_a=__lowerCAmelCase			,						already_has_special_tokens=__lowerCAmelCase      )

    if token_ids_a is not None:
       return [1] + ([0] * len(__lowerCAmelCase      )) + [1] + ([0] * len(__lowerCAmelCase      )) + [1]
    return [1] + ([0] * len(__lowerCAmelCase      )) + [1]

 def     snake_case_      (    self					:					str			,						__lowerCAmelCase					:					List[int]			,						__lowerCAmelCase					:					Optional[List[int]] = None      )   ->	List[int]:
    _A      =       [self.sep_token_id]
    _A      =       [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      ) * [0] + len(token_ids_a + sep      ) * [1]

 def     snake_case_      (    self					:					Tuple			,						__lowerCAmelCase					:					str			,						__lowerCAmelCase					:					Optional[str] = None      )   ->	Tuple[str]:
    if not os.path.isdir(__lowerCAmelCase      ):
       logger.error(f'''Vocabulary path ({save_directory}) should be a directory'''      )
       return
    _A      =       os.path.join(
        __lowerCAmelCase			,						(filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file''']      )

    if os.path.abspath(self.vocab_file      ) != os.path.abspath(__lowerCAmelCase      ) and os.path.isfile(self.vocab_file      ):
       copyfile(self.vocab_file			,						__lowerCAmelCase      )
    elif not os.path.isfile(self.vocab_file      ):
       with open(__lowerCAmelCase			,						'''wb'''      ) as fi:
          _A      =       self.sp_model.serialized_model_proto()
          fi.write(__lowerCAmelCase      )

    return (out_vocab_file,)






'''simple docstring'''

import importlib.util
import json
import os
import warnings
from dataclasses import dataclass, field

import torch

from ..training_args import TrainingArguments
from ..utils import cached_property, is_sagemaker_dp_enabled, logging


SCREAMING_SNAKE_CASE							:				Optional[Any]     	=			logging.get_logger(__name__)




def 							_UpperCamelCase				(   )      -> List[Any]:
							# Get the sagemaker specific mp parameters from smp_options variable.
							SCREAMING_SNAKE_CASE_				=				os.getenv('SM_HP_MP_PARAMETERS'		,'{}'   )
							try:
														# Parse it and check the field "partitions" is included, it is required for model parallel.
														SCREAMING_SNAKE_CASE_				=				json.loads(lowerCAmelCase__   )
														if "partitions" not in smp_options:
																					return False
							except json.JSONDecodeError:
														return False

							# Get the sagemaker specific framework parameters from mpi_options variable.
							SCREAMING_SNAKE_CASE_				=				os.getenv('SM_FRAMEWORK_PARAMS'		,'{}'   )
							try:
														# Parse it and check the field "sagemaker_distributed_dataparallel_enabled".
														SCREAMING_SNAKE_CASE_				=				json.loads(lowerCAmelCase__   )
														if not mpi_options.get('sagemaker_mpi_enabled'		,lowerCAmelCase__   ):
																					return False
							except json.JSONDecodeError:
														return False
							# Lastly, check if the `smdistributed` module is present.
							return importlib.util.find_spec('smdistributed'   ) is not None


if is_sagemaker_model_parallel_available():
							import smdistributed.modelparallel.torch as smp

							smp.init()






@dataclass
class    snake_case     (      lowercase_		):






				"""simple docstring"""
				_a    	=     field(
				    default="""""",						metadata={"""help""": """Used by the SageMaker launcher to send mp-specific args. Ignored in SageMakerTrainer"""},						)



				def   a__					(    self       )     ->							Union[str, Any]:
											super().__post_init__()
											warnings.warn(
											    '`SageMakerTrainingArguments` is deprecated and will be removed in v5 of Transformers. You can use '
											    '`TrainingArguments` instead.',     _lowercase,     )



				@cached_property
				def   a__					(    self       )     ->							"torch.device":
											logger.info('PyTorch: setting up devices'       )
											if torch.distributed.is_available() and torch.distributed.is_initialized() and self.local_rank == -1:
																		logger.warning(
																		    'torch.distributed process group is initialized, but local_rank == -1. '
																		    'In order to use Torch DDP, launch your script with `python -m torch.distributed.launch'       )
											if self.no_cuda:
																		SCREAMING_SNAKE_CASE_				=				torch.device('cpu'       )
																		SCREAMING_SNAKE_CASE_				=				0
											elif is_sagemaker_model_parallel_available():
																		SCREAMING_SNAKE_CASE_				=				smp.local_rank()
																		SCREAMING_SNAKE_CASE_				=				torch.device('cuda',     _lowercase       )
																		SCREAMING_SNAKE_CASE_				=				1
											elif is_sagemaker_dp_enabled():
																		import smdistributed.dataparallel.torch.torch_smddp  # noqa: F401

																		torch.distributed.init_process_group(backend='smddp',     timeout=self.ddp_timeout_delta       )
																		SCREAMING_SNAKE_CASE_				=				int(os.getenv('SMDATAPARALLEL_LOCAL_RANK'       )       )
																		SCREAMING_SNAKE_CASE_				=				torch.device('cuda',     self.local_rank       )
																		SCREAMING_SNAKE_CASE_				=				1
											elif self.local_rank == -1:
																		# if n_gpu is > 1 we'll use nn.DataParallel.
																		# If you only want to use a specific subset of GPUs use `CUDA_VISIBLE_DEVICES=0`
																		# Explicitly set CUDA to the first (index 0) CUDA device, otherwise `set_device` will
																		# trigger an error that a device index is missing. Index 0 takes into account the
																		# GPUs available in the environment, so `CUDA_VISIBLE_DEVICES=1,2` with `cuda:0`
																		# will use the first GPU in that env, i.e. GPU#1
																		SCREAMING_SNAKE_CASE_				=				torch.device('cuda:0' if torch.cuda.is_available() else 'cpu'       )
																		# Sometimes the line in the postinit has not been run before we end up here, so just checking we're not at
																		# the default value.
																		SCREAMING_SNAKE_CASE_				=				torch.cuda.device_count()
											else:
																		# Here, we'll use torch.distributed.
																		# Initializes the distributed backend which will take care of synchronizing nodes/GPUs
																		if not torch.distributed.is_initialized():
																									torch.distributed.init_process_group(backend='nccl',     timeout=self.ddp_timeout_delta       )
																		SCREAMING_SNAKE_CASE_				=				torch.device('cuda',     self.local_rank       )
																		SCREAMING_SNAKE_CASE_				=				1

											if device.type == "cuda":
																		torch.cuda.set_device(_lowercase       )

											return device



				@property
				def   a__					(    self       )     ->							Optional[Any]:
											if is_sagemaker_model_parallel_available():
																		return smp.dp_size()

											return super().world_size



				@property
				def   a__					(    self       )     ->							Optional[Any]:
											return not is_sagemaker_model_parallel_available()





				@property
				def   a__					(    self       )     ->							Tuple:
											return False





