tokenization_codegen.py 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  1. # Copyright 2022 The Salesforce authors, The Open AI Team Authors and The HuggingFace Inc. team.
  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. """Tokenization classes for CodeGen."""
  15. import re
  16. from typing import TYPE_CHECKING, Union
  17. import numpy as np
  18. from tokenizers import Tokenizer, decoders, pre_tokenizers, processors
  19. from tokenizers.models import BPE
  20. from ...tokenization_utils_tokenizers import TokenizersBackend
  21. from ...utils import is_torch_available, logging
  22. if TYPE_CHECKING:
  23. if is_torch_available():
  24. import torch
  25. logger = logging.get_logger(__name__)
  26. VOCAB_FILES_NAMES = {"vocab_file": "vocab.json", "merges_file": "merges.txt"}
  27. class CodeGenTokenizer(TokenizersBackend):
  28. """
  29. Construct a CodeGen tokenizer (backed by HuggingFace's *tokenizers* library). Based on byte-level
  30. Byte-Pair-Encoding.
  31. This tokenizer has been trained to treat spaces like parts of the tokens (a bit like sentencepiece) so a word will
  32. be encoded differently whether it is at the beginning of the sentence (without space) or not:
  33. ```python
  34. >>> from transformers import CodeGenTokenizer
  35. >>> tokenizer = CodeGenTokenizer.from_pretrained("Salesforce/codegen-350M-mono")
  36. >>> tokenizer("Hello world")["input_ids"]
  37. [15496, 995]
  38. >>> tokenizer(" Hello world")["input_ids"]
  39. [18435, 995]
  40. ```
  41. You can get around that behavior by passing `add_prefix_space=True` when instantiating this tokenizer, but since
  42. the model was not pretrained this way, it might yield a decrease in performance.
  43. <Tip>
  44. When used with `is_split_into_words=True`, this tokenizer needs to be instantiated with `add_prefix_space=True`.
  45. </Tip>
  46. This tokenizer inherits from [`TokenizersBackend`] which contains most of the main methods. Users should
  47. refer to this superclass for more information regarding those methods.
  48. Args:
  49. vocab (`str` or `dict[str, int]`, *optional*):
  50. Custom vocabulary dictionary. If not provided, vocabulary is loaded from `vocab_file`.
  51. merges (`str` or `list[str]`, *optional*):
  52. Custom merges list. If not provided, merges are loaded from `merges_file`.
  53. unk_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
  54. The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
  55. token instead.
  56. bos_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
  57. The beginning of sequence token.
  58. eos_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
  59. The end of sequence token.
  60. pad_token (`str`, *optional*):
  61. The token used for padding, for example when batching sequences of different lengths.
  62. add_prefix_space (`bool`, *optional*, defaults to `False`):
  63. Whether or not to add an initial space to the input. This allows to treat the leading word just as any
  64. other word. (CodeGen tokenizer detect beginning of words by the preceding space).
  65. return_token_type_ids (`bool`, *optional*, defaults to `False`):
  66. Whether to return token type IDs.
  67. """
  68. vocab_files_names = VOCAB_FILES_NAMES
  69. model_input_names = ["input_ids", "attention_mask"]
  70. model = BPE
  71. def __init__(
  72. self,
  73. vocab: str | dict[str, int] | None = None,
  74. merges: str | list[str] | None = None,
  75. unk_token: str = "<|endoftext|>",
  76. bos_token: str = "<|endoftext|>",
  77. eos_token: str = "<|endoftext|>",
  78. pad_token=None,
  79. add_prefix_space: bool = False,
  80. return_token_type_ids: bool = False,
  81. **kwargs,
  82. ):
  83. self.return_token_type_ids = return_token_type_ids
  84. if self.return_token_type_ids:
  85. self.model_input_names.append("token_type_ids")
  86. self.add_prefix_space = add_prefix_space
  87. self._vocab = vocab if vocab is not None else {}
  88. self._merges = merges or []
  89. self._tokenizer = Tokenizer(
  90. BPE(
  91. vocab=self._vocab,
  92. merges=self._merges,
  93. dropout=None,
  94. continuing_subword_prefix="",
  95. end_of_word_suffix="",
  96. fuse_unk=False,
  97. )
  98. )
  99. self._tokenizer.pre_tokenizer = pre_tokenizers.ByteLevel(add_prefix_space=add_prefix_space)
  100. self._tokenizer.decoder = decoders.ByteLevel()
  101. self._tokenizer.post_processor = processors.ByteLevel(
  102. add_prefix_space=True, use_regex=True, trim_offsets=False
  103. )
  104. super().__init__(
  105. unk_token=unk_token,
  106. bos_token=bos_token,
  107. eos_token=eos_token,
  108. pad_token=pad_token,
  109. add_prefix_space=add_prefix_space,
  110. return_token_type_ids=return_token_type_ids,
  111. **kwargs,
  112. )
  113. def decode(
  114. self,
  115. token_ids: Union[int, list[int], np.ndarray, "torch.Tensor"],
  116. skip_special_tokens: bool = False,
  117. clean_up_tokenization_spaces: bool | None = None,
  118. truncate_before_pattern: list[str] | None = None,
  119. **kwargs,
  120. ) -> str:
  121. """
  122. Converts a sequence of ids in a string, using the tokenizer and vocabulary with options to remove special
  123. tokens and clean up tokenization spaces.
  124. Similar to doing `self.convert_tokens_to_string(self.convert_ids_to_tokens(token_ids))`.
  125. Args:
  126. token_ids (`Union[int, List[int], np.ndarray, torch.Tensor]`):
  127. List of tokenized input ids. Can be obtained using the `__call__` method.
  128. skip_special_tokens (`bool`, *optional*, defaults to `False`):
  129. Whether or not to remove special tokens in the decoding.
  130. clean_up_tokenization_spaces (`bool`, *optional*):
  131. Whether or not to clean up the tokenization spaces. If `None`, will default to
  132. `self.clean_up_tokenization_spaces` (available in the `tokenizer_config`).
  133. truncate_before_pattern (`List[str]`, *optional*, defaults to `None`):
  134. A list of regular expression strings that will be used to truncate the returned string. This can be
  135. used to remove extra pieces of code (e.g. truncate if observing a comment symbol "#" at the beginning
  136. of a new line). An example pattern could be `["^#", re.escape("<|endoftext|>"), "^'''", "\n\n\n"]`.
  137. kwargs (additional keyword arguments, *optional*):
  138. Will be passed to the underlying model specific decode method.
  139. Returns:
  140. `str`: The decoded sentence.
  141. """
  142. decoded_text = super().decode(
  143. token_ids=token_ids,
  144. skip_special_tokens=skip_special_tokens,
  145. clean_up_tokenization_spaces=clean_up_tokenization_spaces,
  146. **kwargs,
  147. )
  148. if truncate_before_pattern is not None and len(truncate_before_pattern) > 0:
  149. decoded_text = self.truncate(decoded_text, truncate_before_pattern)
  150. return decoded_text
  151. def truncate(self, completion, truncate_before_pattern):
  152. def find_re(string, pattern, start_pos):
  153. m = pattern.search(string, start_pos)
  154. return m.start() if m else -1
  155. terminals = [re.compile(pattern, re.MULTILINE) for pattern in truncate_before_pattern]
  156. prints = list(re.finditer("^print", completion, re.MULTILINE))
  157. if len(prints) > 1:
  158. completion = completion[: prints[1].start()]
  159. defs = list(re.finditer("^def", completion, re.MULTILINE))
  160. if len(defs) > 1:
  161. completion = completion[: defs[1].start()]
  162. start_pos = 0
  163. terminals_pos = [
  164. pos for pos in [find_re(completion, terminal, start_pos) for terminal in terminals] if pos != -1
  165. ]
  166. if len(terminals_pos) > 0:
  167. return completion[: min(terminals_pos)]
  168. else:
  169. return completion
  170. __all__ = ["CodeGenTokenizer"]