tokenization_biogpt.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  1. # Copyright 2022 The HuggingFace Team and Microsoft Research AI4Science. 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. """Tokenization classes for BioGPT."""
  15. import json
  16. import os
  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. def get_pairs(word):
  25. """
  26. Return set of symbol pairs in a word. word is represented as tuple of symbols (symbols being variable-length
  27. strings)
  28. """
  29. pairs = set()
  30. prev_char = word[0]
  31. for char in word[1:]:
  32. pairs.add((prev_char, char))
  33. prev_char = char
  34. return pairs
  35. class BioGptTokenizer(PreTrainedTokenizer):
  36. """
  37. Construct an FAIRSEQ Transformer tokenizer. Moses tokenization followed by Byte-Pair Encoding.
  38. This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
  39. this superclass for more information regarding those methods.
  40. Args:
  41. vocab_file (`str`):
  42. Path to the vocabulary file.
  43. merges_file (`str`):
  44. Merges file.
  45. unk_token (`str`, *optional*, defaults to `"<unk>"`):
  46. The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
  47. token instead.
  48. bos_token (`str`, *optional*, defaults to `"<s>"`):
  49. The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.
  50. <Tip>
  51. When building a sequence using special tokens, this is not the token that is used for the beginning of
  52. sequence. The token used is the `cls_token`.
  53. </Tip>
  54. eos_token (`str`, *optional*, defaults to `"</s>"`):
  55. The end of sequence token.
  56. <Tip>
  57. When building a sequence using special tokens, this is not the token that is used for the end of sequence.
  58. The token used is the `sep_token`.
  59. </Tip>
  60. sep_token (`str`, *optional*, defaults to `"</s>"`):
  61. The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
  62. sequence classification or for a text and a question for question answering. It is also used as the last
  63. token of a sequence built with special tokens.
  64. pad_token (`str`, *optional*, defaults to `"<pad>"`):
  65. The token used for padding, for example when batching sequences of different lengths.
  66. """
  67. vocab_files_names = VOCAB_FILES_NAMES
  68. model_input_names = ["input_ids", "attention_mask"]
  69. def __init__(
  70. self,
  71. vocab_file,
  72. merges_file,
  73. unk_token="<unk>",
  74. bos_token="<s>",
  75. eos_token="</s>",
  76. sep_token="</s>",
  77. pad_token="<pad>",
  78. **kwargs,
  79. ):
  80. try:
  81. import sacremoses
  82. except ImportError:
  83. raise ImportError(
  84. "You need to install sacremoses to use BioGptTokenizer. "
  85. "See https://pypi.org/project/sacremoses/ for installation."
  86. )
  87. self.lang = "en"
  88. self.sm = sacremoses
  89. # cache of sm.MosesTokenizer instance
  90. self.cache_moses_tokenizer = {}
  91. self.cache_moses_detokenizer = {}
  92. """ Initialisation"""
  93. with open(vocab_file, encoding="utf-8") as vocab_handle:
  94. self.encoder = json.load(vocab_handle)
  95. self.decoder = {v: k for k, v in self.encoder.items()}
  96. with open(merges_file, encoding="utf-8") as merges_handle:
  97. merges = merges_handle.read().split("\n")[:-1]
  98. merges = [tuple(merge.split()[:2]) for merge in merges]
  99. self.bpe_ranks = dict(zip(merges, range(len(merges))))
  100. self.cache = {}
  101. super().__init__(
  102. bos_token=bos_token,
  103. eos_token=eos_token,
  104. sep_token=sep_token,
  105. unk_token=unk_token,
  106. pad_token=pad_token,
  107. **kwargs,
  108. )
  109. @property
  110. def vocab_size(self):
  111. """Returns vocab size"""
  112. return len(self.encoder)
  113. def get_vocab(self):
  114. return dict(self.encoder, **self.added_tokens_encoder)
  115. def moses_tokenize(self, text, lang):
  116. if lang not in self.cache_moses_tokenizer:
  117. moses_tokenizer = self.sm.MosesTokenizer(lang=lang)
  118. self.cache_moses_tokenizer[lang] = moses_tokenizer
  119. return self.cache_moses_tokenizer[lang].tokenize(
  120. text, aggressive_dash_splits=True, return_str=False, escape=True
  121. )
  122. def moses_detokenize(self, tokens, lang):
  123. if lang not in self.cache_moses_detokenizer:
  124. moses_detokenizer = self.sm.MosesDetokenizer(lang=lang)
  125. self.cache_moses_detokenizer[lang] = moses_detokenizer
  126. return self.cache_moses_detokenizer[lang].detokenize(tokens)
  127. def bpe(self, token):
  128. word = tuple(token[:-1]) + (token[-1] + "</w>",)
  129. if token in self.cache:
  130. return self.cache[token]
  131. pairs = get_pairs(word)
  132. if not pairs:
  133. return token + "</w>"
  134. while True:
  135. bigram = min(pairs, key=lambda pair: self.bpe_ranks.get(pair, float("inf")))
  136. if bigram not in self.bpe_ranks:
  137. break
  138. first, second = bigram
  139. new_word = []
  140. i = 0
  141. while i < len(word):
  142. try:
  143. j = word.index(first, i)
  144. except ValueError:
  145. new_word.extend(word[i:])
  146. break
  147. else:
  148. new_word.extend(word[i:j])
  149. i = j
  150. if word[i] == first and i < len(word) - 1 and word[i + 1] == second:
  151. new_word.append(first + second)
  152. i += 2
  153. else:
  154. new_word.append(word[i])
  155. i += 1
  156. new_word = tuple(new_word)
  157. word = new_word
  158. if len(word) == 1:
  159. break
  160. else:
  161. pairs = get_pairs(word)
  162. word = " ".join(word)
  163. if word == "\n </w>":
  164. word = "\n</w>"
  165. self.cache[token] = word
  166. return word
  167. def _tokenize(self, text, bypass_tokenizer=False):
  168. """Returns a tokenized string."""
  169. if bypass_tokenizer:
  170. text = text.split()
  171. else:
  172. text = self.moses_tokenize(text, self.lang)
  173. split_tokens = []
  174. for token in text:
  175. if token:
  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. # remove BPE
  187. tokens = [t.replace(" ", "").replace("</w>", " ") for t in tokens]
  188. tokens = "".join(tokens).split()
  189. # detokenize
  190. text = self.moses_detokenize(tokens, self.lang)
  191. return text
  192. def build_inputs_with_special_tokens(
  193. self, token_ids_0: list[int], token_ids_1: list[int] | None = None
  194. ) -> list[int]:
  195. """
  196. Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
  197. adding special tokens. A BioGPT sequence has the following format:
  198. - single sequence: `</s> X `
  199. - pair of sequences: `</s> A </s> B `
  200. Args:
  201. token_ids_0 (`List[int]`):
  202. List of IDs to which the special tokens will be added.
  203. token_ids_1 (`List[int]`, *optional*):
  204. Optional second list of IDs for sequence pairs.
  205. Returns:
  206. `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
  207. """
  208. if token_ids_1 is None:
  209. return [self.sep_token_id] + token_ids_0
  210. sep = [self.sep_token_id]
  211. return sep + token_ids_0 + sep + token_ids_1
  212. def get_special_tokens_mask(
  213. self, token_ids_0: list[int], token_ids_1: list[int] | None = None, already_has_special_tokens: bool = False
  214. ) -> list[int]:
  215. """
  216. Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
  217. special tokens using the tokenizer `prepare_for_model` method.
  218. Args:
  219. token_ids_0 (`List[int]`):
  220. List of IDs.
  221. token_ids_1 (`List[int]`, *optional*):
  222. Optional second list of IDs for sequence pairs.
  223. already_has_special_tokens (`bool`, *optional*, defaults to `False`):
  224. Whether or not the token list is already formatted with special tokens for the model.
  225. Returns:
  226. `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
  227. """
  228. if already_has_special_tokens:
  229. return super().get_special_tokens_mask(
  230. token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
  231. )
  232. # no bos used in fairseq
  233. if token_ids_1 is not None:
  234. return [1] + ([0] * len(token_ids_0)) + [1] + ([0] * len(token_ids_1))
  235. return [1] + ([0] * len(token_ids_0))
  236. def save_vocabulary(self, save_directory: str, filename_prefix: str | None = None) -> tuple[str]:
  237. if not os.path.isdir(save_directory):
  238. logger.error(f"Vocabulary path ({save_directory}) should be a directory")
  239. return
  240. vocab_file = os.path.join(
  241. save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
  242. )
  243. merge_file = os.path.join(
  244. save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["merges_file"]
  245. )
  246. with open(vocab_file, "w", encoding="utf-8") as f:
  247. f.write(json.dumps(self.encoder, indent=2, sort_keys=True, ensure_ascii=False) + "\n")
  248. index = 0
  249. with open(merge_file, "w", encoding="utf-8") as writer:
  250. for bpe_tokens, token_index in sorted(self.bpe_ranks.items(), key=lambda kv: kv[1]):
  251. if index != token_index:
  252. logger.warning(
  253. f"Saving vocabulary to {merge_file}: BPE merge indices are not consecutive."
  254. " Please check that the tokenizer is not corrupted!"
  255. )
  256. index = token_index
  257. writer.write(" ".join(bpe_tokens) + "\n")
  258. index += 1
  259. return vocab_file, merge_file
  260. def __getstate__(self):
  261. state = self.__dict__.copy()
  262. state["sm"] = None
  263. return state
  264. def __setstate__(self, d):
  265. self.__dict__ = d
  266. try:
  267. import sacremoses
  268. except ImportError:
  269. raise ImportError(
  270. "You need to install sacremoses to use XLMTokenizer. "
  271. "See https://pypi.org/project/sacremoses/ for installation."
  272. )
  273. self.sm = sacremoses
  274. __all__ = ["BioGptTokenizer"]