
"""simple docstring"""

import os
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     :    Optional[Any]       =			logging.get_logger(__name__)

UpperCamelCase     :    Union[str, Any]       =			"▁"

UpperCamelCase     :    List[Any]       =			{"vocab_file": "sentencepiece.bpe.model"}

UpperCamelCase     :    str       =			{
    "vocab_file": {
        "xlm-roberta-base": "https://huggingface.co/xlm-roberta-base/resolve/main/sentencepiece.bpe.model",
        "xlm-roberta-large": "https://huggingface.co/xlm-roberta-large/resolve/main/sentencepiece.bpe.model",
        "xlm-roberta-large-finetuned-conll02-dutch": (
            "https://huggingface.co/xlm-roberta-large-finetuned-conll02-dutch/resolve/main/sentencepiece.bpe.model"
        ),
        "xlm-roberta-large-finetuned-conll02-spanish": (
            "https://huggingface.co/xlm-roberta-large-finetuned-conll02-spanish/resolve/main/sentencepiece.bpe.model"
        ),
        "xlm-roberta-large-finetuned-conll03-english": (
            "https://huggingface.co/xlm-roberta-large-finetuned-conll03-english/resolve/main/sentencepiece.bpe.model"
        ),
        "xlm-roberta-large-finetuned-conll03-german": (
            "https://huggingface.co/xlm-roberta-large-finetuned-conll03-german/resolve/main/sentencepiece.bpe.model"
        ),
    }
}

UpperCamelCase     :    Union[str, Any]       =			{
    "xlm-roberta-base": 5_1_2,
    "xlm-roberta-large": 5_1_2,
    "xlm-roberta-large-finetuned-conll02-dutch": 5_1_2,
    "xlm-roberta-large-finetuned-conll02-spanish": 5_1_2,
    "xlm-roberta-large-finetuned-conll03-english": 5_1_2,
    "xlm-roberta-large-finetuned-conll03-german": 5_1_2,
}

