tokenization_qwen2.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  1. # coding=utf-8
  2. # Copyright 2024 The Qwen team, Alibaba Group and The HuggingFace Inc. team. All rights reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. """Tokenization classes for Qwen2."""
  16. import json
  17. import os
  18. import unicodedata
  19. from functools import lru_cache
  20. from typing import Optional
  21. import regex as re
  22. from ...tokenization_utils import AddedToken, PreTrainedTokenizer
  23. from ...utils import logging
  24. logger = logging.get_logger(__name__)
  25. VOCAB_FILES_NAMES = {
  26. "vocab_file": "vocab.json",
  27. "merges_file": "merges.txt",
  28. }
  29. MAX_MODEL_INPUT_SIZES = {"qwen/qwen-tokenizer": 32768}
  30. PRETOKENIZE_REGEX = r"""(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\r\n\p{L}\p{N}]?\p{L}+|\p{N}| ?[^\s\p{L}\p{N}]+[\r\n]*|\s*[\r\n]+|\s+(?!\S)|\s+"""
  31. @lru_cache
  32. # Copied from transformers.models.gpt2.tokenization_gpt2.bytes_to_unicode
  33. def bytes_to_unicode():
  34. """
  35. Returns list of utf-8 byte and a mapping to unicode strings. We specifically avoids mapping to whitespace/control
  36. characters the bpe code barfs on.
  37. The reversible bpe codes work on unicode strings. This means you need a large # of unicode characters in your vocab
  38. if you want to avoid UNKs. When you're at something like a 10B token dataset you end up needing around 5K for
  39. decent coverage. This is a significant percentage of your normal, say, 32K bpe vocab. To avoid that, we want lookup
  40. tables between utf-8 bytes and unicode strings.
  41. """
  42. bs = (
  43. list(range(ord("!"), ord("~") + 1)) + list(range(ord("¡"), ord("¬") + 1)) + list(range(ord("®"), ord("ÿ") + 1))
  44. )
  45. cs = bs[:]
  46. n = 0
  47. for b in range(2**8):
  48. if b not in bs:
  49. bs.append(b)
  50. cs.append(2**8 + n)
  51. n += 1
  52. cs = [chr(n) for n in cs]
  53. return dict(zip(bs, cs))
  54. # Copied from transformers.models.gpt2.tokenization_gpt2.get_pairs
  55. def get_pairs(word):
  56. """
  57. Return set of symbol pairs in a word.
  58. Word is represented as tuple of symbols (symbols being variable-length strings).
  59. """
  60. pairs = set()
  61. prev_char = word[0]
  62. for char in word[1:]:
  63. pairs.add((prev_char, char))
  64. prev_char = char
  65. return pairs
  66. class Qwen2Tokenizer(PreTrainedTokenizer):
  67. """
  68. Construct a Qwen2 tokenizer. Based on byte-level Byte-Pair-Encoding.
  69. Same with GPT2Tokenizer, this tokenizer has been trained to treat spaces like parts of the tokens so a word will
  70. be encoded differently whether it is at the beginning of the sentence (without space) or not:
  71. ```python
  72. >>> from transformers import Qwen2Tokenizer
  73. >>> tokenizer = Qwen2Tokenizer.from_pretrained("Qwen/Qwen-tokenizer")
  74. >>> tokenizer("Hello world")["input_ids"]
  75. [9707, 1879]
  76. >>> tokenizer(" Hello world")["input_ids"]
  77. [21927, 1879]
  78. ```
  79. This is expected.
  80. You should not use GPT2Tokenizer instead, because of the different pretokenization rules.
  81. This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
  82. this superclass for more information regarding those methods.
  83. Args:
  84. vocab_file (`str`):
  85. Path to the vocabulary file.
  86. merges_file (`str`):
  87. Path to the merges file.
  88. errors (`str`, *optional*, defaults to `"replace"`):
  89. Paradigm to follow when decoding bytes to UTF-8. See
  90. [bytes.decode](https://docs.python.org/3/library/stdtypes.html#bytes.decode) for more information.
  91. unk_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
  92. The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
  93. token instead.
  94. bos_token (`str`, *optional*):
  95. The beginning of sequence token. Not applicable for this tokenizer.
  96. eos_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
  97. The end of sequence token.
  98. pad_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
  99. The token used for padding, for example when batching sequences of different lengths.
  100. clean_up_tokenization_spaces (`bool`, *optional*, defaults to `False`):
  101. Whether or not the model should cleanup the spaces that were added when splitting the input text during the
  102. tokenization process. Not applicable to this tokenizer, since tokenization does not add spaces.
  103. split_special_tokens (`bool`, *optional*, defaults to `False`):
  104. Whether or not the special tokens should be split during the tokenization process. The default behavior is
  105. to not split special tokens. This means that if `<|endoftext|>` is the `eos_token`, then `tokenizer.tokenize("<|endoftext|>") =
  106. ['<|endoftext|>`]. Otherwise, if `split_special_tokens=True`, then `tokenizer.tokenize("<|endoftext|>")` will be give `['<',
  107. '|', 'endo', 'ft', 'ext', '|', '>']`. This argument is only supported for `slow` tokenizers for the moment.
  108. """
  109. vocab_files_names = VOCAB_FILES_NAMES
  110. model_input_names = ["input_ids", "attention_mask"]
  111. def __init__(
  112. self,
  113. vocab_file,
  114. merges_file,
  115. errors="replace",
  116. unk_token="<|endoftext|>",
  117. bos_token=None,
  118. eos_token="<|endoftext|>",
  119. pad_token="<|endoftext|>",
  120. clean_up_tokenization_spaces=False,
  121. split_special_tokens=False,
  122. **kwargs,
  123. ):
  124. # Qwen vocab does not contain control tokens; added tokens need to be special
  125. bos_token = (
  126. AddedToken(bos_token, lstrip=False, rstrip=False, special=True, normalized=False)
  127. if isinstance(bos_token, str)
  128. else bos_token
  129. )
  130. eos_token = (
  131. AddedToken(eos_token, lstrip=False, rstrip=False, special=True, normalized=False)
  132. if isinstance(eos_token, str)
  133. else eos_token
  134. )
  135. unk_token = (
  136. AddedToken(unk_token, lstrip=False, rstrip=False, special=True, normalized=False)
  137. if isinstance(unk_token, str)
  138. else unk_token
  139. )
  140. pad_token = (
  141. AddedToken(pad_token, lstrip=False, rstrip=False, special=True, normalized=False)
  142. if isinstance(pad_token, str)
  143. else pad_token
  144. )
  145. with open(vocab_file, encoding="utf-8") as vocab_handle:
  146. self.encoder = json.load(vocab_handle)
  147. self.decoder = {v: k for k, v in self.encoder.items()}
  148. self.errors = errors # how to handle errors in decoding
  149. self.byte_encoder = bytes_to_unicode()
  150. self.byte_decoder = {v: k for k, v in self.byte_encoder.items()}
  151. bpe_merges = []
  152. with open(merges_file, encoding="utf-8") as merges_handle:
  153. for i, line in enumerate(merges_handle):
  154. line = line.strip()
  155. if (i == 0 and line.startswith("#version:")) or not line:
  156. continue
  157. bpe_merges.append(tuple(line.split()))
  158. self.bpe_ranks = dict(zip(bpe_merges, range(len(bpe_merges))))
  159. # NOTE: the cache can grow without bound and will get really large for long running processes
  160. # (esp. for texts of language that do not use space between word, e.g. Chinese); technically
  161. # not a memory leak but appears as one.
  162. # GPT2Tokenizer has the same problem, so let's be consistent.
  163. self.cache = {}
  164. self.pat = re.compile(PRETOKENIZE_REGEX)
  165. if kwargs.get("add_prefix_space", False):
  166. logger.warning_once(
  167. f"{self.__class__.__name} does not support `add_prefix_space`, setting it to True has no effect."
  168. )
  169. super().__init__(
  170. errors=errors,
  171. bos_token=bos_token,
  172. eos_token=eos_token,
  173. pad_token=pad_token,
  174. unk_token=unk_token,
  175. clean_up_tokenization_spaces=clean_up_tokenization_spaces,
  176. split_special_tokens=split_special_tokens,
  177. **kwargs,
  178. )
  179. @property
  180. def vocab_size(self) -> int:
  181. return len(self.encoder)
  182. # Copied from transformers.models.gpt2.tokenization_gpt2.GPT2Tokenizer.get_vocab
  183. def get_vocab(self):
  184. return dict(self.encoder, **self.added_tokens_encoder)
  185. # Copied from transformers.models.gpt2.tokenization_gpt2.GPT2Tokenizer.bpe
  186. def bpe(self, token):
  187. if token in self.cache:
  188. return self.cache[token]
  189. word = tuple(token)
  190. pairs = get_pairs(word)
  191. if not pairs:
  192. return token
  193. while True:
  194. bigram = min(pairs, key=lambda pair: self.bpe_ranks.get(pair, float("inf")))
  195. if bigram not in self.bpe_ranks:
  196. break
  197. first, second = bigram
  198. new_word = []
  199. i = 0
  200. while i < len(word):
  201. try:
  202. j = word.index(first, i)
  203. except ValueError:
  204. new_word.extend(word[i:])
  205. break
  206. else:
  207. new_word.extend(word[i:j])
  208. i = j
  209. if word[i] == first and i < len(word) - 1 and word[i + 1] == second:
  210. new_word.append(first + second)
  211. i += 2
  212. else:
  213. new_word.append(word[i])
  214. i += 1
  215. new_word = tuple(new_word)
  216. word = new_word
  217. if len(word) == 1:
  218. break
  219. else:
  220. pairs = get_pairs(word)
  221. word = " ".join(word)
  222. self.cache[token] = word
  223. return word
  224. # Copied from transformers.models.gpt2.tokenization_gpt2.GPT2Tokenizer._tokenize
  225. def _tokenize(self, text):
  226. """Tokenize a string."""
  227. bpe_tokens = []
  228. for token in re.findall(self.pat, text):
  229. token = "".join(
  230. self.byte_encoder[b] for b in token.encode("utf-8")
  231. ) # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case)
  232. bpe_tokens.extend(bpe_token for bpe_token in self.bpe(token).split(" "))
  233. return bpe_tokens
  234. # Copied from transformers.models.gpt2.tokenization_gpt2.GPT2Tokenizer._convert_token_to_id
  235. def _convert_token_to_id(self, token):
  236. """Converts a token (str) in an id using the vocab."""
  237. return self.encoder.get(token, self.encoder.get(self.unk_token))
  238. # Copied from transformers.models.gpt2.tokenization_gpt2.GPT2Tokenizer._convert_id_to_token
  239. def _convert_id_to_token(self, index):
  240. """Converts an index (integer) in a token (str) using the vocab."""
  241. return self.decoder.get(index)
  242. # Copied from transformers.models.gpt2.tokenization_gpt2.GPT2Tokenizer.convert_tokens_to_string
  243. def convert_tokens_to_string(self, tokens):
  244. """Converts a sequence of tokens (string) in a single string."""
  245. text = "".join(tokens)
  246. text = bytearray([self.byte_decoder[c] for c in text]).decode("utf-8", errors=self.errors)
  247. return text
  248. def decode(
  249. self,
  250. token_ids,
  251. skip_special_tokens: bool = False,
  252. clean_up_tokenization_spaces: Optional[bool] = False,
  253. spaces_between_special_tokens: bool = False,
  254. **kwargs,
  255. ) -> str:
  256. # `spaces_between_special_tokens` defaults to True for _decode in slow tokenizers
  257. # and cannot be configured elsewhere, but it should default to False for Qwen2Tokenizer
  258. return super().decode(
  259. token_ids,
  260. skip_special_tokens=skip_special_tokens,
  261. clean_up_tokenization_spaces=clean_up_tokenization_spaces,
  262. spaces_between_special_tokens=spaces_between_special_tokens,
  263. **kwargs,
  264. )
  265. # Copied from transformers.models.gpt2.tokenization_gpt2.GPT2Tokenizer.save_vocabulary
  266. def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> tuple[str]:
  267. if not os.path.isdir(save_directory):
  268. logger.error(f"Vocabulary path ({save_directory}) should be a directory")
  269. return
  270. vocab_file = os.path.join(
  271. save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
  272. )
  273. merge_file = os.path.join(
  274. save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["merges_file"]
  275. )
  276. with open(vocab_file, "w", encoding="utf-8") as f:
  277. f.write(json.dumps(self.encoder, indent=2, sort_keys=True, ensure_ascii=False) + "\n")
  278. index = 0
  279. with open(merge_file, "w", encoding="utf-8") as writer:
  280. writer.write("#version: 0.2\n")
  281. for bpe_tokens, token_index in sorted(self.bpe_ranks.items(), key=lambda kv: kv[1]):
  282. if index != token_index:
  283. logger.warning(
  284. f"Saving vocabulary to {merge_file}: BPE merge indices are not consecutive."
  285. " Please check that the tokenizer is not corrupted!"
  286. )
  287. index = token_index
  288. writer.write(" ".join(bpe_tokens) + "\n")
  289. index += 1
  290. return vocab_file, merge_file
  291. def prepare_for_tokenization(self, text, **kwargs):
  292. text = unicodedata.normalize("NFC", text)
  293. return (text, kwargs)
  294. __all__ = ["Qwen2Tokenizer"]