tokenization_ctrl.py 7.9 KB

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