class __lowerCAmelCase		(				__SCREAMING_SNAKE_CASE      ):
     lowercase						       =						VOCAB_FILES_NAMES
     lowercase						       =						PRETRAINED_VOCAB_FILES_MAP
     lowercase						       =						PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
     lowercase						       =						["input_ids", "attention_mask"]





     def __init__(     self     ,					__UpperCAmelCase     ,					__UpperCAmelCase="<s>"     ,					__UpperCAmelCase="</s>"     ,					__UpperCAmelCase="</s>"     ,					__UpperCAmelCase="<s>"     ,					__UpperCAmelCase="<unk>"     ,					__UpperCAmelCase="<pad>"     ,					__UpperCAmelCase="<mask>"     ,					__UpperCAmelCase = None     ,					**__UpperCAmelCase     ,					):

      '''simple docstring'''




      __UpperCamelCase      =	AddedToken(__UpperCAmelCase     ,					lstrip=__UpperCAmelCase     ,					rstrip=__UpperCAmelCase				) if isinstance(__UpperCAmelCase     ,					__UpperCAmelCase				) else mask_token

      __UpperCamelCase      =	{} if sp_model_kwargs is None else sp_model_kwargs

      super().__init__(
          bos_token=__UpperCAmelCase     ,					eos_token=__UpperCAmelCase     ,					unk_token=__UpperCAmelCase     ,					sep_token=__UpperCAmelCase     ,					cls_token=__UpperCAmelCase     ,					pad_token=__UpperCAmelCase     ,					mask_token=__UpperCAmelCase     ,					sp_model_kwargs=self.sp_model_kwargs     ,					**__UpperCAmelCase     ,					)

      __UpperCamelCase      =	spm.SentencePieceProcessor(**self.sp_model_kwargs				)
      self.sp_model.Load(str(__UpperCAmelCase				)				)
      __UpperCamelCase      =	vocab_file

      # Original fairseq vocab and spm vocab must be "aligned":
      # Vocab    |    0    |    1    |   2    |    3    |  4  |  5  |  6  |   7   |   8   |  9
      # -------- | ------- | ------- | ------ | ------- | --- | --- | --- | ----- | ----- | ----
      # fairseq  | '<s>'   | '<pad>' | '</s>' | '<unk>' | ',' | '.' | '▁' | 's'   | '▁de' | '-'
      # spm      | '<unk>' | '<s>'   | '</s>' | ','     | '.' | '▁' | 's' | '▁de' | '-'   | '▁a'

      # Mimic fairseq token-to-id alignment for the first 4 token
      __UpperCamelCase      =	{'<s>': 0, '<pad>': 1, '</s>': 2, '<unk>': 3}

      # The first "real" token "," has position 4 in the original fairseq vocab and position 3 in the spm vocab
      __UpperCamelCase      =	1

      __UpperCamelCase      =	len(self.sp_model				) + self.fairseq_offset
      __UpperCamelCase      =	{v: k for k, v in self.fairseq_tokens_to_ids.items()}





     def __getstate__(     self				):

      '''simple docstring'''




      __UpperCamelCase      =	self.__dict__.copy()
      __UpperCamelCase      =	None
      __UpperCamelCase      =	self.sp_model.serialized_model_proto()
      return state





     def __setstate__(     self     ,					__UpperCAmelCase				):

      '''simple docstring'''




      __UpperCamelCase      =	d

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

      __UpperCamelCase      =	spm.SentencePieceProcessor(**self.sp_model_kwargs				)
      self.sp_model.LoadFromSerializedProto(self.sp_model_proto				)





     def 						UpperCAmelCase (     self     ,					__UpperCAmelCase     ,					__UpperCAmelCase = None				):

      '''simple docstring'''




      if token_ids_a is None:
       return [self.cls_token_id] + token_ids_a + [self.sep_token_id]
      __UpperCamelCase      =	[self.cls_token_id]
      __UpperCamelCase      =	[self.sep_token_id]
      return cls + token_ids_a + sep + sep + token_ids_a + sep





     def 						UpperCAmelCase (     self     ,					__UpperCAmelCase     ,					__UpperCAmelCase = None     ,					__UpperCAmelCase = False				):

      '''simple docstring'''




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

      if token_ids_a is None:
       return [1] + ([0] * len(__UpperCAmelCase				)) + [1]
      return [1] + ([0] * len(__UpperCAmelCase				)) + [1, 1] + ([0] * len(__UpperCAmelCase				)) + [1]





     def 						UpperCAmelCase (     self     ,					__UpperCAmelCase     ,					__UpperCAmelCase = None				):

      '''simple docstring'''




      __UpperCamelCase      =	[self.sep_token_id]
      __UpperCamelCase      =	[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]





     @property
     def 						UpperCAmelCase (     self				):

      '''simple docstring'''




      return len(self.sp_model				) + self.fairseq_offset + 1  # Add the <mask> token





     def 						UpperCAmelCase (     self				):

      '''simple docstring'''




      __UpperCamelCase      =	{self.convert_ids_to_tokens(__UpperCAmelCase				): i for i in range(self.vocab_size				)}
      vocab.update(self.added_tokens_encoder				)
      return vocab





     def 						UpperCAmelCase (     self     ,					__UpperCAmelCase				):

      '''simple docstring'''




      return self.sp_model.encode(__UpperCAmelCase     ,					out_type=__UpperCAmelCase				)





     def 						UpperCAmelCase (     self     ,					__UpperCAmelCase				):

      '''simple docstring'''




      if token in self.fairseq_tokens_to_ids:
       return self.fairseq_tokens_to_ids[token]
      __UpperCamelCase      =	self.sp_model.PieceToId(__UpperCAmelCase				)

      # Need to return unknown token if the SP model returned 0
      return spm_id + self.fairseq_offset if spm_id else self.unk_token_id





     def 						UpperCAmelCase (     self     ,					__UpperCAmelCase				):

      '''simple docstring'''




      if index in self.fairseq_ids_to_tokens:
       return self.fairseq_ids_to_tokens[index]
      return self.sp_model.IdToPiece(index - self.fairseq_offset				)





     def 						UpperCAmelCase (     self     ,					__UpperCAmelCase				):

      '''simple docstring'''




      __UpperCamelCase      =	''.join(__UpperCAmelCase				).replace(__UpperCAmelCase     ,					' '				).strip()
      return out_string







     def 						UpperCAmelCase (     self     ,					__UpperCAmelCase     ,					__UpperCAmelCase = None				):

      '''simple docstring'''




      if not os.path.isdir(__UpperCAmelCase				):
       logger.error(F'Vocabulary path ({save_directory}) should be a directory'				)
       return
      __UpperCamelCase      =	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				) and os.path.isfile(self.vocab_file				):
       copyfile(self.vocab_file     ,					__UpperCAmelCase				)
      elif not os.path.isfile(self.vocab_file				):
       with open(__UpperCAmelCase     ,					'wb'				) as fi:
        __UpperCamelCase      =	self.sp_model.serialized_model_proto()
        fi.write(__UpperCAmelCase				)

      return (out_vocab_file,)





