tokenization_pegasus.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  1. # coding=utf-8
  2. # Copyright 2020 Google 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. import os
  16. from shutil import copyfile
  17. from typing import Any, Dict, List, Optional, Tuple
  18. import sentencepiece as spm
  19. from ...tokenization_utils import AddedToken, PreTrainedTokenizer
  20. from ...utils import logging
  21. SPIECE_UNDERLINE = "▁"
  22. VOCAB_FILES_NAMES = {"vocab_file": "spiece.model"}
  23. logger = logging.get_logger(__name__)
  24. # TODO ArthurZ refactor this to only use the added_tokens_encoder
  25. class PegasusTokenizer(PreTrainedTokenizer):
  26. r"""
  27. Construct a PEGASUS tokenizer. Based on [SentencePiece](https://github.com/google/sentencepiece).
  28. This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
  29. this superclass for more information regarding those methods.
  30. Args:
  31. vocab_file (`str`):
  32. [SentencePiece](https://github.com/google/sentencepiece) file (generally has a *.spm* extension) that
  33. contains the vocabulary necessary to instantiate a tokenizer.
  34. pad_token (`str`, *optional*, defaults to `"<pad>"`):
  35. The token used for padding, for example when batching sequences of different lengths.
  36. eos_token (`str`, *optional*, defaults to `"</s>"`):
  37. The end of sequence token.
  38. <Tip>
  39. When building a sequence using special tokens, this is not the token that is used for the end of sequence.
  40. The token used is the `sep_token`.
  41. </Tip>
  42. unk_token (`str`, *optional*, defaults to `"<unk>"`):
  43. The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
  44. token instead.
  45. mask_token (`str`, *optional*, defaults to `"<mask_2>"`):
  46. The token used for masking single token values. This is the token used when training this model with masked
  47. language modeling (MLM). This is the token that the PEGASUS encoder will try to predict during pretraining.
  48. It corresponds to *[MASK2]* in [PEGASUS: Pre-training with Extracted Gap-sentences for Abstractive
  49. Summarization](https://arxiv.org/pdf/1912.08777.pdf).
  50. mask_token_sent (`str`, *optional*, defaults to `"<mask_1>"`):
  51. The token used for masking whole target sentences. This is the token used when training this model with gap
  52. sentences generation (GSG). This is the sentence that the PEGASUS decoder will try to predict during
  53. pretraining. It corresponds to *[MASK1]* in [PEGASUS: Pre-training with Extracted Gap-sentences for
  54. Abstractive Summarization](https://arxiv.org/pdf/1912.08777.pdf).
  55. additional_special_tokens (`List[str]`, *optional*):
  56. Additional special tokens used by the tokenizer. If no additional_special_tokens are provided <mask_2> and
  57. <unk_2, ..., unk_102> are used as additional special tokens corresponding to the [original PEGASUS
  58. tokenizer](https://github.com/google-research/pegasus/blob/939830367bcf411193d2b5eca2f2f90f3f9260ca/pegasus/ops/pretrain_parsing_ops.cc#L66)
  59. that uses the tokens 2 - 104 only for pretraining
  60. sp_model_kwargs (`dict`, *optional*):
  61. Will be passed to the `SentencePieceProcessor.__init__()` method. The [Python wrapper for
  62. SentencePiece](https://github.com/google/sentencepiece/tree/master/python) can be used, among other things,
  63. to set:
  64. - `enable_sampling`: Enable subword regularization.
  65. - `nbest_size`: Sampling parameters for unigram. Invalid for BPE-Dropout.
  66. - `nbest_size = {0,1}`: No sampling is performed.
  67. - `nbest_size > 1`: samples from the nbest_size results.
  68. - `nbest_size < 0`: assuming that nbest_size is infinite and samples from the all hypothesis (lattice)
  69. using forward-filtering-and-backward-sampling algorithm.
  70. - `alpha`: Smoothing parameter for unigram sampling, and dropout probability of merge operations for
  71. BPE-dropout.
  72. """
  73. vocab_files_names = VOCAB_FILES_NAMES
  74. model_input_names = ["input_ids", "attention_mask"]
  75. def __init__(
  76. self,
  77. vocab_file,
  78. pad_token="<pad>",
  79. eos_token="</s>",
  80. unk_token="<unk>",
  81. mask_token="<mask_2>",
  82. mask_token_sent="<mask_1>",
  83. additional_special_tokens=None,
  84. offset=103, # entries 2 - 104 are only used for pretraining
  85. sp_model_kwargs: Optional[Dict[str, Any]] = None,
  86. **kwargs,
  87. ) -> None:
  88. self.offset = offset
  89. if additional_special_tokens is not None:
  90. if not isinstance(additional_special_tokens, list):
  91. raise TypeError(
  92. f"additional_special_tokens should be of type {type(list)}, but is"
  93. f" {type(additional_special_tokens)}"
  94. )
  95. additional_special_tokens_extended = (
  96. ([mask_token_sent] + additional_special_tokens)
  97. if mask_token_sent not in additional_special_tokens and mask_token_sent is not None
  98. else additional_special_tokens
  99. )
  100. # fill additional tokens with ..., <unk_token_102> in case not all additional tokens are already taken
  101. additional_special_tokens_extended += [
  102. f"<unk_{i}>" for i in range(len(additional_special_tokens_extended), self.offset - 1)
  103. ]
  104. if len(set(additional_special_tokens_extended)) != len(additional_special_tokens_extended):
  105. raise ValueError(
  106. "Please make sure that the provided additional_special_tokens do not contain an incorrectly"
  107. f" shifted list of <unk_x> tokens. Found {additional_special_tokens_extended}."
  108. )
  109. additional_special_tokens = additional_special_tokens_extended
  110. else:
  111. additional_special_tokens_extended = []
  112. additional_special_tokens = [mask_token_sent] if mask_token_sent is not None else []
  113. additional_special_tokens += [f"<unk_{i}>" for i in range(2, self.offset)]
  114. self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs
  115. self.mask_token_sent = mask_token_sent
  116. self.vocab_file = vocab_file
  117. self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
  118. self.sp_model.Load(vocab_file)
  119. _added_tokens_decoder = {
  120. 0: AddedToken(str(pad_token), special=True),
  121. 1: AddedToken(str(eos_token), special=True),
  122. }
  123. if self.mask_token_sent is not None:
  124. _added_tokens_decoder[2] = AddedToken(mask_token_sent, special=True)
  125. _added_tokens_decoder[3] = AddedToken(str(mask_token), special=True)
  126. for i in range(2, self.offset):
  127. _added_tokens_decoder[len(_added_tokens_decoder)] = AddedToken(f"<unk_{i}>", special=True)
  128. # Force update as we want to make sure vocab is enforced (same as fast)
  129. self._added_tokens_decoder = kwargs.pop("added_tokens_decoder", {})
  130. self._added_tokens_decoder.update(_added_tokens_decoder)
  131. super().__init__(
  132. eos_token=eos_token,
  133. unk_token=unk_token,
  134. mask_token=mask_token,
  135. pad_token=pad_token,
  136. mask_token_sent=mask_token_sent,
  137. offset=offset,
  138. additional_special_tokens=additional_special_tokens,
  139. sp_model_kwargs=self.sp_model_kwargs,
  140. **kwargs,
  141. )
  142. @property
  143. def vocab_size(self) -> int:
  144. return len(self.sp_model) + self.offset
  145. def get_vocab(self) -> Dict[str, int]:
  146. vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size)}
  147. vocab.update(self.added_tokens_encoder)
  148. return vocab
  149. def __getstate__(self):
  150. state = self.__dict__.copy()
  151. state["sp_model"] = None
  152. return state
  153. def __setstate__(self, d):
  154. self.__dict__ = d
  155. # for backward compatibility
  156. if not hasattr(self, "sp_model_kwargs"):
  157. self.sp_model_kwargs = {}
  158. self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
  159. self.sp_model.Load(self.vocab_file)
  160. def _tokenize(self, text: str) -> List[str]:
  161. """Take as input a string and return a list of strings (tokens) for words/sub-words"""
  162. return self.sp_model.encode(text, out_type=str)
  163. def _convert_token_to_id(self, token: str) -> int:
  164. """Converts a token (str) to an id using the vocab."""
  165. sp_id = self.sp_model.piece_to_id(token)
  166. return sp_id + self.offset
  167. def _convert_id_to_token(self, index: int) -> str:
  168. """Converts an index (integer) to a token (str) using the vocab."""
  169. if index < self.offset:
  170. return self.sp_model.IdToPiece(index)
  171. token = self.sp_model.IdToPiece(index - self.offset)
  172. return token
  173. def convert_tokens_to_string(self, tokens):
  174. """Converts a sequence of tokens (string) in a single string."""
  175. current_sub_tokens = []
  176. out_string = ""
  177. for token in tokens:
  178. # make sure that special tokens are not decoded using sentencepiece model
  179. if token in self.all_special_tokens:
  180. out_string += self.sp_model.decode(current_sub_tokens) + token
  181. current_sub_tokens = []
  182. else:
  183. current_sub_tokens.append(token)
  184. out_string += self.sp_model.decode(current_sub_tokens)
  185. return out_string.strip()
  186. def num_special_tokens_to_add(self, pair=False):
  187. """Just EOS"""
  188. return 1
  189. def _special_token_mask(self, seq):
  190. all_special_ids = set(self.all_special_ids) # call it once instead of inside list comp
  191. all_special_ids.remove(self.unk_token_id) # <unk> is only sometimes special
  192. return [1 if x in all_special_ids else 0 for x in seq]
  193. def get_special_tokens_mask(
  194. self, token_ids_0: List, token_ids_1: Optional[List] = None, already_has_special_tokens: bool = False
  195. ) -> List[int]:
  196. """Get list where entries are [1] if a token is [eos] or [pad] else 0."""
  197. if already_has_special_tokens:
  198. return self._special_token_mask(token_ids_0)
  199. elif token_ids_1 is None:
  200. return self._special_token_mask(token_ids_0) + [1]
  201. else:
  202. return self._special_token_mask(token_ids_0 + token_ids_1) + [1]
  203. def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None) -> List[int]:
  204. """
  205. Build model inputs from a sequence or a pair of sequences for sequence classification tasks by concatenating
  206. and adding special tokens. A PEGASUS sequence has the following format, where `X` represents the sequence:
  207. - single sequence: `X </s>`
  208. - pair of sequences: `A B </s>` (not intended use)
  209. BOS is never used. Pairs of sequences are not the expected use case, but they will be handled without a
  210. separator.
  211. Args:
  212. token_ids_0 (`List[int]`):
  213. List of IDs to which the special tokens will be added.
  214. token_ids_1 (`List[int]`, *optional*):
  215. Optional second list of IDs for sequence pairs.
  216. Returns:
  217. `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
  218. """
  219. if token_ids_1 is None:
  220. return token_ids_0 + [self.eos_token_id]
  221. # We don't expect to process pairs, but leave the pair logic for API consistency
  222. return token_ids_0 + token_ids_1 + [self.eos_token_id]
  223. def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
  224. if not os.path.isdir(save_directory):
  225. logger.error(f"Vocabulary path ({save_directory}) should be a directory")
  226. return
  227. out_vocab_file = os.path.join(
  228. save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
  229. )
  230. if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file) and os.path.isfile(self.vocab_file):
  231. copyfile(self.vocab_file, out_vocab_file)
  232. elif not os.path.isfile(self.vocab_file):
  233. with open(out_vocab_file, "wb") as fi:
  234. content_spiece_model = self.sp_model.serialized_model_proto()
  235. fi.write(content_spiece_model)
  236. return (out_vocab_file,)