tokenization_phobert.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  1. # Copyright (c) 2020, VinAI Research and the HuggingFace Inc. team.
  2. # Copyright 2018 The Open AI Team Authors 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 PhoBERT"""
  16. import os
  17. import re
  18. from shutil import copyfile
  19. from ...tokenization_python import PreTrainedTokenizer
  20. from ...utils import logging
  21. logger = logging.get_logger(__name__)
  22. VOCAB_FILES_NAMES = {
  23. "vocab_file": "vocab.txt",
  24. "merges_file": "bpe.codes",
  25. }
  26. def get_pairs(word):
  27. """
  28. Return set of symbol pairs in a word.
  29. Word is represented as tuple of symbols (symbols being variable-length 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. pairs = set(pairs)
  37. return pairs
  38. class PhobertTokenizer(PreTrainedTokenizer):
  39. """
  40. Construct a PhoBERT tokenizer. Based on Byte-Pair-Encoding.
  41. This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
  42. this superclass for more information regarding those methods.
  43. Args:
  44. vocab_file (`str`):
  45. Path to the vocabulary file.
  46. merges_file (`str`):
  47. Path to the merges file.
  48. bos_token (`st`, *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. cls_token (`str`, *optional*, defaults to `"<s>"`):
  65. The classifier token which is used when doing sequence classification (classification of the whole sequence
  66. instead of per-token classification). It is the first token of the sequence when built with special tokens.
  67. unk_token (`str`, *optional*, defaults to `"<unk>"`):
  68. The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
  69. token instead.
  70. pad_token (`str`, *optional*, defaults to `"<pad>"`):
  71. The token used for padding, for example when batching sequences of different lengths.
  72. mask_token (`str`, *optional*, defaults to `"<mask>"`):
  73. The token used for masking values. This is the token used when training this model with masked language
  74. modeling. This is the token which the model will try to predict.
  75. """
  76. vocab_files_names = VOCAB_FILES_NAMES
  77. def __init__(
  78. self,
  79. vocab_file,
  80. merges_file,
  81. bos_token="<s>",
  82. eos_token="</s>",
  83. sep_token="</s>",
  84. cls_token="<s>",
  85. unk_token="<unk>",
  86. pad_token="<pad>",
  87. mask_token="<mask>",
  88. **kwargs,
  89. ):
  90. self.vocab_file = vocab_file
  91. self.merges_file = merges_file
  92. self.encoder = {}
  93. self.encoder[str(bos_token)] = 0
  94. self.encoder[str(pad_token)] = 1
  95. self.encoder[str(eos_token)] = 2
  96. self.encoder[str(unk_token)] = 3
  97. self.add_from_file(vocab_file)
  98. self.decoder = {v: k for k, v in self.encoder.items()}
  99. with open(merges_file, encoding="utf-8") as merges_handle:
  100. merges = merges_handle.read().split("\n")[:-1]
  101. merges = [tuple(merge.split()[:-1]) for merge in merges]
  102. self.bpe_ranks = dict(zip(merges, range(len(merges))))
  103. self.cache = {}
  104. super().__init__(
  105. bos_token=bos_token,
  106. eos_token=eos_token,
  107. unk_token=unk_token,
  108. sep_token=sep_token,
  109. cls_token=cls_token,
  110. pad_token=pad_token,
  111. mask_token=mask_token,
  112. **kwargs,
  113. )
  114. def build_inputs_with_special_tokens(
  115. self, token_ids_0: list[int], token_ids_1: list[int] | None = None
  116. ) -> list[int]:
  117. """
  118. Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
  119. adding special tokens. A PhoBERT sequence has the following format:
  120. - single sequence: `<s> X </s>`
  121. - pair of sequences: `<s> A </s></s> B </s>`
  122. Args:
  123. token_ids_0 (`list[int]`):
  124. List of IDs to which the special tokens will be added.
  125. token_ids_1 (`list[int]`, *optional*):
  126. Optional second list of IDs for sequence pairs.
  127. Returns:
  128. `list[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
  129. """
  130. if token_ids_1 is None:
  131. return [self.cls_token_id] + token_ids_0 + [self.sep_token_id]
  132. cls = [self.cls_token_id]
  133. sep = [self.sep_token_id]
  134. return cls + token_ids_0 + sep + sep + token_ids_1 + sep
  135. def get_special_tokens_mask(
  136. self, token_ids_0: list[int], token_ids_1: list[int] | None = None, already_has_special_tokens: bool = False
  137. ) -> list[int]:
  138. """
  139. Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
  140. special tokens using the tokenizer `prepare_for_model` method.
  141. Args:
  142. token_ids_0 (`list[int]`):
  143. List of IDs.
  144. token_ids_1 (`list[int]`, *optional*):
  145. Optional second list of IDs for sequence pairs.
  146. already_has_special_tokens (`bool`, *optional*, defaults to `False`):
  147. Whether or not the token list is already formatted with special tokens for the model.
  148. Returns:
  149. `list[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
  150. """
  151. if already_has_special_tokens:
  152. return super().get_special_tokens_mask(
  153. token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
  154. )
  155. if token_ids_1 is None:
  156. return [1] + ([0] * len(token_ids_0)) + [1]
  157. return [1] + ([0] * len(token_ids_0)) + [1, 1] + ([0] * len(token_ids_1)) + [1]
  158. def create_token_type_ids_from_sequences(
  159. self, token_ids_0: list[int], token_ids_1: list[int] | None = None
  160. ) -> list[int]:
  161. """
  162. Create a mask from the two sequences passed to be used in a sequence-pair classification task. PhoBERT does not
  163. make use of token type ids, therefore a list of zeros is returned.
  164. Args:
  165. token_ids_0 (`list[int]`):
  166. List of IDs.
  167. token_ids_1 (`list[int]`, *optional*):
  168. Optional second list of IDs for sequence pairs.
  169. Returns:
  170. `list[int]`: List of zeros.
  171. """
  172. sep = [self.sep_token_id]
  173. cls = [self.cls_token_id]
  174. if token_ids_1 is None:
  175. return len(cls + token_ids_0 + sep) * [0]
  176. return len(cls + token_ids_0 + sep + sep + token_ids_1 + sep) * [0]
  177. @property
  178. def vocab_size(self):
  179. return len(self.encoder)
  180. def get_vocab(self):
  181. return dict(self.encoder, **self.added_tokens_encoder)
  182. def bpe(self, token):
  183. if token in self.cache:
  184. return self.cache[token]
  185. word = tuple(token)
  186. word = tuple(list(word[:-1]) + [word[-1] + "</w>"])
  187. pairs = get_pairs(word)
  188. if not pairs:
  189. return token
  190. while True:
  191. bigram = min(pairs, key=lambda pair: self.bpe_ranks.get(pair, float("inf")))
  192. if bigram not in self.bpe_ranks:
  193. break
  194. first, second = bigram
  195. new_word = []
  196. i = 0
  197. while i < len(word):
  198. try:
  199. j = word.index(first, i)
  200. except ValueError:
  201. new_word.extend(word[i:])
  202. break
  203. else:
  204. new_word.extend(word[i:j])
  205. i = j
  206. if word[i] == first and i < len(word) - 1 and word[i + 1] == second:
  207. new_word.append(first + second)
  208. i += 2
  209. else:
  210. new_word.append(word[i])
  211. i += 1
  212. new_word = tuple(new_word)
  213. word = new_word
  214. if len(word) == 1:
  215. break
  216. else:
  217. pairs = get_pairs(word)
  218. word = "@@ ".join(word)
  219. word = word[:-4]
  220. self.cache[token] = word
  221. return word
  222. def _tokenize(self, text):
  223. """Tokenize a string."""
  224. split_tokens = []
  225. words = re.findall(r"\S+\n?", text)
  226. for token in words:
  227. split_tokens.extend(list(self.bpe(token).split(" ")))
  228. return split_tokens
  229. def _convert_token_to_id(self, token):
  230. """Converts a token (str) in an id using the vocab."""
  231. return self.encoder.get(token, self.encoder.get(self.unk_token))
  232. def _convert_id_to_token(self, index):
  233. """Converts an index (integer) in a token (str) using the vocab."""
  234. return self.decoder.get(index, self.unk_token)
  235. def convert_tokens_to_string(self, tokens):
  236. """Converts a sequence of tokens (string) in a single string."""
  237. out_string = " ".join(tokens).replace("@@ ", "").strip()
  238. return out_string
  239. def save_vocabulary(self, save_directory: str, filename_prefix: str | None = None) -> tuple[str]:
  240. if not os.path.isdir(save_directory):
  241. logger.error(f"Vocabulary path ({save_directory}) should be a directory")
  242. return
  243. out_vocab_file = os.path.join(
  244. save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
  245. )
  246. out_merge_file = os.path.join(
  247. save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["merges_file"]
  248. )
  249. if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file) and os.path.isfile(self.vocab_file):
  250. copyfile(self.vocab_file, out_vocab_file)
  251. elif not os.path.isfile(self.vocab_file):
  252. with open(out_vocab_file, "wb") as fi:
  253. content_spiece_model = self.sp_model.serialized_model_proto()
  254. fi.write(content_spiece_model)
  255. if os.path.abspath(self.merges_file) != os.path.abspath(out_merge_file):
  256. copyfile(self.merges_file, out_merge_file)
  257. return out_vocab_file, out_merge_file
  258. # def decode(self, token_ids, skip_special_tokens=False, clean_up_tokenization_spaces=True):
  259. # filtered_tokens = ' '.join(self.convert_ids_to_tokens(token_ids, skip_special_tokens=skip_special_tokens))
  260. # tokens_generated_so_far = re.sub('(@@ )', '', string=filtered_tokens)
  261. # tokens_generated_so_far = re.sub('(@@ ?$)', '', string=tokens_generated_so_far)
  262. # return ''.join(tokens_generated_so_far)
  263. def add_from_file(self, f):
  264. """
  265. Loads a pre-existing dictionary from a text file and adds its symbols to this instance.
  266. """
  267. if isinstance(f, str):
  268. try:
  269. with open(f, "r", encoding="utf-8") as fd:
  270. self.add_from_file(fd)
  271. except FileNotFoundError as fnfe:
  272. raise fnfe
  273. except UnicodeError:
  274. raise Exception(f"Incorrect encoding detected in {f}, please rebuild the dataset")
  275. return
  276. lines = f.readlines()
  277. for lineTmp in lines:
  278. line = lineTmp.strip()
  279. idx = line.rfind(" ")
  280. if idx == -1:
  281. raise ValueError("Incorrect dictionary format, expected '<token> <cnt>'")
  282. word = line[:idx]
  283. self.encoder[word] = len(self.encoder)
  284. __all__ = ["PhobertTokenizer"]