"""simple docstring"""

from collections import OrderedDict
from typing import Mapping

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging


UpperCamelCase     :    Union[str, Any]       =			logging.get_logger(__name__)

UpperCamelCase     :    int       =			{
    "distilbert-base-uncased": "https://huggingface.co/distilbert-base-uncased/resolve/main/config.json",
    "distilbert-base-uncased-distilled-squad": (
        "https://huggingface.co/distilbert-base-uncased-distilled-squad/resolve/main/config.json"
    ),
    "distilbert-base-cased": "https://huggingface.co/distilbert-base-cased/resolve/main/config.json",
    "distilbert-base-cased-distilled-squad": (
        "https://huggingface.co/distilbert-base-cased-distilled-squad/resolve/main/config.json"
    ),
    "distilbert-base-german-cased": "https://huggingface.co/distilbert-base-german-cased/resolve/main/config.json",
    "distilbert-base-multilingual-cased": (
        "https://huggingface.co/distilbert-base-multilingual-cased/resolve/main/config.json"
    ),
    "distilbert-base-uncased-finetuned-sst-2-english": (
        "https://huggingface.co/distilbert-base-uncased-finetuned-sst-2-english/resolve/main/config.json"
    ),
}

class __lowerCAmelCase		(				__SCREAMING_SNAKE_CASE      ):
     lowercase						       =						"distilbert"
     lowercase						       =						{
         "hidden_size": "dim",
         "num_attention_heads": "n_heads",
         "num_hidden_layers": "n_layers",
     }





     def __init__(     self     ,					__UpperCAmelCase=3_0522     ,					__UpperCAmelCase=512     ,					__UpperCAmelCase=False     ,					__UpperCAmelCase=6     ,					__UpperCAmelCase=12     ,					__UpperCAmelCase=768     ,					__UpperCAmelCase=4 * 768     ,					__UpperCAmelCase=0.1     ,					__UpperCAmelCase=0.1     ,					__UpperCAmelCase="gelu"     ,					__UpperCAmelCase=0.0_2     ,					__UpperCAmelCase=0.1     ,					__UpperCAmelCase=0.2     ,					__UpperCAmelCase=0     ,					**__UpperCAmelCase     ,					):

      '''simple docstring'''




      __UpperCamelCase      =	vocab_size
      __UpperCamelCase      =	max_position_embeddings
      __UpperCamelCase      =	sinusoidal_pos_embds
      __UpperCamelCase      =	n_layers
      __UpperCamelCase      =	n_heads
      __UpperCamelCase      =	dim
      __UpperCamelCase      =	hidden_dim
      __UpperCamelCase      =	dropout
      __UpperCamelCase      =	attention_dropout
      __UpperCamelCase      =	activation
      __UpperCamelCase      =	initializer_range
      __UpperCamelCase      =	qa_dropout
      __UpperCamelCase      =	seq_classif_dropout
      super().__init__(**__UpperCAmelCase     ,					pad_token_id=__UpperCAmelCase				)


class __lowerCAmelCase		(				__SCREAMING_SNAKE_CASE      ):





     @property
     def 						UpperCAmelCase (     self				):

      '''simple docstring'''




      if self.task == "multiple-choice":
       __UpperCamelCase      =	{0: 'batch', 1: 'choice', 2: 'sequence'}
      else:
       __UpperCamelCase      =	{0: 'batch', 1: 'sequence'}
      return OrderedDict(
          [
              ('input_ids', dynamic_axis),
              ('attention_mask', dynamic_axis),
          ]				)



