tokenization_codegen.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  1. # coding=utf-8
  2. # Copyright 2022 The Salesforce authors, The Open AI Team Authors and The HuggingFace Inc. team.
  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 CodeGen"""
  16. import json
  17. import os
  18. from functools import lru_cache
  19. from typing import TYPE_CHECKING, Optional, Union
  20. import numpy as np
  21. import regex as re
  22. from ...utils import is_tf_available, is_torch_available, logging, to_py_obj
  23. if TYPE_CHECKING:
  24. if is_torch_available():
  25. import torch
  26. if is_tf_available():
  27. import tensorflow as tf
  28. from ...tokenization_utils import AddedToken, PreTrainedTokenizer
  29. logger = logging.get_logger(__name__)
  30. VOCAB_FILES_NAMES = {
  31. "vocab_file": "vocab.json",
  32. "merges_file": "merges.txt",
  33. }
  34. @lru_cache
  35. def bytes_to_unicode():
  36. """
  37. Returns list of utf-8 byte and a mapping to unicode strings. We specifically avoids mapping to whitespace/control
  38. characters the bpe code barfs on.
  39. The reversible bpe codes work on unicode strings. This means you need a large # of unicode characters in your vocab
  40. if you want to avoid UNKs. When you're at something like a 10B token dataset you end up needing around 5K for
  41. decent coverage. This is a significant percentage of your normal, say, 32K bpe vocab. To avoid that, we want lookup
  42. tables between utf-8 bytes and unicode strings.
  43. """
  44. bs = (
  45. list(range(ord("!"), ord("~") + 1)) + list(range(ord("¡"), ord("¬") + 1)) + 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 CodeGenTokenizer(PreTrainedTokenizer):
  68. """
  69. Construct a CodeGen tokenizer. Based on byte-level Byte-Pair-Encoding.
  70. This tokenizer has been trained to treat spaces like parts of the tokens (a bit like sentencepiece) 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 CodeGenTokenizer
  74. >>> tokenizer = CodeGenTokenizer.from_pretrained("Salesforce/codegen-350M-mono")
  75. >>> tokenizer("Hello world")["input_ids"]
  76. [15496, 995]
  77. >>> tokenizer(" Hello world")["input_ids"]
  78. [18435, 995]
  79. ```
  80. You can get around that behavior by passing `add_prefix_space=True` when instantiating this tokenizer or when you
  81. call it on some text, but since the model was not pretrained this way, it might yield a decrease in performance.
  82. <Tip>
  83. When used with `is_split_into_words=True`, this tokenizer will add a space before each word (even the first one).
  84. </Tip>
  85. This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
  86. this superclass for more information regarding those methods.
  87. Args:
  88. vocab_file (`str`):
  89. Path to the vocabulary file.
  90. merges_file (`str`):
  91. Path to the merges file.
  92. errors (`str`, *optional*, defaults to `"replace"`):
  93. Paradigm to follow when decoding bytes to UTF-8. See
  94. [bytes.decode](https://docs.python.org/3/library/stdtypes.html#bytes.decode) for more information.
  95. unk_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
  96. The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
  97. token instead.
  98. bos_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
  99. The beginning of sequence token.
  100. eos_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
  101. The end of sequence token.
  102. pad_token (`str`, *optional*):
  103. The token used for padding, for example when batching sequences of different lengths.
  104. add_prefix_space (`bool`, *optional*, defaults to `False`):
  105. Whether or not to add an initial space to the input. This allows to treat the leading word just as any
  106. other word. (CodeGen tokenizer detect beginning of words by the preceding space).
  107. add_bos_token (`bool`, *optional*, defaults to `False`):
  108. Whether to add a beginning of sequence token at the start of sequences.
  109. return_token_type_ids (`bool`, *optional*, defaults to `False`):
  110. Whether to return token type IDs.
  111. """
  112. vocab_files_names = VOCAB_FILES_NAMES
  113. model_input_names = ["input_ids", "attention_mask"]
  114. def __init__(
  115. self,
  116. vocab_file,
  117. merges_file,
  118. errors="replace",
  119. unk_token="<|endoftext|>",
  120. bos_token="<|endoftext|>",
  121. eos_token="<|endoftext|>",
  122. pad_token=None,
  123. add_prefix_space=False,
  124. add_bos_token=False,
  125. return_token_type_ids=False,
  126. **kwargs,
  127. ):
  128. bos_token = AddedToken(bos_token, special=True) if isinstance(bos_token, str) else bos_token
  129. eos_token = AddedToken(eos_token, special=True) if isinstance(eos_token, str) else eos_token
  130. unk_token = AddedToken(unk_token, special=True) if isinstance(unk_token, str) else unk_token
  131. pad_token = AddedToken(pad_token, special=True) if isinstance(pad_token, str) else pad_token
  132. self.add_bos_token = add_bos_token
  133. self.return_token_type_ids = return_token_type_ids
  134. if self.return_token_type_ids:
  135. self.model_input_names.append("token_type_ids")
  136. with open(vocab_file, encoding="utf-8") as vocab_handle:
  137. self.encoder = json.load(vocab_handle)
  138. self.decoder = {v: k for k, v in self.encoder.items()}
  139. self.errors = errors # how to handle errors in decoding
  140. self.byte_encoder = bytes_to_unicode()
  141. self.byte_decoder = {v: k for k, v in self.byte_encoder.items()}
  142. with open(merges_file, encoding="utf-8") as merges_handle:
  143. bpe_merges = merges_handle.read().split("\n")[1:-1]
  144. bpe_merges = [tuple(merge.split()) for merge in bpe_merges]
  145. self.bpe_ranks = dict(zip(bpe_merges, range(len(bpe_merges))))
  146. self.cache = {}
  147. self.add_prefix_space = add_prefix_space
  148. # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions
  149. self.pat = re.compile(r"""'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+""")
  150. super().__init__(
  151. errors=errors,
  152. unk_token=unk_token,
  153. bos_token=bos_token,
  154. eos_token=eos_token,
  155. pad_token=pad_token,
  156. add_prefix_space=add_prefix_space,
  157. add_bos_token=add_bos_token,
  158. return_token_type_ids=return_token_type_ids,
  159. **kwargs,
  160. )
  161. @property
  162. def vocab_size(self):
  163. return len(self.encoder)
  164. def get_vocab(self):
  165. return dict(self.encoder, **self.added_tokens_encoder)
  166. def bpe(self, token):
  167. if token in self.cache:
  168. return self.cache[token]
  169. word = tuple(token)
  170. pairs = get_pairs(word)
  171. if not pairs:
  172. return token
  173. while True:
  174. bigram = min(pairs, key=lambda pair: self.bpe_ranks.get(pair, float("inf")))
  175. if bigram not in self.bpe_ranks:
  176. break
  177. first, second = bigram
  178. new_word = []
  179. i = 0
  180. while i < len(word):
  181. try:
  182. j = word.index(first, i)
  183. except ValueError:
  184. new_word.extend(word[i:])
  185. break
  186. else:
  187. new_word.extend(word[i:j])
  188. i = j
  189. if word[i] == first and i < len(word) - 1 and word[i + 1] == second:
  190. new_word.append(first + second)
  191. i += 2
  192. else:
  193. new_word.append(word[i])
  194. i += 1
  195. new_word = tuple(new_word)
  196. word = new_word
  197. if len(word) == 1:
  198. break
  199. else:
  200. pairs = get_pairs(word)
  201. word = " ".join(word)
  202. self.cache[token] = word
  203. return word
  204. def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
  205. if self.add_bos_token:
  206. bos_token_ids = [self.bos_token_id]
  207. else:
  208. bos_token_ids = []
  209. output = bos_token_ids + token_ids_0
  210. if token_ids_1 is None:
  211. return output
  212. return output + bos_token_ids + token_ids_1
  213. def _tokenize(self, text):
  214. """Tokenize a string."""
  215. bpe_tokens = []
  216. for token in re.findall(self.pat, text):
  217. token = "".join(
  218. self.byte_encoder[b] for b in token.encode("utf-8")
  219. ) # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case)
  220. bpe_tokens.extend(bpe_token for bpe_token in self.bpe(token).split(" "))
  221. return bpe_tokens
  222. def _convert_token_to_id(self, token):
  223. """Converts a token (str) in an id using the vocab."""
  224. return self.encoder.get(token, self.encoder.get(self.unk_token))
  225. def _convert_id_to_token(self, index):
  226. """Converts an index (integer) in a token (str) using the vocab."""
  227. return self.decoder.get(index)
  228. def convert_tokens_to_string(self, tokens):
  229. """Converts a sequence of tokens (string) in a single string."""
  230. text = "".join(tokens)
  231. text = bytearray([self.byte_decoder[c] for c in text]).decode("utf-8", errors=self.errors)
  232. return text
  233. def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> tuple[str]:
  234. if not os.path.isdir(save_directory):
  235. logger.error(f"Vocabulary path ({save_directory}) should be a directory")
  236. return
  237. vocab_file = os.path.join(
  238. save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
  239. )
  240. merge_file = os.path.join(
  241. save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["merges_file"]
  242. )
  243. with open(vocab_file, "w", encoding="utf-8") as f:
  244. f.write(json.dumps(self.encoder, indent=2, sort_keys=True, ensure_ascii=False) + "\n")
  245. index = 0
  246. with open(merge_file, "w", encoding="utf-8") as writer:
  247. writer.write("#version: 0.2\n")
  248. for bpe_tokens, token_index in sorted(self.bpe_ranks.items(), key=lambda kv: kv[1]):
  249. if index != token_index:
  250. logger.warning(
  251. f"Saving vocabulary to {merge_file}: BPE merge indices are not consecutive."
  252. " Please check that the tokenizer is not corrupted!"
  253. )
  254. index = token_index
  255. writer.write(" ".join(bpe_tokens) + "\n")
  256. index += 1
  257. return vocab_file, merge_file
  258. def prepare_for_tokenization(self, text, is_split_into_words=False, **kwargs):
  259. add_prefix_space = kwargs.pop("add_prefix_space", self.add_prefix_space)
  260. if is_split_into_words or add_prefix_space:
  261. text = " " + text
  262. return (text, kwargs)
  263. def decode(
  264. self,
  265. token_ids: Union[int, list[int], "np.ndarray", "torch.Tensor", "tf.Tensor"],
  266. skip_special_tokens: bool = False,
  267. clean_up_tokenization_spaces: Optional[bool] = None,
  268. truncate_before_pattern: Optional[list[str]] = None,
  269. **kwargs,
  270. ) -> str:
  271. """
  272. Converts a sequence of ids in a string, using the tokenizer and vocabulary with options to remove special
  273. tokens and clean up tokenization spaces.
  274. Similar to doing `self.convert_tokens_to_string(self.convert_ids_to_tokens(token_ids))`.
  275. Args:
  276. token_ids (`Union[int, List[int], np.ndarray, torch.Tensor, tf.Tensor]`):
  277. List of tokenized input ids. Can be obtained using the `__call__` method.
  278. skip_special_tokens (`bool`, *optional*, defaults to `False`):
  279. Whether or not to remove special tokens in the decoding.
  280. clean_up_tokenization_spaces (`bool`, *optional*):
  281. Whether or not to clean up the tokenization spaces. If `None`, will default to
  282. `self.clean_up_tokenization_spaces` (available in the `tokenizer_config`).
  283. truncate_before_pattern (`List[str]`, *optional*, defaults to `None`):
  284. A list of regular expression strings that will be used to truncate the returned string. This can be
  285. used to remove extra pieces of code (e.g. truncate if observing a comment symbol "#" at the beginning
  286. of a new line). An example pattern could be `["^#", re.escape("<|endoftext|>"), "^'''", "\n\n\n"]`.
  287. kwargs (additional keyword arguments, *optional*):
  288. Will be passed to the underlying model specific decode method.
  289. Returns:
  290. `str`: The decoded sentence.
  291. """
  292. token_ids = to_py_obj(token_ids)
  293. decoded_text = super()._decode(
  294. token_ids=token_ids,
  295. skip_special_tokens=skip_special_tokens,
  296. clean_up_tokenization_spaces=clean_up_tokenization_spaces,
  297. **kwargs,
  298. )
  299. if truncate_before_pattern is not None and len(truncate_before_pattern) > 0:
  300. decoded_text = self.truncate(decoded_text, truncate_before_pattern)
  301. return decoded_text
  302. def truncate(self, completion, truncate_before_pattern):
  303. def find_re(string, pattern, start_pos):
  304. m = pattern.search(string, start_pos)
  305. return m.start() if m else -1
  306. terminals = [re.compile(pattern, re.MULTILINE) for pattern in truncate_before_pattern]
  307. prints = list(re.finditer("^print", completion, re.MULTILINE))
  308. if len(prints) > 1:
  309. completion = completion[: prints[1].start()]
  310. defs = list(re.finditer("^def", completion, re.MULTILINE))
  311. if len(defs) > 1:
  312. completion = completion[: defs[1].start()]
  313. start_pos = 0
  314. terminals_pos = [
  315. pos for pos in [find_re(completion, terminal, start_pos) for terminal in terminals] if pos != -1
  316. ]
  317. if len(terminals_pos) > 0:
  318. return completion[: min(terminals_pos)]
  319. else:
  320. return completion
  321. __all__ = ["CodeGenTokenizer"]