



'''simple docstring'''





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

import sentencepiece as spm

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


if TYPE_CHECKING:
   from transformers.pipelines.conversational import Conversation

_UpperCamelCase							       =		logging.get_logger(__name__)

_UpperCamelCase							       =		{'vocab_file': 'tokenizer.model'}

_UpperCamelCase							       =		{
    'vocab_file': {
        'hf-internal-testing/llama-tokenizer': 'https://huggingface.co/hf-internal-testing/llama-tokenizer/resolve/main/tokenizer.model',
    },
    'tokenizer_file': {
        'hf-internal-testing/llama-tokenizer': 'https://huggingface.co/hf-internal-testing/llama-tokenizer/resolve/main/tokenizer_config.json',
    },
}
_UpperCamelCase							       =		{
    'hf-internal-testing/llama-tokenizer': 2048,
}
_UpperCamelCase							       =		'▁'

_UpperCamelCase       ,       _UpperCamelCase							       =		'[INST]', '[/INST]'
_UpperCamelCase       ,       _UpperCamelCase							       =		'<<SYS>>\n', '\n<</SYS>>\n\n'

# fmt: off
_UpperCamelCase							       =		'You are a helpful, respectful and honest assistant. Always answer as helpfully as possible, while being safe. Your\\nanswers should not include any harmful, unethical, racist, sexist, toxic, dangerous, or illegal content. Please ensure\\nthat your responses are socially unbiased and positive in nature.\n\nIf a question does not make any sense, or is not factually coherent, explain why instead of answering something not\\ncorrect. If you don\'t know the answer to a question, please don\'t share false information.'






