tokenization_biogpt.py 12 KB

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