qwen2_tokenizer.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432
  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. from .....utils.deps import is_dep_available
  20. from .tokenizer_utils import PretrainedTokenizer
  21. from .tokenizer_utils_base import AddedToken, TextInput
  22. if is_dep_available("regex"):
  23. import regex as re
  24. VOCAB_FILES_NAMES = {
  25. "vocab_file": "vocab.json",
  26. "merges_file": "merges.txt",
  27. }
  28. __all__ = ["Qwen2Tokenizer", "MIXQwen2Tokenizer"]
  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. def bytes_to_unicode():
  33. """
  34. Returns list of utf-8 byte and a mapping to unicode strings. We specifically avoids mapping to whitespace/control
  35. characters the bpe code barfs on.
  36. The reversible bpe codes work on unicode strings. This means you need a large # of unicode characters in your vocab
  37. if you want to avoid UNKs. When you're at something like a 10B token dataset you end up needing around 5K for
  38. decent coverage. This is a significant percentage of your normal, say, 32K bpe vocab. To avoid that, we want lookup
  39. tables between utf-8 bytes and unicode strings.
  40. """
  41. bs = (
  42. list(range(ord("!"), ord("~") + 1))
  43. + list(range(ord("¡"), ord("¬") + 1))
  44. + list(range(ord("®"), ord("ÿ") + 1))
  45. )
  46. cs = bs[:]
  47. n = 0
  48. for b in range(2**8):
  49. if b not in bs:
  50. bs.append(b)
  51. cs.append(2**8 + n)
  52. n += 1
  53. cs = [chr(n) for n in cs]
  54. return dict(zip(bs, cs))
  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. resource_files_names = VOCAB_FILES_NAMES
  110. model_input_names = ["input_ids", "attention_mask"]
  111. max_model_input_sizes = MAX_MODEL_INPUT_SIZES
  112. def __init__(
  113. self,
  114. vocab_file,
  115. merges_file,
  116. errors="replace",
  117. unk_token="<|endoftext|>",
  118. bos_token=None,
  119. eos_token="<|endoftext|>",
  120. pad_token="<|endoftext|>",
  121. clean_up_tokenization_spaces=False,
  122. split_special_tokens=False,
  123. **kwargs,
  124. ):
  125. super().__init__(**kwargs)
  126. # Qwen vocab does not contain control tokens; added tokens need to be special
  127. bos_token = (
  128. AddedToken(
  129. bos_token, lstrip=False, rstrip=False, special=True, normalized=False
  130. )
  131. if isinstance(bos_token, str)
  132. else bos_token
  133. )
  134. eos_token = (
  135. AddedToken(
  136. eos_token, lstrip=False, rstrip=False, special=True, normalized=False
  137. )
  138. if isinstance(eos_token, str)
  139. else eos_token
  140. )
  141. unk_token = (
  142. AddedToken(
  143. unk_token, lstrip=False, rstrip=False, special=True, normalized=False
  144. )
  145. if isinstance(unk_token, str)
  146. else unk_token
  147. )
  148. pad_token = (
  149. AddedToken(
  150. pad_token, lstrip=False, rstrip=False, special=True, normalized=False
  151. )
  152. if isinstance(pad_token, str)
  153. else pad_token
  154. )
  155. with open(vocab_file, encoding="utf-8") as vocab_handle:
  156. self.encoder = json.load(vocab_handle)
  157. self.decoder = {v: k for k, v in self.encoder.items()}
  158. self.errors = errors # how to handle errors in decoding
  159. self.byte_encoder = bytes_to_unicode()
  160. self.byte_decoder = {v: k for k, v in self.byte_encoder.items()}
  161. bpe_merges = []
  162. with open(merges_file, encoding="utf-8") as merges_handle:
  163. for i, line in enumerate(merges_handle):
  164. line = line.strip()
  165. if (i == 0 and line.startswith("#version:")) or not line:
  166. continue
  167. bpe_merges.append(tuple(line.split()))
  168. self.bpe_ranks = dict(zip(bpe_merges, range(len(bpe_merges))))
  169. # NOTE: the cache can grow without bound and will get really large for long running processes
  170. # (esp. for texts of language that do not use space between word, e.g. Chinese); technically
  171. # not a memory leak but appears as one.
  172. # GPT2Tokenizer has the same problem, so let's be consistent.
  173. self.cache = {}
  174. self.pat = re.compile(PRETOKENIZE_REGEX)
  175. self.bos_token_id = kwargs["bos_token_id"] if "bos_token_id" in kwargs else None
  176. self.eos_token_id = kwargs["eos_token_id"] if "eos_token_id" in kwargs else None
  177. self.unk_token_id = kwargs["unk_token_id"] if "unk_token_id" in kwargs else None
  178. self.pad_token_id = kwargs["pad_token_id"] if "pad_token_id" in kwargs else None
  179. super().__init__(
  180. errors=errors,
  181. bos_token=bos_token,
  182. eos_token=eos_token,
  183. pad_token=pad_token,
  184. unk_token=unk_token,
  185. clean_up_tokenization_spaces=clean_up_tokenization_spaces,
  186. split_special_tokens=split_special_tokens,
  187. **kwargs,
  188. )
  189. @property
  190. def vocab_size(self) -> int:
  191. return len(self.encoder)
  192. def get_vocab(self):
  193. return dict(self.encoder, **self.added_tokens_encoder)
  194. def bpe(self, token):
  195. if token in self.cache:
  196. return self.cache[token]
  197. word = tuple(token)
  198. pairs = get_pairs(word)
  199. if not pairs:
  200. return token
  201. while True:
  202. bigram = min(pairs, key=lambda pair: self.bpe_ranks.get(pair, float("inf")))
  203. if bigram not in self.bpe_ranks:
  204. break
  205. first, second = bigram
  206. new_word = []
  207. i = 0
  208. while i < len(word):
  209. try:
  210. j = word.index(first, i)
  211. except ValueError:
  212. new_word.extend(word[i:])
  213. break
  214. else:
  215. new_word.extend(word[i:j])
  216. i = j
  217. if word[i] == first and i < len(word) - 1 and word[i + 1] == second:
  218. new_word.append(first + second)
  219. i += 2
  220. else:
  221. new_word.append(word[i])
  222. i += 1
  223. new_word = tuple(new_word)
  224. word = new_word
  225. if len(word) == 1:
  226. break
  227. else:
  228. pairs = get_pairs(word)
  229. word = " ".join(word)
  230. self.cache[token] = word
  231. return word
  232. def _tokenize(self, text):
  233. """Tokenize a string."""
  234. bpe_tokens = []
  235. for token in re.findall(self.pat, text):
  236. token = "".join(
  237. self.byte_encoder[b] for b in token.encode("utf-8")
  238. ) # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case)
  239. bpe_tokens.extend(bpe_token for bpe_token in self.bpe(token).split(" "))
  240. return bpe_tokens
  241. def _convert_token_to_id(self, token):
  242. """Converts a token (str) in an id using the vocab."""
  243. return self.encoder.get(
  244. token, self.added_tokens_encoder.get(token, len(self.encoder))
  245. )
  246. def _convert_id_to_token(self, index):
  247. """Converts an index (integer) in a token (str) using the vocab."""
  248. return self.decoder.get(
  249. index, self.added_tokens_decoder.get(index, self.unk_token)
  250. )
  251. def convert_tokens_to_string(self, tokens):
  252. """Converts a sequence of tokens (string) in a single string."""
  253. text = "".join(tokens)
  254. text = bytearray([self.byte_decoder[c] for c in text]).decode(
  255. "utf-8", errors=self.errors
  256. )
  257. return text
  258. def _decode(
  259. self,
  260. token_ids,
  261. skip_special_tokens: bool = False,
  262. clean_up_tokenization_spaces: Optional[bool] = False,
  263. spaces_between_special_tokens: bool = False,
  264. **kwargs,
  265. ) -> str:
  266. # `spaces_between_special_tokens` defaults to True for _decode in slow tokenizers
  267. # and cannot be configured elsewhere, but it should default to False for Qwen2Tokenizer
  268. return super()._decode(
  269. token_ids,
  270. skip_special_tokens=skip_special_tokens,
  271. clean_up_tokenization_spaces=clean_up_tokenization_spaces,
  272. spaces_between_special_tokens=spaces_between_special_tokens,
  273. **kwargs,
  274. )
  275. def save_vocabulary(
  276. self, save_directory: str, filename_prefix: Optional[str] = None
  277. ) -> Tuple[str]:
  278. vocab_file = os.path.join(
  279. save_directory,
  280. (filename_prefix + "-" if filename_prefix else "")
  281. + VOCAB_FILES_NAMES["vocab_file"],
  282. )
  283. merge_file = os.path.join(
  284. save_directory,
  285. (filename_prefix + "-" if filename_prefix else "")
  286. + VOCAB_FILES_NAMES["merges_file"],
  287. )
  288. with open(vocab_file, "w", encoding="utf-8") as f:
  289. f.write(
  290. json.dumps(self.encoder, indent=2, sort_keys=True, ensure_ascii=False)
  291. + "\n"
  292. )
  293. index = 0
  294. with open(merge_file, "w", encoding="utf-8") as writer:
  295. writer.write("#version: 0.2\n")
  296. for bpe_tokens, token_index in sorted(
  297. self.bpe_ranks.items(), key=lambda kv: kv[1]
  298. ):
  299. if index != token_index:
  300. index = token_index
  301. writer.write(" ".join(bpe_tokens) + "\n")
  302. index += 1
  303. return vocab_file, merge_file
  304. def prepare_for_tokenization(self, text, **kwargs):
  305. text = unicodedata.normalize("NFC", text)
  306. return (text, kwargs)
  307. class MIXQwen2Tokenizer(Qwen2Tokenizer):
  308. def __init__(self, *args, **kwargs):
  309. super(MIXQwen2Tokenizer, self).__init__(*args, **kwargs)
  310. def tokenize(self, text: TextInput, **kwargs) -> List[str]:
  311. """
  312. Converts a string in a sequence of tokens, using the tokenizer.
  313. Split in words for word-based vocabulary or sub-words for sub-word-based vocabularies
  314. (BPE/SentencePieces/WordPieces). Takes care of added tokens.
  315. Args:
  316. text (`str`):
  317. The sequence to be encoded.
  318. **kwargs (additional keyword arguments):
  319. Passed along to the model-specific `prepare_for_tokenization` preprocessing method.
  320. Returns:
  321. `List[str]`: The list of tokens.
  322. """
  323. split_special_tokens = kwargs.pop(
  324. "split_special_tokens", self.split_special_tokens
  325. )
  326. # Simple mapping string => AddedToken for special tokens with specific tokenization behaviors
  327. all_special_tokens_extended = dict(
  328. (str(t), t)
  329. for t in self.all_special_tokens_extended
  330. if isinstance(t, AddedToken)
  331. )
  332. text, kwargs = self.prepare_for_tokenization(text, **kwargs)
  333. # TODO: should this be in the base class?
  334. if hasattr(self, "do_lower_case") and self.do_lower_case:
  335. # convert non-special tokens to lowercase
  336. escaped_special_toks = [
  337. re.escape(s_tok)
  338. for s_tok in (self.unique_no_split_tokens + self.all_special_tokens)
  339. ]
  340. pattern = r"(" + r"|".join(escaped_special_toks) + r")|" + r"(.+?)"
  341. text = re.sub(
  342. pattern, lambda m: m.groups()[0] or m.groups()[1].lower(), text
  343. )
  344. if split_special_tokens:
  345. no_split_token = []
  346. tokens = [text]
  347. else:
  348. no_split_token = set(
  349. self.unique_no_split_tokens
  350. ) # don't split on any of the added tokens
  351. # "This is something<special_token_1> else"
  352. tokens = self.tokens_trie.split(text)
  353. # ["This is something", "<special_token_1>", " else"]
  354. for i, token in enumerate(tokens):
  355. if token in no_split_token:
  356. tok_extended = all_special_tokens_extended.get(token, None)
  357. left = tokens[i - 1] if i > 0 else None
  358. right = tokens[i + 1] if i < len(tokens) - 1 else None
  359. if isinstance(tok_extended, AddedToken):
  360. if tok_extended.rstrip and right:
  361. # A bit counter-intuitive but we strip the left of the string
  362. # since tok_extended.rstrip means the special token is eating all white spaces on its right
  363. tokens[i + 1] = right.lstrip()
  364. if tok_extended.lstrip and left:
  365. tokens[i - 1] = left.rstrip()
  366. tokenized_text = []
  367. for token in tokens:
  368. # Need to skip eventual empty (fully stripped) tokens
  369. if not token:
  370. continue
  371. if token in no_split_token:
  372. tokenized_text.append(token)
  373. else:
  374. tokenized_text.extend(self._tokenize(token))
  375. return tokenized_text