


'''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''': 2_0_4_8,
}
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\
answers should not include any harmful, unethical, racist, sexist, toxic, dangerous, or illegal content. Please ensure\
that your responses are socially unbiased and positive in nature.

If a question does not make any sense, or is not factually coherent, explain why instead of answering something not\
correct. If you don\'t know the answer to a question, please don\'t share false information.'''
class 	a__				(				a_      ):





			'''simple docstring'''

			A	:							Dict							= VOCAB_FILES_NAMES
			A	:							Optional[Any]							= PRETRAINED_VOCAB_FILES_MAP
			A	:							List[Any]							= PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
			A	:							str							= ['''input_ids''', '''attention_mask''']
			def __init__(     self       : Dict ,						lowerCAmelCase_       : Tuple ,						lowerCAmelCase_       : Union[str, Any]="<unk>" ,						lowerCAmelCase_       : str="<s>" ,						lowerCAmelCase_       : Any="</s>" ,						lowerCAmelCase_       : Optional[Any]=None ,						lowerCAmelCase_       : Optional[Dict[str, Any]] = None ,						lowerCAmelCase_       : str=True ,						lowerCAmelCase_       : str=False ,						lowerCAmelCase_       : Any=False ,						lowerCAmelCase_       : Dict=True ,						**lowerCAmelCase_       : List[str] ,						)			->		Optional[int]:
						__A=  {} if sp_model_kwargs is None else sp_model_kwargs
						__A=  AddedToken(lowerCAmelCase_ ,						lstrip=lowerCAmelCase_ ,						rstrip=lowerCAmelCase_  ) if isinstance(lowerCAmelCase_ ,						lowerCAmelCase_  ) else bos_token
						__A=  AddedToken(lowerCAmelCase_ ,						lstrip=lowerCAmelCase_ ,						rstrip=lowerCAmelCase_  ) if isinstance(lowerCAmelCase_ ,						lowerCAmelCase_  ) else eos_token
						__A=  AddedToken(lowerCAmelCase_ ,						lstrip=lowerCAmelCase_ ,						rstrip=lowerCAmelCase_  ) if isinstance(lowerCAmelCase_ ,						lowerCAmelCase_  ) else unk_token
						__A=  AddedToken(lowerCAmelCase_ ,						lstrip=lowerCAmelCase_ ,						rstrip=lowerCAmelCase_  ) if isinstance(lowerCAmelCase_ ,						lowerCAmelCase_  ) else pad_token
						super().__init__(
						    bos_token=lowerCAmelCase_ ,						eos_token=lowerCAmelCase_ ,						unk_token=lowerCAmelCase_ ,						pad_token=lowerCAmelCase_ ,						add_bos_token=lowerCAmelCase_ ,						add_eos_token=lowerCAmelCase_ ,						sp_model_kwargs=self.sp_model_kwargs ,						clean_up_tokenization_spaces=lowerCAmelCase_ ,						legacy=lowerCAmelCase_ ,						**lowerCAmelCase_ ,						)
						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'  )
						__A=  legacy
						__A=  vocab_file
						__A=  add_bos_token
						__A=  add_eos_token
						__A=  spm.SentencePieceProcessor(**self.sp_model_kwargs  )
						self.sp_model.Load(lowerCAmelCase_  )
			def __getstate__(     self       : Optional[Any]  )			->		Optional[Any]:
						__A=  self.__dict__.copy()
						__A=  None
						__A=  self.sp_model.serialized_model_proto()
						return state
			def __setstate__(     self       : Union[str, Any] ,						lowerCAmelCase_       : Union[str, Any]  )			->		Dict:
						__A=  d
						__A=  spm.SentencePieceProcessor(**self.sp_model_kwargs  )
						self.sp_model.LoadFromSerializedProto(self.sp_model_proto  )
			@property
			def 				lowerCAmelCase    (     self       : Dict  )			->		Union[str, Any]:
						return self.sp_model.get_piece_size()
			def 				lowerCAmelCase    (     self       : Dict  )			->		int:
						__A=  {self.convert_ids_to_tokens(lowerCAmelCase_  ): i for i in range(self.vocab_size  )}
						vocab.update(self.added_tokens_encoder  )
						return vocab
			def 				lowerCAmelCase    (     self       : int ,						lowerCAmelCase_       : Optional[int] ,						**lowerCAmelCase_       : int  )			->		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:
									__A=  SPIECE_UNDERLINE + text.replace(lowerCAmelCase_ ,						' '  )
						return super().tokenize(lowerCAmelCase_ ,						**lowerCAmelCase_  )
			def 				lowerCAmelCase    (     self       : str ,						lowerCAmelCase_       : Union[str, Any]  )			->		int:
						if not self.legacy:
									__A=  text.startswith(lowerCAmelCase_  )
									if is_first:
												__A=  text[1:]

						__A=  self.sp_model.encode(lowerCAmelCase_ ,						out_type=lowerCAmelCase_  )

						if not self.legacy and not is_first and not text.startswith(' '  ) and tokens[0].startswith(lowerCAmelCase_  ):
									__A=  ([tokens[0][1:]] if len(tokens[0]  ) > 1 else []) + tokens[1:]
						return tokens
			def 				lowerCAmelCase    (     self       : List[Any] ,						lowerCAmelCase_       : List[Any]  )			->		List[str]:
						return self.sp_model.piece_to_id(lowerCAmelCase_  )
			def 				lowerCAmelCase    (     self       : Optional[int] ,						lowerCAmelCase_       : Dict  )			->		int:
						__A=  self.sp_model.IdToPiece(lowerCAmelCase_  )
						return token
			def 				lowerCAmelCase    (     self       : Any ,						lowerCAmelCase_       : Optional[Any]  )			->		Optional[Any]:
						__A=  []
						__A=  ''
						__A=  False
						for i, token in enumerate(lowerCAmelCase_  ):
									# 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(lowerCAmelCase_  ) + token
												__A=  True
												__A=  []
									else:
												current_sub_tokens.append(lowerCAmelCase_  )
												__A=  False
						out_string += self.sp_model.decode(lowerCAmelCase_  )
						return out_string
			def 				lowerCAmelCase    (     self       : Union[str, Any] ,						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,)
			def 				lowerCAmelCase    (     self       : List[Any] ,						lowerCAmelCase_       : Dict ,						lowerCAmelCase_       : Union[str, Any]=None  )			->		Any:
						__A=  [self.bos_token_id] if self.add_bos_token else []
						__A=  [self.eos_token_id] if self.add_eos_token else []

						__A=  bos_token_id + token_ids_a + eos_token_id

						if token_ids_a is not None:
									__A=  output + bos_token_id + token_ids_a + eos_token_id

						return output
			def 				lowerCAmelCase    (     self       : Any ,						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_  )

						__A=  [1] if self.add_bos_token else []
						__A=  [1] if self.add_eos_token else []

						if token_ids_a is None:
									return bos_token_id + ([0] * len(lowerCAmelCase_  )) + eos_token_id
						return (
						    bos_token_id
						    + ([0] * len(lowerCAmelCase_  ))
						    + eos_token_id
						    + bos_token_id
						    + ([0] * len(lowerCAmelCase_  ))
						    + eos_token_id
						)
			def 				lowerCAmelCase    (     self       : List[str] ,						lowerCAmelCase_       : List[int] ,						lowerCAmelCase_       : Optional[List[int]] = None  )			->		List[int]:
						__A=  [self.bos_token_id] if self.add_bos_token else []
						__A=  [self.eos_token_id] if self.add_eos_token else []

						__A=  [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 				lowerCAmelCase    (     self       : Dict ,						lowerCAmelCase_       : "Conversation"  )			->		List[int]:
						__A=  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...)'  )

						__A=  []
						if len(conversation.past_user_inputs  ) > 0:
									if not conversation.past_user_inputs[0].startswith(lowerCAmelCase_  ) or E_SYS not in conversation.past_user_inputs[0]:
												__A=  (
												    B_SYS + DEFAULT_SYSTEM_PROMPT + E_SYS + conversation.past_user_inputs[0]
												)
						elif not dialogue[0][1].startswith(lowerCAmelCase_  ) or E_SYS not in dialogue[0][1]:
									__A=  (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=lowerCAmelCase_  )
						        + [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=lowerCAmelCase_  )
						return dialog_tokens







