tokenization_llama.py 18 KB

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