tokenization_ctrl.py 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  1. # Copyright 2018 Salesforce 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 Salesforce CTRL."""
  15. import json
  16. import regex as re
  17. from ...tokenization_python import PreTrainedTokenizer
  18. from ...utils import logging
  19. logger = logging.get_logger(__name__)
  20. VOCAB_FILES_NAMES = {
  21. "vocab_file": "vocab.json",
  22. "merges_file": "merges.txt",
  23. }
  24. CONTROL_CODES = {
  25. "Pregnancy": 168629,
  26. "Christianity": 7675,
  27. "Explain": 106423,
  28. "Fitness": 63440,
  29. "Saving": 63163,
  30. "Ask": 27171,
  31. "Ass": 95985,
  32. "Joke": 163509,
  33. "Questions": 45622,
  34. "Thoughts": 49605,
  35. "Retail": 52342,
  36. "Feminism": 164338,
  37. "Writing": 11992,
  38. "Atheism": 192263,
  39. "Netflix": 48616,
  40. "Computing": 39639,
  41. "Opinion": 43213,
  42. "Alone": 44967,
  43. "Funny": 58917,
  44. "Gaming": 40358,
  45. "Human": 4088,
  46. "India": 1331,
  47. "Joker": 77138,
  48. "Diet": 36206,
  49. "Legal": 11859,
  50. "Norman": 4939,
  51. "Tip": 72689,
  52. "Weight": 52343,
  53. "Movies": 46273,
  54. "Running": 23425,
  55. "Science": 2090,
  56. "Horror": 37793,
  57. "Confession": 60572,
  58. "Finance": 12250,
  59. "Politics": 16360,
  60. "Scary": 191985,
  61. "Support": 12654,
  62. "Technologies": 32516,
  63. "Teenage": 66160,
  64. "Event": 32769,
  65. "Learned": 67460,
  66. "Notion": 182770,
  67. "Wikipedia": 37583,
  68. "Books": 6665,
  69. "Extract": 76050,
  70. "Confessions": 102701,
  71. "Conspiracy": 75932,
  72. "Links": 63674,
  73. "Narcissus": 150425,
  74. "Relationship": 54766,
  75. "Relationships": 134796,
  76. "Reviews": 41671,
  77. "News": 4256,
  78. "Translation": 26820,
  79. "multilingual": 128406,
  80. }
  81. def get_pairs(word):
  82. """
  83. Return set of symbol pairs in a word.
  84. Word is represented as tuple of symbols (symbols being variable-length strings).
  85. """
  86. pairs = set()
  87. prev_char = word[0]
  88. for char in word[1:]:
  89. pairs.add((prev_char, char))
  90. prev_char = char
  91. pairs = set(pairs)
  92. return pairs
  93. class CTRLTokenizer(PreTrainedTokenizer):
  94. """
  95. Construct a CTRL tokenizer. Based on Byte-Pair-Encoding.
  96. This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
  97. this superclass for more information regarding those methods.
  98. Args:
  99. vocab_file (`str`):
  100. Path to the vocabulary file.
  101. merges_file (`str`):
  102. Path to the merges file.
  103. unk_token (`str`, *optional*, defaults to `"<unk>"`):
  104. The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
  105. token instead.
  106. """
  107. vocab_files_names = VOCAB_FILES_NAMES
  108. control_codes = CONTROL_CODES
  109. def __init__(self, vocab_file, merges_file, unk_token="<unk>", **kwargs):
  110. with open(vocab_file, encoding="utf-8") as vocab_handle:
  111. self.encoder = json.load(vocab_handle)
  112. self.decoder = {v: k for k, v in self.encoder.items()}
  113. with open(merges_file, encoding="utf-8") as merges_handle:
  114. merges = merges_handle.read().split("\n")[1:-1]
  115. merges = [tuple(merge.split()) for merge in merges]
  116. self.bpe_ranks = dict(zip(merges, range(len(merges))))
  117. self.cache = {}
  118. self.add_bpe_version_header = True
  119. super().__init__(
  120. unk_token=unk_token,
  121. token_type_ids_pattern="all_zeros",
  122. token_type_ids_include_special_tokens=True,
  123. special_tokens_pattern="none",
  124. **kwargs,
  125. )
  126. @property
  127. def vocab_size(self):
  128. return len(self.encoder)
  129. def get_vocab(self):
  130. return dict(self.encoder, **self.added_tokens_encoder)
  131. def bpe(self, token):
  132. if token in self.cache:
  133. return self.cache[token]
  134. word = tuple(token)
  135. word = tuple(list(word[:-1]) + [word[-1] + "</w>"])
  136. pairs = get_pairs(word)
  137. if not pairs:
  138. return token
  139. while True:
  140. bigram = min(pairs, key=lambda pair: self.bpe_ranks.get(pair, float("inf")))
  141. if bigram not in self.bpe_ranks:
  142. break
  143. first, second = bigram
  144. new_word = []
  145. i = 0
  146. while i < len(word):
  147. try:
  148. j = word.index(first, i)
  149. except ValueError:
  150. new_word.extend(word[i:])
  151. break
  152. else:
  153. new_word.extend(word[i:j])
  154. i = j
  155. if word[i] == first and i < len(word) - 1 and word[i + 1] == second:
  156. new_word.append(first + second)
  157. i += 2
  158. else:
  159. new_word.append(word[i])
  160. i += 1
  161. new_word = tuple(new_word)
  162. word = new_word
  163. if len(word) == 1:
  164. break
  165. else:
  166. pairs = get_pairs(word)
  167. word = "@@ ".join(word)
  168. word = word[:-4]
  169. self.cache[token] = word
  170. return word
  171. def _tokenize(self, text):
  172. """Tokenize a string."""
  173. split_tokens = []
  174. words = re.findall(r"\S+\n?", text)
  175. for token in words:
  176. split_tokens.extend(list(self.bpe(token).split(" ")))
  177. return split_tokens
  178. def _convert_token_to_id(self, token):
  179. """Converts a token (str) in an id using the vocab."""
  180. return self.encoder.get(token, self.encoder.get(self.unk_token))
  181. def _convert_id_to_token(self, index):
  182. """Converts an index (integer) in a token (str) using the vocab."""
  183. return self.decoder.get(index, self.unk_token)
  184. def convert_tokens_to_string(self, tokens):
  185. """Converts a sequence of tokens (string) in a single string."""
  186. out_string = " ".join(tokens).replace("@@ ", "").strip()
  187. return out_string
  188. # def decode(self, token_ids, skip_special_tokens=False, clean_up_tokenization_spaces=True):
  189. # filtered_tokens = ' '.join(self.convert_ids_to_tokens(token_ids, skip_special_tokens=skip_special_tokens))
  190. # tokens_generated_so_far = re.sub('(@@ )', '', string=filtered_tokens)
  191. # tokens_generated_so_far = re.sub('(@@ ?$)', '', string=tokens_generated_so_far)
  192. # return ''.join(tokens_generated_so_far)
  193. __all__ = ["CTRLTokenizer"]