'''simple docstring'''





from collections import OrderedDict
from typing import Mapping

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


UpperCAmelCase__      =							logging.get_logger(__name__)

UpperCAmelCase__      =							{
    '''google/mobilebert-uncased''': '''https://huggingface.co/google/mobilebert-uncased/resolve/main/config.json'''
}
class 	a__				(				a_      ):





			'''simple docstring'''

			A	:							int							= MOBILEBERT_PRETRAINED_CONFIG_ARCHIVE_MAP
			A	:							Optional[int]							= '''mobilebert'''
			def __init__(     self       : Optional[int] ,						lowerCAmelCase_       : str=30_522 ,						lowerCAmelCase_       : List[Any]=512 ,						lowerCAmelCase_       : Optional[int]=24 ,						lowerCAmelCase_       : str=4 ,						lowerCAmelCase_       : List[str]=512 ,						lowerCAmelCase_       : List[str]="relu" ,						lowerCAmelCase_       : Dict=0.0 ,						lowerCAmelCase_       : List[Any]=0.1 ,						lowerCAmelCase_       : Optional[Any]=512 ,						lowerCAmelCase_       : str=2 ,						lowerCAmelCase_       : Dict=0.02 ,						lowerCAmelCase_       : Any=1E-12 ,						lowerCAmelCase_       : List[Any]=0 ,						lowerCAmelCase_       : Union[str, Any]=128 ,						lowerCAmelCase_       : Any=True ,						lowerCAmelCase_       : Optional[Any]=True ,						lowerCAmelCase_       : List[Any]=128 ,						lowerCAmelCase_       : Dict=False ,						lowerCAmelCase_       : Tuple=True ,						lowerCAmelCase_       : Any=4 ,						lowerCAmelCase_       : Optional[Any]="no_norm" ,						lowerCAmelCase_       : Optional[Any]=True ,						lowerCAmelCase_       : Union[str, Any]=None ,						**lowerCAmelCase_       : Union[str, Any] ,						)			->		List[Any]:
						super().__init__(pad_token_id=lowerCAmelCase_ ,						**lowerCAmelCase_  )

						__A=  vocab_size
						__A=  hidden_size
						__A=  num_hidden_layers
						__A=  num_attention_heads
						__A=  hidden_act
						__A=  intermediate_size
						__A=  hidden_dropout_prob
						__A=  attention_probs_dropout_prob
						__A=  max_position_embeddings
						__A=  type_vocab_size
						__A=  initializer_range
						__A=  layer_norm_eps
						__A=  embedding_size
						__A=  trigram_input
						__A=  use_bottleneck
						__A=  intra_bottleneck_size
						__A=  use_bottleneck_attention
						__A=  key_query_shared_bottleneck
						__A=  num_feedforward_networks
						__A=  normalization_type
						__A=  classifier_activation

						if self.use_bottleneck:
									__A=  intra_bottleneck_size
						else:
									__A=  hidden_size

						__A=  classifier_dropout


class 	a__				(				a_      ):





			'''simple docstring'''

			@property
			def 				lowerCAmelCase    (     self       : List[str]  )			->		Mapping[str, Mapping[int, str]]:
						if self.task == "multiple-choice":
									__A=  {0: 'batch', 1: 'choice', 2: 'sequence'}
						else:
									__A=  {0: 'batch', 1: 'sequence'}
						return OrderedDict(
						    [
						        ('input_ids', dynamic_axis),
						        ('attention_mask', dynamic_axis),
						        ('token_type_ids', dynamic_axis),
						    ]  )



