tokenization_llama.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  1. # coding=utf-8
  2. # Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
  3. #
  4. # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
  5. # and OPT implementations in this library. It has been modified from its
  6. # original forms to accommodate minor architectural differences compared
  7. # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
  8. #
  9. # Licensed under the Apache License, Version 2.0 (the "License");
  10. # you may not use this file except in compliance with the License.
  11. # You may obtain a copy of the License at
  12. #
  13. # http://www.apache.org/licenses/LICENSE-2.0
  14. #
  15. # Unless required by applicable law or agreed to in writing, software
  16. # distributed under the License is distributed on an "AS IS" BASIS,
  17. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  18. # See the License for the specific language governing permissions and
  19. # limitations under the License.
  20. """Tokenization classes for LLaMA."""
  21. import os
  22. from shutil import copyfile
  23. from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple
  24. import sentencepiece as spm
  25. from ...convert_slow_tokenizer import import_protobuf
  26. from ...tokenization_utils import AddedToken, PreTrainedTokenizer
  27. from ...utils import logging
  28. if TYPE_CHECKING:
  29. from ...tokenization_utils_base import TextInput
  30. logger = logging.get_logger(__name__)
  31. VOCAB_FILES_NAMES = {"vocab_file": "tokenizer.model"}
  32. SPIECE_UNDERLINE = "▁"
  33. B_INST, E_INST = "[INST]", "[/INST]"
  34. B_SYS, E_SYS = "<<SYS>>\n", "\n<</SYS>>\n\n"
  35. DEFAULT_SYSTEM_PROMPT = """You are a helpful, respectful and honest assistant. Always answer as helpfully as possible, while being safe. Your \
  36. answers should not include any harmful, unethical, racist, sexist, toxic, dangerous, or illegal content. Please ensure\
  37. that your responses are socially unbiased and positive in nature.
  38. If a question does not make any sense, or is not factually coherent, explain why instead of answering something not \
  39. correct. If you don't know the answer to a question, please don't share false information.""" # fmt: skip
  40. class LlamaTokenizer(PreTrainedTokenizer):
  41. """
  42. Construct a Llama tokenizer. Based on byte-level Byte-Pair-Encoding. The default padding token is unset as there is
  43. no padding token in the original model.
  44. Args:
  45. vocab_file (`str`):
  46. Path to the vocabulary file.
  47. unk_token (`str` or `tokenizers.AddedToken`, *optional*, defaults to `"<unk>"`):
  48. The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
  49. token instead.
  50. bos_token (`str` or `tokenizers.AddedToken`, *optional*, defaults to `"<s>"`):
  51. The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.
  52. eos_token (`str` or `tokenizers.AddedToken`, *optional*, defaults to `"</s>"`):
  53. The end of sequence token.
  54. pad_token (`str` or `tokenizers.AddedToken`, *optional*):
  55. A special token used to make arrays of tokens the same size for batching purpose. Will then be ignored by
  56. attention mechanisms or loss computation.
  57. sp_model_kwargs (`Dict[str, Any]`, `Optional`, *optional*):
  58. Will be passed to the `SentencePieceProcessor.__init__()` method. The [Python wrapper for
  59. SentencePiece](https://github.com/google/sentencepiece/tree/master/python) can be used, among other things,
  60. to set:
  61. - `enable_sampling`: Enable subword regularization.
  62. - `nbest_size`: Sampling parameters for unigram. Invalid for BPE-Dropout.
  63. - `nbest_size = {0,1}`: No sampling is performed.
  64. - `nbest_size > 1`: samples from the nbest_size results.
  65. - `nbest_size < 0`: assuming that nbest_size is infinite and samples from the all hypothesis (lattice)
  66. using forward-filtering-and-backward-sampling algorithm.
  67. - `alpha`: Smoothing parameter for unigram sampling, and dropout probability of merge operations for
  68. BPE-dropout.
  69. add_bos_token (`bool`, *optional*, defaults to `True`):
  70. Whether or not to add an `bos_token` at the start of sequences.
  71. add_eos_token (`bool`, *optional*, defaults to `False`):
  72. Whether or not to add an `eos_token` at the end of sequences.
  73. clean_up_tokenization_spaces (`bool`, *optional*, defaults to `False`):
  74. Whether or not to cleanup spaces after decoding, cleanup consists in removing potential artifacts like
  75. extra spaces.
  76. use_default_system_prompt (`bool`, *optional*, defaults to `False`):
  77. Whether or not the default system prompt for Llama should be used.
  78. spaces_between_special_tokens (`bool`, *optional*, defaults to `False`):
  79. Whether or not to add spaces between special tokens.
  80. legacy (`bool`, *optional*):
  81. Whether or not the `legacy` behavior of the tokenizer should be used. Legacy is before the merge of #24622
  82. and #25224 which includes fixes to properly handle tokens that appear after special tokens.
  83. Make sure to also set `from_slow` to `True`.
  84. A simple example:
  85. - `legacy=True`:
  86. ```python
  87. >>> from transformers import LlamaTokenizerFast
  88. >>> tokenizer = LlamaTokenizerFast.from_pretrained("huggyllama/llama-7b", legacy=True, from_slow=True)
  89. >>> tokenizer.encode("Hello <s>.") # 869 is '▁.'
  90. [1, 15043, 29871, 1, 869]
  91. ```
  92. - `legacy=False`:
  93. ```python
  94. >>> from transformers import LlamaTokenizerFast
  95. >>> tokenizer = LlamaTokenizerFast.from_pretrained("huggyllama/llama-7b", legacy=False, from_slow=True)
  96. >>> tokenizer.encode("Hello <s>.") # 29889 is '.'
  97. [1, 15043, 29871, 1, 29889]
  98. ```
  99. Checkout the [pull request](https://github.com/huggingface/transformers/pull/24565) for more details.
  100. add_prefix_space (`bool`, *optional*, defaults to `True`):
  101. Whether or not to add an initial space to the input. This allows to treat the leading word just as any
  102. other word. Again, this should be set with `from_slow=True` to make sure it's taken into account.
  103. """
  104. vocab_files_names = VOCAB_FILES_NAMES
  105. model_input_names = ["input_ids", "attention_mask"]
  106. def __init__(
  107. self,
  108. vocab_file,
  109. unk_token="<unk>",
  110. bos_token="<s>",
  111. eos_token="</s>",
  112. pad_token=None,
  113. sp_model_kwargs: Optional[Dict[str, Any]] = None,
  114. add_bos_token=True,
  115. add_eos_token=False,
  116. clean_up_tokenization_spaces=False,
  117. use_default_system_prompt=False,
  118. spaces_between_special_tokens=False,
  119. legacy=None,
  120. add_prefix_space=True,
  121. **kwargs,
  122. ):
  123. self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs
  124. bos_token = AddedToken(bos_token, normalized=False, special=True) if isinstance(bos_token, str) else bos_token
  125. eos_token = AddedToken(eos_token, normalized=False, special=True) if isinstance(eos_token, str) else eos_token
  126. unk_token = AddedToken(unk_token, normalized=False, special=True) if isinstance(unk_token, str) else unk_token
  127. pad_token = AddedToken(pad_token, normalized=False, special=True) if isinstance(pad_token, str) else pad_token
  128. if legacy is None:
  129. logger.warning_once(
  130. f"You are using the default legacy behaviour of the {self.__class__}. This is"
  131. " expected, and simply means that the `legacy` (previous) behavior will be used so nothing changes for you."
  132. " If you want to use the new behaviour, set `legacy=False`. This should only be set if you understand what it"
  133. " means, and thoroughly read the reason why this was added as explained in"
  134. " https://github.com/huggingface/transformers/pull/24565 - if you loaded a llama tokenizer from a GGUF file"
  135. " you can ignore this message"
  136. )
  137. legacy = True
  138. self.legacy = legacy
  139. self.vocab_file = vocab_file
  140. self.add_bos_token = add_bos_token
  141. self.add_eos_token = add_eos_token
  142. self.use_default_system_prompt = use_default_system_prompt
  143. self.sp_model = self.get_spm_processor(kwargs.pop("from_slow", False))
  144. self.add_prefix_space = add_prefix_space
  145. super().__init__(
  146. bos_token=bos_token,
  147. eos_token=eos_token,
  148. unk_token=unk_token,
  149. pad_token=pad_token,
  150. add_bos_token=add_bos_token,
  151. add_eos_token=add_eos_token,
  152. sp_model_kwargs=self.sp_model_kwargs,
  153. clean_up_tokenization_spaces=clean_up_tokenization_spaces,
  154. use_default_system_prompt=use_default_system_prompt,
  155. spaces_between_special_tokens=spaces_between_special_tokens,
  156. legacy=legacy,
  157. add_prefix_space=add_prefix_space,
  158. **kwargs,
  159. )
  160. @property
  161. def unk_token_length(self):
  162. return len(self.sp_model.encode(str(self.unk_token)))
  163. # Copied from transformers.models.t5.tokenization_t5.T5Tokenizer.get_spm_processor
  164. def get_spm_processor(self, from_slow=False):
  165. tokenizer = spm.SentencePieceProcessor(**self.sp_model_kwargs)
  166. if self.legacy or from_slow: # no dependency on protobuf
  167. tokenizer.Load(self.vocab_file)
  168. return tokenizer
  169. with open(self.vocab_file, "rb") as f:
  170. sp_model = f.read()
  171. model_pb2 = import_protobuf(f"The new behaviour of {self.__class__.__name__} (with `self.legacy = False`)")
  172. model = model_pb2.ModelProto.FromString(sp_model)
  173. normalizer_spec = model_pb2.NormalizerSpec()
  174. normalizer_spec.add_dummy_prefix = False
  175. model.normalizer_spec.MergeFrom(normalizer_spec)
  176. sp_model = model.SerializeToString()
  177. tokenizer.LoadFromSerializedProto(sp_model)
  178. return tokenizer
  179. def __getstate__(self):
  180. state = self.__dict__.copy()
  181. state["sp_model"] = None
  182. state["sp_model_proto"] = self.sp_model.serialized_model_proto()
  183. return state
  184. def __setstate__(self, d):
  185. self.__dict__ = d
  186. self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
  187. self.sp_model.LoadFromSerializedProto(self.sp_model_proto)
  188. @property
  189. def vocab_size(self):
  190. """Returns vocab size"""
  191. return self.sp_model.get_piece_size()
  192. def get_vocab(self):
  193. """Returns vocab as a dict"""
  194. vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size)}
  195. vocab.update(self.added_tokens_encoder)
  196. return vocab
  197. # Copied from transformers.models.t5.tokenization_t5.T5Tokenizer.tokenize
  198. def tokenize(self, text: "TextInput", **kwargs) -> List[str]:
  199. """
  200. Converts a string to a list of tokens. If `self.legacy` is set to `False`, a prefix token is added unless the
  201. first token is special.
  202. """
  203. if self.legacy or len(text) == 0:
  204. return super().tokenize(text, **kwargs)
  205. text = text.replace(SPIECE_UNDERLINE, " ")
  206. if self.add_prefix_space:
  207. text = SPIECE_UNDERLINE + text
  208. tokens = super().tokenize(text, **kwargs)
  209. if len(tokens) > 1 and tokens[0] == SPIECE_UNDERLINE and tokens[1] in self.all_special_tokens:
  210. tokens = tokens[1:]
  211. return tokens
  212. # Copied from transformers.models.t5.tokenization_t5.T5Tokenizer._tokenize
  213. def _tokenize(self, text, **kwargs):
  214. """
  215. Returns a tokenized string.
  216. We de-activated the `add_dummy_prefix` option, thus the sentencepiece internals will always strip any
  217. SPIECE_UNDERLINE. For example: `self.sp_model.encode(f"{SPIECE_UNDERLINE}Hey", out_type = str)` will give
  218. `['H', 'e', 'y']` instead of `['▁He', 'y']`. Thus we always encode `f"{unk_token}text"` and strip the
  219. `unk_token`. Here is an example with `unk_token = "<unk>"` and `unk_token_length = 4`.
  220. `self.tokenizer.sp_model.encode("<unk> Hey", out_type = str)[4:]`.
  221. """
  222. if self.legacy or not text.startswith((SPIECE_UNDERLINE, " ")):
  223. return self.sp_model.encode(text, out_type=str)
  224. # 1. Encode string + prefix ex: "<unk> Hey"
  225. tokens = self.sp_model.encode(self.unk_token + text, out_type=str)
  226. # 2. Remove self.unk_token from ['<','unk','>', '▁Hey']
  227. return tokens[self.unk_token_length :] if len(tokens) >= self.unk_token_length else tokens
  228. def _convert_token_to_id(self, token):
  229. """Converts a token (str) in an id using the vocab."""
  230. return self.sp_model.piece_to_id(token)
  231. def _convert_id_to_token(self, index):
  232. """Converts an index (integer) in a token (str) using the vocab."""
  233. token = self.sp_model.IdToPiece(index)
  234. return token
  235. def convert_tokens_to_string(self, tokens):
  236. """Converts a sequence of tokens (string) in a single string."""
  237. # since we manually add the prefix space, we have to remove it when decoding
  238. if tokens[0].startswith(SPIECE_UNDERLINE) and self.add_prefix_space:
  239. tokens[0] = tokens[0][1:]
  240. current_sub_tokens = []
  241. out_string = ""
  242. prev_is_special = False
  243. for i, token in enumerate(tokens):
  244. # make sure that special tokens are not decoded using sentencepiece model
  245. if token in self.all_special_tokens:
  246. if not prev_is_special and i != 0 and self.legacy:
  247. out_string += " "
  248. out_string += self.sp_model.decode(current_sub_tokens) + token
  249. prev_is_special = True
  250. current_sub_tokens = []
  251. else:
  252. if prev_is_special and i == 1 and self.add_prefix_space and not token.startswith(SPIECE_UNDERLINE):
  253. out_string += " "
  254. current_sub_tokens.append(token)
  255. prev_is_special = False
  256. out_string += self.sp_model.decode(current_sub_tokens)
  257. return out_string
  258. def save_vocabulary(self, save_directory, filename_prefix: Optional[str] = None) -> Tuple[str]:
  259. """
  260. Save the vocabulary and special tokens file to a directory.
  261. Args:
  262. save_directory (`str`):
  263. The directory in which to save the vocabulary.
  264. Returns:
  265. `Tuple(str)`: Paths to the files saved.
  266. """
  267. if not os.path.isdir(save_directory):
  268. logger.error(f"Vocabulary path ({save_directory}) should be a directory")
  269. return
  270. out_vocab_file = os.path.join(
  271. save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
  272. )
  273. if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file) and os.path.isfile(self.vocab_file):
  274. copyfile(self.vocab_file, out_vocab_file)
  275. elif not os.path.isfile(self.vocab_file):
  276. with open(out_vocab_file, "wb") as fi:
  277. content_spiece_model = self.sp_model.serialized_model_proto()
  278. fi.write(content_spiece_model)
  279. return (out_vocab_file,)
  280. def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
  281. bos_token_id = [self.bos_token_id] if self.add_bos_token else []
  282. eos_token_id = [self.eos_token_id] if self.add_eos_token else []
  283. output = bos_token_id + token_ids_0 + eos_token_id
  284. if token_ids_1 is not None:
  285. output = output + bos_token_id + token_ids_1 + eos_token_id
  286. return output
  287. def get_special_tokens_mask(
  288. self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
  289. ) -> List[int]:
  290. """
  291. Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
  292. special tokens using the tokenizer `prepare_for_model` method.
  293. Args:
  294. token_ids_0 (`List[int]`):
  295. List of IDs.
  296. token_ids_1 (`List[int]`, *optional*):
  297. Optional second list of IDs for sequence pairs.
  298. already_has_special_tokens (`bool`, *optional*, defaults to `False`):
  299. Whether or not the token list is already formatted with special tokens for the model.
  300. Returns:
  301. `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
  302. """
  303. if already_has_special_tokens:
  304. return super().get_special_tokens_mask(
  305. token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
  306. )
  307. bos_token_id = [1] if self.add_bos_token else []
  308. eos_token_id = [1] if self.add_eos_token else []
  309. if token_ids_1 is None:
  310. return bos_token_id + ([0] * len(token_ids_0)) + eos_token_id
  311. return (
  312. bos_token_id
  313. + ([0] * len(token_ids_0))
  314. + eos_token_id
  315. + bos_token_id
  316. + ([0] * len(token_ids_1))
  317. + eos_token_id
  318. )
  319. def create_token_type_ids_from_sequences(
  320. self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
  321. ) -> List[int]:
  322. """
  323. Creates a mask from the two sequences passed to be used in a sequence-pair classification task. An ALBERT
  324. sequence pair mask has the following format:
  325. ```
  326. 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
  327. | first sequence | second sequence |
  328. ```
  329. if token_ids_1 is None, only returns the first portion of the mask (0s).
  330. Args:
  331. token_ids_0 (`List[int]`):
  332. List of ids.
  333. token_ids_1 (`List[int]`, *optional*):
  334. Optional second list of IDs for sequence pairs.
  335. Returns:
  336. `List[int]`: List of [token type IDs](../glossary#token-type-ids) according to the given sequence(s).
  337. """
  338. bos_token_id = [self.bos_token_id] if self.add_bos_token else []
  339. eos_token_id = [self.eos_token_id] if self.add_eos_token else []
  340. output = [0] * len(bos_token_id + token_ids_0 + eos_token_id)
  341. if token_ids_1 is not None:
  342. output += [1] * len(bos_token_id + token_ids_1 + eos_token_id)
  343. return output