class       lowerCamelCase_					(       SCREAMING_SNAKE_CASE_  ):
  """simple docstring"""




  a_							      =VOCAB_FILES_NAMES
  a_							      =PRETRAINED_VOCAB_FILES_MAP
  a_							      =PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
  a_							      =["""input_ids""", """attention_mask"""]




  def __init__(				self   :			int    ,			_a   :			Any    ,			_a   :			List[str]="<unk>"    ,			_a   :			Any="<s>"    ,			_a   :			int="</s>"    ,			_a   :			Any=None    ,			_a   :			Optional[Dict[str, Any]] = None    ,			_a   :			Any=True    ,			_a   :			Optional[int]=False    ,			_a   :			Dict=False    ,			_a   :			str=True    ,			**_a   :			Any    ,			)      ->      Dict:
    __lowerCamelCase : List[str]					 =				{} if sp_model_kwargs is None else sp_model_kwargs
    __lowerCamelCase : int					 =				AddedToken(_a    ,			lstrip=_a    ,			rstrip=_a     ) if isinstance(_a    ,			_a     ) else bos_token
    __lowerCamelCase : int					 =				AddedToken(_a    ,			lstrip=_a    ,			rstrip=_a     ) if isinstance(_a    ,			_a     ) else eos_token
    __lowerCamelCase : List[str]					 =				AddedToken(_a    ,			lstrip=_a    ,			rstrip=_a     ) if isinstance(_a    ,			_a     ) else unk_token
    __lowerCamelCase : Dict					 =				AddedToken(_a    ,			lstrip=_a    ,			rstrip=_a     ) if isinstance(_a    ,			_a     ) else pad_token
    super().__init__(
        bos_token=_a    ,			eos_token=_a    ,			unk_token=_a    ,			pad_token=_a    ,			add_bos_token=_a    ,			add_eos_token=_a    ,			sp_model_kwargs=self.sp_model_kwargs    ,			clean_up_tokenization_spaces=_a    ,			legacy=_a    ,			**_a    ,			)
    if legacy:
      logger.warning_once(
          f'You are using the legacy behaviour of the {self.__class__}. This means that tokens that come after special tokens will not be properly handled. We recommend you to'
          ' read the related pull request available at https://github.com/huggingface/transformers/pull/24565'     )
    __lowerCamelCase : Any					 =				legacy
    __lowerCamelCase : Union[str, Any]					 =				vocab_file
    __lowerCamelCase : Union[str, Any]					 =				add_bos_token
    __lowerCamelCase : List[str]					 =				add_eos_token
    __lowerCamelCase : int					 =				spm.SentencePieceProcessor(**self.sp_model_kwargs     )
    self.sp_model.Load(_a     )




  def __getstate__(				self   :			Tuple     )      ->      Dict:
    __lowerCamelCase : Optional[Any]					 =				self.__dict__.copy()
    __lowerCamelCase : Dict					 =				None
    __lowerCamelCase : str					 =				self.sp_model.serialized_model_proto()
    return state




  def __setstate__(				self   :			Dict    ,			_a   :			Optional[Any]     )      ->      List[str]:
    __lowerCamelCase : Optional[int]					 =				d
    __lowerCamelCase : Optional[int]					 =				spm.SentencePieceProcessor(**self.sp_model_kwargs     )
    self.sp_model.LoadFromSerializedProto(self.sp_model_proto     )




  @property
  def 		_lowercase  (				self   :			List[str]     )      ->      Optional[Any]:
    return self.sp_model.get_piece_size()




  def 		_lowercase  (				self   :			List[str]     )      ->      Union[str, Any]:
    __lowerCamelCase : Tuple					 =				{self.convert_ids_to_tokens(_a     ): i for i in range(self.vocab_size     )}
    vocab.update(self.added_tokens_encoder     )
    return vocab




  def 		_lowercase  (				self   :			List[Any]    ,			_a   :			List[str]    ,			**_a   :			Dict     )      ->      List[str]:
    # Replace the SPIECE_UNDERLINE with a space to make sure SPIECE_UNDERLINE is only used at
    # the beginning of the text
    if not self.legacy:
      __lowerCamelCase : Optional[int]					 =				SPIECE_UNDERLINE + text.replace(_a    ,			' '     )
    return super().tokenize(_a    ,			**_a     )




  def 		_lowercase  (				self   :			Union[str, Any]    ,			_a   :			str     )      ->      Any:
    if not self.legacy:
      __lowerCamelCase : int					 =				text.startswith(_a     )
      if is_first:
        __lowerCamelCase : List[Any]					 =				text[1:]

    __lowerCamelCase : Optional[Any]					 =				self.sp_model.encode(_a    ,			out_type=_a     )

    if not self.legacy and not is_first and not text.startswith(' '     ) and tokens[0].startswith(_a     ):
      __lowerCamelCase : int					 =				([tokens[0][1:]] if len(tokens[0]     ) > 1 else []) + tokens[1:]
    return tokens




  def 		_lowercase  (				self   :			List[Any]    ,			_a   :			Union[str, Any]     )      ->      Any:
    return self.sp_model.piece_to_id(_a     )




  def 		_lowercase  (				self   :			Union[str, Any]    ,			_a   :			Tuple     )      ->      List[str]:
    __lowerCamelCase : Tuple					 =				self.sp_model.IdToPiece(_a     )
    return token




  def 		_lowercase  (				self   :			Dict    ,			_a   :			Optional[int]     )      ->      Optional[int]:
    __lowerCamelCase : Union[str, Any]					 =				[]
    __lowerCamelCase : Any					 =				''
    __lowerCamelCase : Optional[Any]					 =				False
    for i, token in enumerate(_a     ):
      # make sure that special tokens are not decoded using sentencepiece model
      if token in self.all_special_tokens:
        if not prev_is_special and i != 0:
          out_string += " "
        out_string += self.sp_model.decode(_a     ) + token
        __lowerCamelCase : Optional[int]					 =				True
        __lowerCamelCase : Optional[Any]					 =				[]
      else:
        current_sub_tokens.append(_a     )
        __lowerCamelCase : str					 =				False
    out_string += self.sp_model.decode(_a     )
    return out_string




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

    if os.path.abspath(self.vocab_file     ) != os.path.abspath(_a     ) and os.path.isfile(self.vocab_file     ):
      copyfile(self.vocab_file    ,			_a     )
    elif not os.path.isfile(self.vocab_file     ):
      with open(_a    ,			'wb'     ) as fi:
        __lowerCamelCase : Optional[Any]					 =				self.sp_model.serialized_model_proto()
        fi.write(_a     )

    return (out_vocab_file,)




  def 		_lowercase  (				self   :			int    ,			_a   :			Union[str, Any]    ,			_a   :			Dict=None     )      ->      int:
    __lowerCamelCase : Optional[Any]					 =				[self.bos_token_id] if self.add_bos_token else []
    __lowerCamelCase : Any					 =				[self.eos_token_id] if self.add_eos_token else []

    __lowerCamelCase : Any					 =				bos_token_id + token_ids_a + eos_token_id

    if token_ids_a is not None:
      __lowerCamelCase : Dict					 =				output + bos_token_id + token_ids_a + eos_token_id

    return output




  def 		_lowercase  (				self   :			int    ,			_a   :			List[int]    ,			_a   :			Optional[List[int]] = None    ,			_a   :			bool = False     )      ->      List[int]:
    if already_has_special_tokens:
      return super().get_special_tokens_mask(
          token_ids_a=_a    ,			token_ids_a=_a    ,			already_has_special_tokens=_a     )

    __lowerCamelCase : Tuple					 =				[1] if self.add_bos_token else []
    __lowerCamelCase : Optional[int]					 =				[1] if self.add_eos_token else []

    if token_ids_a is None:
      return bos_token_id + ([0] * len(_a     )) + eos_token_id
    return (
        bos_token_id
        + ([0] * len(_a     ))
        + eos_token_id
        + bos_token_id
        + ([0] * len(_a     ))
        + eos_token_id
    )




  def 		_lowercase  (				self   :			List[str]    ,			_a   :			List[int]    ,			_a   :			Optional[List[int]] = None     )      ->      List[int]:
    __lowerCamelCase : List[Any]					 =				[self.bos_token_id] if self.add_bos_token else []
    __lowerCamelCase : List[Any]					 =				[self.eos_token_id] if self.add_eos_token else []

    __lowerCamelCase : Optional[Any]					 =				[0] * len(bos_token_id + token_ids_a + eos_token_id     )

    if token_ids_a is not None:
      output += [1] * len(bos_token_id + token_ids_a + eos_token_id     )

    return output




  def 		_lowercase  (				self   :			Union[str, Any]    ,			_a   :			"Conversation"     )      ->      List[int]:
    __lowerCamelCase : List[Any]					 =				list(conversation.iter_texts()     )
    if not all([is_user for is_user, msg in dialogue[::2]]     ) or not all(
        [not is_user for is_user, msg in dialogue[1::2]]     ):
      raise ValueError(
          'The model only supports \'user\' and \'assistant\' roles, starting with user and alternating (u/a/u/a/u...)'     )

    __lowerCamelCase : List[int]					 =				[]
    if len(conversation.past_user_inputs     ) > 0:
      if not conversation.past_user_inputs[0].startswith(_a     ) or E_SYS not in conversation.past_user_inputs[0]:
        __lowerCamelCase : Any					 =				(
            B_SYS + DEFAULT_SYSTEM_PROMPT + E_SYS + conversation.past_user_inputs[0]
        )
    elif not dialogue[0][1].startswith(_a     ) or E_SYS not in dialogue[0][1]:
      __lowerCamelCase : List[Any]					 =				(dialogue[0][0], B_SYS + DEFAULT_SYSTEM_PROMPT + E_SYS + dialogue[0][1])

    dialog_tokens += sum(
        [
            [self.bos_token_id]
            + self.encode(
                f'{B_INST} {(prompt[1]).strip()} {E_INST} {(answer[1]).strip()} '    ,			add_special_tokens=_a     )
            + [self.eos_token_id]
            for prompt, answer in zip(dialogue[::2]    ,			dialogue[1::2]     )
        ]    ,			[]    ,			)
    if not (dialogue[-1][0]):
      raise ValueError(f'Last message must be from user, got {dialogue[-1]["role"]}'     )
    dialog_tokens += [self.bos_token_id] + self.encode(
        f'{B_INST} {(dialogue[-1][1]).strip()} {E_INST}'    ,			add_special_tokens=_a     )
    return dialog_tokens











