tokenization_phobert.py 13 KB

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