qwen2_tokenizer.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430
  1. # Copyright (c) 2024 PaddlePaddle Authors. All Rights Reserved.
  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. import json
  15. import os
  16. import unicodedata
  17. from functools import lru_cache
  18. from typing import List, Optional, Tuple
  19. import regex as re
  20. from .tokenizer_utils import PretrainedTokenizer
  21. from .tokenizer_utils_base import AddedToken, TextInput
  22. VOCAB_FILES_NAMES = {
  23. "vocab_file": "vocab.json",
  24. "merges_file": "merges.txt",
  25. }
  26. __all__ = ["Qwen2Tokenizer", "MIXQwen2Tokenizer"]
  27. MAX_MODEL_INPUT_SIZES = {"qwen/qwen-tokenizer": 32768}
  28. 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+"""
  29. @lru_cache()
  30. def bytes_to_unicode():
  31. """
  32. Returns list of utf-8 byte and a mapping to unicode strings. We specifically avoids mapping to whitespace/control
  33. characters the bpe code barfs on.
  34. The reversible bpe codes work on unicode strings. This means you need a large # of unicode characters in your vocab
  35. if you want to avoid UNKs. When you're at something like a 10B token dataset you end up needing around 5K for
  36. decent coverage. This is a significant percentage of your normal, say, 32K bpe vocab. To avoid that, we want lookup
  37. tables between utf-8 bytes and unicode strings.
  38. """
  39. bs = (
  40. list(range(ord("!"), ord("~") + 1))
  41. + list(range(ord("¡"), ord("¬") + 1))
  42. + list(range(ord("®"), ord("ÿ") + 1))
  43. )
  44. cs = bs[:]
  45. n = 0
  46. for b in range(2**8):
  47. if b not in bs:
  48. bs.append(b)
  49. cs.append(2**8 + n)
  50. n += 1
  51. cs = [chr(n) for n in cs]
  52. return dict(zip(bs, cs))
  53. def get_pairs(word):
  54. """
  55. Return set of symbol pairs in a word.
  56. Word is represented as tuple of symbols (symbols being variable-length strings).
  57. """
  58. pairs = set()
  59. prev_char = word[0]
  60. for char in word[1:]:
  61. pairs.add((prev_char, char))
  62. prev_char = char
  63. return pairs
  64. class Qwen2Tokenizer(PretrainedTokenizer):
  65. """
  66. Construct a Qwen2 tokenizer. Based on byte-level Byte-Pair-Encoding.
  67. Same with GPT2Tokenizer, this tokenizer has been trained to treat spaces like parts of the tokens so a word will
  68. be encoded differently whether it is at the beginning of the sentence (without space) or not:
  69. ```python
  70. >>> from transformers import Qwen2Tokenizer
  71. >>> tokenizer = Qwen2Tokenizer.from_pretrained("Qwen/Qwen-tokenizer")
  72. >>> tokenizer("Hello world")["input_ids"]
  73. [9707, 1879]
  74. >>> tokenizer(" Hello world")["input_ids"]
  75. [21927, 1879]
  76. ```
  77. This is expected.
  78. You should not use GPT2Tokenizer instead, because of the different pretokenization rules.
  79. This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
  80. this superclass for more information regarding those methods.
  81. Args:
  82. vocab_file (`str`):
  83. Path to the vocabulary file.
  84. merges_file (`str`):
  85. Path to the merges file.
  86. errors (`str`, *optional*, defaults to `"replace"`):
  87. Paradigm to follow when decoding bytes to UTF-8. See
  88. [bytes.decode](https://docs.python.org/3/library/stdtypes.html#bytes.decode) for more information.
  89. unk_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
  90. The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
  91. token instead.
  92. bos_token (`str`, *optional*):
  93. The beginning of sequence token. Not applicable for this tokenizer.
  94. eos_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
  95. The end of sequence token.
  96. pad_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
  97. The token used for padding, for example when batching sequences of different lengths.
  98. clean_up_tokenization_spaces (`bool`, *optional*, defaults to `False`):
  99. Whether or not the model should cleanup the spaces that were added when splitting the input text during the
  100. tokenization process. Not applicable to this tokenizer, since tokenization does not add spaces.
  101. split_special_tokens (`bool`, *optional*, defaults to `False`):
  102. Whether or not the special tokens should be split during the tokenization process. The default behavior is
  103. to not split special tokens. This means that if `<|endoftext|>` is the `eos_token`, then `tokenizer.tokenize("<|endoftext|>") =
  104. ['<|endoftext|>`]. Otherwise, if `split_special_tokens=True`, then `tokenizer.tokenize("<|endoftext|>")` will be give `['<',
  105. '|', 'endo', 'ft', 'ext', '|', '>']`. This argument is only supported for `slow` tokenizers for the moment.
  106. """
  107. resource_files_names = VOCAB_FILES_NAMES
  108. model_input_names = ["input_ids", "attention_mask"]
  109. max_model_input_sizes = MAX_MODEL_INPUT_SIZES
  110. def __init__(
  111. self,
  112. vocab_file,
  113. merges_file,
  114. errors="replace",
  115. unk_token="<|endoftext|>",
  116. bos_token=None,
  117. eos_token="<|endoftext|>",
  118. pad_token="<|endoftext|>",
  119. clean_up_tokenization_spaces=False,
  120. split_special_tokens=False,
  121. **kwargs,
  122. ):
  123. super().__init__(**kwargs)
  124. # Qwen vocab does not contain control tokens; added tokens need to be special
  125. bos_token = (
  126. AddedToken(
  127. bos_token, lstrip=False, rstrip=False, special=True, normalized=False
  128. )
  129. if isinstance(bos_token, str)
  130. else bos_token
  131. )
  132. eos_token = (
  133. AddedToken(
  134. eos_token, lstrip=False, rstrip=False, special=True, normalized=False
  135. )
  136. if isinstance(eos_token, str)
  137. else eos_token
  138. )
  139. unk_token = (
  140. AddedToken(
  141. unk_token, lstrip=False, rstrip=False, special=True, normalized=False
  142. )
  143. if isinstance(unk_token, str)
  144. else unk_token
  145. )
  146. pad_token = (
  147. AddedToken(
  148. pad_token, lstrip=False, rstrip=False, special=True, normalized=False
  149. )
  150. if isinstance(pad_token, str)
  151. else pad_token
  152. )
  153. with open(vocab_file, encoding="utf-8") as vocab_handle:
  154. self.encoder = json.load(vocab_handle)
  155. self.decoder = {v: k for k, v in self.encoder.items()}
  156. self.errors = errors # how to handle errors in decoding
  157. self.byte_encoder = bytes_to_unicode()
  158. self.byte_decoder = {v: k for k, v in self.byte_encoder.items()}
  159. bpe_merges = []
  160. with open(merges_file, encoding="utf-8") as merges_handle:
  161. for i, line in enumerate(merges_handle):
  162. line = line.strip()
  163. if (i == 0 and line.startswith("#version:")) or not line:
  164. continue
  165. bpe_merges.append(tuple(line.split()))
  166. self.bpe_ranks = dict(zip(bpe_merges, range(len(bpe_merges))))
  167. # NOTE: the cache can grow without bound and will get really large for long running processes
  168. # (esp. for texts of language that do not use space between word, e.g. Chinese); technically
  169. # not a memory leak but appears as one.
  170. # GPT2Tokenizer has the same problem, so let's be consistent.
  171. self.cache = {}
  172. self.pat = re.compile(PRETOKENIZE_REGEX)
  173. self.bos_token_id = kwargs["bos_token_id"] if "bos_token_id" in kwargs else None
  174. self.eos_token_id = kwargs["eos_token_id"] if "eos_token_id" in kwargs else None
  175. self.unk_token_id = kwargs["unk_token_id"] if "unk_token_id" in kwargs else None
  176. self.pad_token_id = kwargs["pad_token_id"] if "pad_token_id" in kwargs else None
  177. super().__init__(
  178. errors=errors,
  179. bos_token=bos_token,
  180. eos_token=eos_token,
  181. pad_token=pad_token,
  182. unk_token=unk_token,
  183. clean_up_tokenization_spaces=clean_up_tokenization_spaces,
  184. split_special_tokens=split_special_tokens,
  185. **kwargs,
  186. )
  187. @property
  188. def vocab_size(self) -> int:
  189. return len(self.encoder)
  190. def get_vocab(self):
  191. return dict(self.encoder, **self.added_tokens_encoder)
  192. def bpe(self, token):
  193. if token in self.cache:
  194. return self.cache[token]
  195. word = tuple(token)
  196. pairs = get_pairs(word)
  197. if not pairs:
  198. return token
  199. while True:
  200. bigram = min(pairs, key=lambda pair: self.bpe_ranks.get(pair, float("inf")))
  201. if bigram not in self.bpe_ranks:
  202. break
  203. first, second = bigram
  204. new_word = []
  205. i = 0
  206. while i < len(word):
  207. try:
  208. j = word.index(first, i)
  209. except ValueError:
  210. new_word.extend(word[i:])
  211. break
  212. else:
  213. new_word.extend(word[i:j])
  214. i = j
  215. if word[i] == first and i < len(word) - 1 and word[i + 1] == second:
  216. new_word.append(first + second)
  217. i += 2
  218. else:
  219. new_word.append(word[i])
  220. i += 1
  221. new_word = tuple(new_word)
  222. word = new_word
  223. if len(word) == 1:
  224. break
  225. else:
  226. pairs = get_pairs(word)
  227. word = " ".join(word)
  228. self.cache[token] = word
  229. return word
  230. def _tokenize(self, text):
  231. """Tokenize a string."""
  232. bpe_tokens = []
  233. for token in re.findall(self.pat, text):
  234. token = "".join(
  235. self.byte_encoder[b] for b in token.encode("utf-8")
  236. ) # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case)
  237. bpe_tokens.extend(bpe_token for bpe_token in self.bpe(token).split(" "))
  238. return bpe_tokens
  239. def _convert_token_to_id(self, token):
  240. """Converts a token (str) in an id using the vocab."""
  241. return self.encoder.get(
  242. token, self.added_tokens_encoder.get(token, len(self.encoder))
  243. )
  244. def _convert_id_to_token(self, index):
  245. """Converts an index (integer) in a token (str) using the vocab."""
  246. return self.decoder.get(
  247. index, self.added_tokens_decoder.get(index, self.unk_token)
  248. )
  249. def convert_tokens_to_string(self, tokens):
  250. """Converts a sequence of tokens (string) in a single string."""
  251. text = "".join(tokens)
  252. text = bytearray([self.byte_decoder[c] for c in text]).decode(
  253. "utf-8", errors=self.errors
  254. )
  255. return text
  256. def _decode(
  257. self,
  258. token_ids,
  259. skip_special_tokens: bool = False,
  260. clean_up_tokenization_spaces: Optional[bool] = False,
  261. spaces_between_special_tokens: bool = False,
  262. **kwargs,
  263. ) -> str:
  264. # `spaces_between_special_tokens` defaults to True for _decode in slow tokenizers
  265. # and cannot be configured elsewhere, but it should default to False for Qwen2Tokenizer
  266. return super()._decode(
  267. token_ids,
  268. skip_special_tokens=skip_special_tokens,
  269. clean_up_tokenization_spaces=clean_up_tokenization_spaces,
  270. spaces_between_special_tokens=spaces_between_special_tokens,
  271. **kwargs,
  272. )
  273. def save_vocabulary(
  274. self, save_directory: str, filename_prefix: Optional[str] = None
  275. ) -> Tuple[str]:
  276. vocab_file = os.path.join(
  277. save_directory,
  278. (filename_prefix + "-" if filename_prefix else "")
  279. + VOCAB_FILES_NAMES["vocab_file"],
  280. )
  281. merge_file = os.path.join(
  282. save_directory,
  283. (filename_prefix + "-" if filename_prefix else "")
  284. + VOCAB_FILES_NAMES["merges_file"],
  285. )
  286. with open(vocab_file, "w", encoding="utf-8") as f:
  287. f.write(
  288. json.dumps(self.encoder, indent=2, sort_keys=True, ensure_ascii=False)
  289. + "\n"
  290. )
  291. index = 0
  292. with open(merge_file, "w", encoding="utf-8") as writer:
  293. writer.write("#version: 0.2\n")
  294. for bpe_tokens, token_index in sorted(
  295. self.bpe_ranks.items(), key=lambda kv: kv[1]
  296. ):
  297. if index != token_index:
  298. index = token_index
  299. writer.write(" ".join(bpe_tokens) + "\n")
  300. index += 1
  301. return vocab_file, merge_file
  302. def prepare_for_tokenization(self, text, **kwargs):
  303. text = unicodedata.normalize("NFC", text)
  304. return (text, kwargs)
  305. class MIXQwen2Tokenizer(Qwen2Tokenizer):
  306. def __init__(self, *args, **kwargs):
  307. super(MIXQwen2Tokenizer, self).__init__(*args, **kwargs)
  308. def tokenize(self, text: TextInput, **kwargs) -> List[str]:
  309. """
  310. Converts a string in a sequence of tokens, using the tokenizer.
  311. Split in words for word-based vocabulary or sub-words for sub-word-based vocabularies
  312. (BPE/SentencePieces/WordPieces). Takes care of added tokens.
  313. Args:
  314. text (`str`):
  315. The sequence to be encoded.
  316. **kwargs (additional keyword arguments):
  317. Passed along to the model-specific `prepare_for_tokenization` preprocessing method.
  318. Returns:
  319. `List[str]`: The list of tokens.
  320. """
  321. split_special_tokens = kwargs.pop(
  322. "split_special_tokens", self.split_special_tokens
  323. )
  324. # Simple mapping string => AddedToken for special tokens with specific tokenization behaviors
  325. all_special_tokens_extended = dict(
  326. (str(t), t)
  327. for t in self.all_special_tokens_extended
  328. if isinstance(t, AddedToken)
  329. )
  330. text, kwargs = self.prepare_for_tokenization(text, **kwargs)
  331. # TODO: should this be in the base class?
  332. if hasattr(self, "do_lower_case") and self.do_lower_case:
  333. # convert non-special tokens to lowercase
  334. escaped_special_toks = [
  335. re.escape(s_tok)
  336. for s_tok in (self.unique_no_split_tokens + self.all_special_tokens)
  337. ]
  338. pattern = r"(" + r"|".join(escaped_special_toks) + r")|" + r"(.+?)"
  339. text = re.sub(
  340. pattern, lambda m: m.groups()[0] or m.groups()[1].lower(), text
  341. )
  342. if split_special_tokens:
  343. no_split_token = []
  344. tokens = [text]
  345. else:
  346. no_split_token = set(
  347. self.unique_no_split_tokens
  348. ) # don't split on any of the added tokens
  349. # "This is something<special_token_1> else"
  350. tokens = self.tokens_trie.split(text)
  351. # ["This is something", "<special_token_1>", " else"]
  352. for i, token in enumerate(tokens):
  353. if token in no_split_token:
  354. tok_extended = all_special_tokens_extended.get(token, None)
  355. left = tokens[i - 1] if i > 0 else None
  356. right = tokens[i + 1] if i < len(tokens) - 1 else None
  357. if isinstance(tok_extended, AddedToken):
  358. if tok_extended.rstrip and right:
  359. # A bit counter-intuitive but we strip the left of the string
  360. # since tok_extended.rstrip means the special token is eating all white spaces on its right
  361. tokens[i + 1] = right.lstrip()
  362. if tok_extended.lstrip and left:
  363. tokens[i - 1] = left.rstrip()
  364. tokenized_text = []
  365. for token in tokens:
  366. # Need to skip eventual empty (fully stripped) tokens
  367. if not token:
  368. continue
  369. if token in no_split_token:
  370. tokenized_text.append(token)
  371. else:
  372. tokenized_text.extend(self._tokenize(token))
  373. return tokenized_text