'''simple docstring'''





from typing import List, Union

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


_UpperCamelCase							       =		logging.get_logger(__name__)

_UpperCamelCase							       =		{
    'allenai/led-base-16384': 'https://huggingface.co/allenai/led-base-16384/resolve/main/config.json',
    # See all LED models at https://huggingface.co/models?filter=led
}






class       lowerCamelCase_					(       SCREAMING_SNAKE_CASE_  ):
  """simple docstring"""




  a_							      ="""led"""
  a_							      ={
      """num_attention_heads""": """encoder_attention_heads""",
      """hidden_size""": """d_model""",
      """attention_probs_dropout_prob""": """attention_dropout""",
      """initializer_range""": """init_std""",
  }




  def __init__(				self   :			str    ,			_a   :			Union[str, Any]=5_0265    ,			_a   :			Any=1_6384    ,			_a   :			List[Any]=1024    ,			_a   :			List[Any]=12    ,			_a   :			Any=4096    ,			_a   :			int=16    ,			_a   :			int=12    ,			_a   :			Optional[int]=4096    ,			_a   :			Tuple=16    ,			_a   :			Optional[Any]=0.0    ,			_a   :			Tuple=0.0    ,			_a   :			List[Any]=True    ,			_a   :			Optional[Any]=True    ,			_a   :			Any="gelu"    ,			_a   :			List[Any]=1024    ,			_a   :			List[str]=0.1    ,			_a   :			Dict=0.0    ,			_a   :			Tuple=0.0    ,			_a   :			Any=0.02    ,			_a   :			Optional[int]=2    ,			_a   :			Optional[int]=0.0    ,			_a   :			int=1    ,			_a   :			List[Any]=0    ,			_a   :			str=2    ,			_a   :			Union[List[int], int] = 512    ,			**_a   :			Optional[int]    ,			)      ->      Tuple:
    __lowerCamelCase : Optional[int]					 =				vocab_size
    __lowerCamelCase : List[str]					 =				max_encoder_position_embeddings
    __lowerCamelCase : Any					 =				max_decoder_position_embeddings
    __lowerCamelCase : Optional[Any]					 =				d_model
    __lowerCamelCase : str					 =				encoder_ffn_dim
    __lowerCamelCase : List[Any]					 =				encoder_layers
    __lowerCamelCase : Union[str, Any]					 =				encoder_attention_heads
    __lowerCamelCase : Optional[Any]					 =				decoder_ffn_dim
    __lowerCamelCase : Union[str, Any]					 =				decoder_layers
    __lowerCamelCase : Optional[Any]					 =				decoder_attention_heads
    __lowerCamelCase : Optional[Any]					 =				dropout
    __lowerCamelCase : List[Any]					 =				attention_dropout
    __lowerCamelCase : Optional[int]					 =				activation_dropout
    __lowerCamelCase : Optional[int]					 =				activation_function
    __lowerCamelCase : Union[str, Any]					 =				init_std
    __lowerCamelCase : str					 =				encoder_layerdrop
    __lowerCamelCase : Tuple					 =				decoder_layerdrop
    __lowerCamelCase : Dict					 =				classifier_dropout
    __lowerCamelCase : Any					 =				use_cache
    __lowerCamelCase : Union[str, Any]					 =				encoder_layers
    __lowerCamelCase : Any					 =				attention_window

    super().__init__(
        pad_token_id=_a    ,			bos_token_id=_a    ,			eos_token_id=_a    ,			is_encoder_decoder=_a    ,			decoder_start_token_id=_a    ,			**_a    ,			)






