qwen2_tokenizer.py 17 KB

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