tokenization_llama.py 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149
  1. # Copyright 2020 The HuggingFace Inc. team.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. from tokenizers import Tokenizer, decoders, pre_tokenizers
  15. from tokenizers.models import BPE
  16. from ...tokenization_utils_base import _get_prepend_scheme
  17. from ...tokenization_utils_tokenizers import TokenizersBackend
  18. from ...utils import logging
  19. logger = logging.get_logger(__name__)
  20. VOCAB_FILES_NAMES = {"vocab_file": "tokenizer.model", "tokenizer_file": "tokenizer.json"}
  21. B_INST, E_INST = "[INST]", "[/INST]"
  22. B_SYS, E_SYS = "<<SYS>>\n", "\n<</SYS>>\n\n"
  23. # fmt: off
  24. DEFAULT_SYSTEM_PROMPT = """You are a helpful, respectful and honest assistant. Always answer as helpfully as possible, while being safe. Your \
  25. answers should not include any harmful, unethical, racist, sexist, toxic, dangerous, or illegal content. Please ensure\
  26. that your responses are socially unbiased and positive in nature.
  27. If a question does not make any sense, or is not factually coherent, explain why instead of answering something not \
  28. correct. If you don't know the answer to a question, please don't share false information."""
  29. # fmt: on
  30. class LlamaTokenizer(TokenizersBackend):
  31. """
  32. Construct a Llama tokenizer. Based on byte-level Byte-Pair-Encoding.
  33. This uses notably ByteFallback and no normalization.
  34. ```python
  35. >>> from transformers import LlamaTokenizer
  36. >>> tokenizer = LlamaTokenizer.from_pretrained("hf-internal-testing/llama-tokenizer")
  37. >>> tokenizer.encode("Hello this is a test")
  38. [1, 15043, 445, 338, 263, 1243]
  39. ```
  40. If you want to change the `bos_token` or the `eos_token`, make sure to specify them when initializing the model, or
  41. call `tokenizer.update_post_processor()` to make sure that the post-processing is correctly done (otherwise the
  42. values of the first token and final token of an encoded sequence will not be correct). For more details, checkout
  43. [post-processors] (https://huggingface.co/docs/tokenizers/api/post-processors) documentation.
  44. This tokenizer inherits from [`PreTrainedTokenizerFast`] which contains most of the main methods. Users should
  45. refer to this superclass for more information regarding those methods.
  46. Args:
  47. vocab (`str`, `dict` or `list`, *optional*):
  48. Path to the vocabulary file, a dictionary or a list of tokens.
  49. merges (`str` or `list`, *optional*):
  50. Path to the merges file or a list of merges.
  51. clean_up_tokenization_spaces (`bool`, *optional*, defaults to `False`):
  52. Whether or not to cleanup spaces after decoding, cleanup consists in removing potential artifacts like
  53. extra spaces.
  54. unk_token (`str` or `tokenizers.AddedToken`, *optional*, defaults to `"<unk>"`):
  55. The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
  56. token instead.
  57. bos_token (`str` or `tokenizers.AddedToken`, *optional*, defaults to `"<s>"`):
  58. The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.
  59. eos_token (`str` or `tokenizers.AddedToken`, *optional*, defaults to `"</s>"`):
  60. The end of sequence token.
  61. add_bos_token (`bool`, *optional*, defaults to `True`):
  62. Whether or not to add an `bos_token` at the start of sequences.
  63. add_eos_token (`bool`, *optional*, defaults to `False`):
  64. Whether or not to add an `eos_token` at the end of sequences.
  65. use_default_system_prompt (`bool`, *optional*, defaults to `False`):
  66. Whether or not the default system prompt for Llama should be used
  67. add_prefix_space (`bool`, *optional*):
  68. Whether or not the tokenizer should automatically add a prefix space
  69. """
  70. vocab_files_names = VOCAB_FILES_NAMES
  71. padding_side = "left"
  72. model_input_names = ["input_ids", "attention_mask"]
  73. model = BPE
  74. def __init__(
  75. self,
  76. vocab: str | dict | list | None = None,
  77. merges: str | list | None = None,
  78. clean_up_tokenization_spaces=False,
  79. unk_token="<unk>",
  80. bos_token="<s>",
  81. eos_token="</s>",
  82. use_default_system_prompt=False,
  83. legacy=False,
  84. add_prefix_space=None,
  85. **kwargs,
  86. ):
  87. self.add_prefix_space = add_prefix_space if add_prefix_space is not None else True
  88. self.legacy = legacy
  89. self._vocab = vocab
  90. if vocab is None:
  91. self._vocab = {
  92. str(unk_token): 0,
  93. str(bos_token): 1,
  94. str(eos_token): 2,
  95. }
  96. self._merges = merges or []
  97. self._tokenizer = Tokenizer(
  98. BPE(vocab=self._vocab, merges=self._merges, fuse_unk=True, byte_fallback=True, dropout=None)
  99. )
  100. self._tokenizer.normalizer = None
  101. self._tokenizer.pre_tokenizer = pre_tokenizers.Metaspace(
  102. replacement="▁", prepend_scheme=_get_prepend_scheme(self.add_prefix_space, self), split=False
  103. )
  104. sequence = [
  105. decoders.Replace("▁", " "),
  106. decoders.ByteFallback(),
  107. decoders.Fuse(),
  108. ]
  109. if self.add_prefix_space:
  110. sequence += [decoders.Strip(content=" ", left=1)]
  111. self._tokenizer.decoder = decoders.Sequence(sequence)
  112. self.use_default_system_prompt = use_default_system_prompt
  113. super().__init__(
  114. clean_up_tokenization_spaces=clean_up_tokenization_spaces,
  115. unk_token=unk_token,
  116. bos_token=bos_token,
  117. eos_token=eos_token,
  118. use_default_system_prompt=use_default_system_prompt,
  119. add_prefix_space=add_prefix_space,
  120. **kwargs,
  121. )
  122. __all__ = ["LlamaTokenizer", "LlamaTokenizerFast"]
  123. # Backward alias
  124. LlamaTokenizerFast = LlamaTokenizer