tokenization_xglm.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  1. # coding=utf-8
  2. # Copyright The HuggingFace Team and The HuggingFace Inc. team. 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 ."""
  16. import os
  17. from shutil import copyfile
  18. from typing import Any, Optional
  19. import sentencepiece as spm
  20. from ...tokenization_utils import PreTrainedTokenizer
  21. from ...utils import logging
  22. from ...utils.import_utils import requires
  23. logger = logging.get_logger(__name__)
  24. SPIECE_UNDERLINE = "▁"
  25. VOCAB_FILES_NAMES = {"vocab_file": "sentencepiece.bpe.model"}
  26. @requires(backends=("sentencepiece",))
  27. class XGLMTokenizer(PreTrainedTokenizer):
  28. """
  29. Adapted from [`RobertaTokenizer`] and [`XLNetTokenizer`]. Based on
  30. [SentencePiece](https://github.com/google/sentencepiece).
  31. This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
  32. this superclass for more information regarding those methods.
  33. Args:
  34. vocab_file (`str`):
  35. Path to the vocabulary file.
  36. bos_token (`str`, *optional*, defaults to `"<s>"`):
  37. The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.
  38. <Tip>
  39. When building a sequence using special tokens, this is not the token that is used for the beginning of
  40. sequence. The token used is the `cls_token`.
  41. </Tip>
  42. eos_token (`str`, *optional*, defaults to `"</s>"`):
  43. The end of sequence token.
  44. <Tip>
  45. When building a sequence using special tokens, this is not the token that is used for the end of sequence.
  46. The token used is the `sep_token`.
  47. </Tip>
  48. sep_token (`str`, *optional*, defaults to `"</s>"`):
  49. The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
  50. sequence classification or for a text and a question for question answering. It is also used as the last
  51. token of a sequence built with special tokens.
  52. cls_token (`str`, *optional*, defaults to `"<s>"`):
  53. The classifier token which is used when doing sequence classification (classification of the whole sequence
  54. instead of per-token classification). It is the first token of the sequence when built with special tokens.
  55. unk_token (`str`, *optional*, defaults to `"<unk>"`):
  56. The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
  57. token instead.
  58. pad_token (`str`, *optional*, defaults to `"<pad>"`):
  59. The token used for padding, for example when batching sequences of different lengths.
  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. Attributes:
  73. sp_model (`SentencePieceProcessor`):
  74. The *SentencePiece* processor that is used for every conversion (string, tokens and IDs).
  75. """
  76. vocab_files_names = VOCAB_FILES_NAMES
  77. model_input_names = ["input_ids", "attention_mask"]
  78. def __init__(
  79. self,
  80. vocab_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. sp_model_kwargs: Optional[dict[str, Any]] = None,
  88. **kwargs,
  89. ) -> None:
  90. self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs
  91. # Compatibility with the original tokenizer
  92. self.num_madeup_words = 7
  93. madeup_words = [f"<madeupword{i}>" for i in range(self.num_madeup_words)]
  94. kwargs["additional_special_tokens"] = kwargs.get("additional_special_tokens", []) or []
  95. kwargs["additional_special_tokens"] += [
  96. word for word in madeup_words if word not in kwargs["additional_special_tokens"]
  97. ]
  98. self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
  99. self.sp_model.Load(str(vocab_file))
  100. self.vocab_file = vocab_file
  101. # Original fairseq vocab and spm vocab must be "aligned":
  102. # Vocab | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9
  103. # -------- | ------- | ------- | ------ | ------- | --- | --- | --- | ----- | ----- | ----
  104. # fairseq | '<s>' | '<pad>' | '</s>' | '<unk>' | ',' | '.' | '▁' | 's' | '▁de' | '-'
  105. # spm | '<unk>' | '<s>' | '</s>' | ',' | '.' | '▁' | 's' | '▁de' | '-' | '▁a'
  106. # The first "real" token "," has position 4 in the original fairseq vocab and position 3 in the spm vocab
  107. self.fairseq_offset = 1
  108. # Mimic fairseq token-to-id alignment for the first 4 token
  109. self.fairseq_tokens_to_ids = {"<s>": 0, "<pad>": 1, "</s>": 2, "<unk>": 3}
  110. sp_size = len(self.sp_model)
  111. madeup_words = {f"<madeupword{i}>": sp_size + i + self.fairseq_offset for i in range(self.num_madeup_words)}
  112. self.fairseq_tokens_to_ids.update(madeup_words)
  113. self.fairseq_ids_to_tokens = {v: k for k, v in self.fairseq_tokens_to_ids.items()}
  114. super().__init__(
  115. bos_token=bos_token,
  116. eos_token=eos_token,
  117. unk_token=unk_token,
  118. sep_token=sep_token,
  119. cls_token=cls_token,
  120. pad_token=pad_token,
  121. sp_model_kwargs=self.sp_model_kwargs,
  122. **kwargs,
  123. )
  124. def __getstate__(self):
  125. state = self.__dict__.copy()
  126. state["sp_model"] = None
  127. state["sp_model_proto"] = self.sp_model.serialized_model_proto()
  128. return state
  129. def __setstate__(self, d):
  130. self.__dict__ = d
  131. # for backward compatibility
  132. if not hasattr(self, "sp_model_kwargs"):
  133. self.sp_model_kwargs = {}
  134. self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
  135. self.sp_model.LoadFromSerializedProto(self.sp_model_proto)
  136. def build_inputs_with_special_tokens(
  137. self, token_ids_0: list[int], token_ids_1: Optional[list[int]] = None
  138. ) -> list[int]:
  139. """
  140. Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
  141. adding special tokens. An XLM-RoBERTa sequence has the following format:
  142. - single sequence: `<s> X </s>`
  143. - pair of sequences: `<s> A </s></s> B </s>`
  144. Args:
  145. token_ids_0 (`list[int]`):
  146. List of IDs to which the special tokens will be added.
  147. token_ids_1 (`list[int]`, *optional*):
  148. Optional second list of IDs for sequence pairs.
  149. Returns:
  150. `list[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
  151. """
  152. if token_ids_1 is None:
  153. return [self.sep_token_id] + token_ids_0
  154. sep = [self.sep_token_id]
  155. return sep + token_ids_0 + sep + sep + token_ids_1
  156. def get_special_tokens_mask(
  157. self, token_ids_0: list[int], token_ids_1: Optional[list[int]] = None, already_has_special_tokens: bool = False
  158. ) -> list[int]:
  159. """
  160. Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
  161. special tokens using the tokenizer `prepare_for_model` method.
  162. Args:
  163. token_ids_0 (`list[int]`):
  164. List of IDs.
  165. token_ids_1 (`list[int]`, *optional*):
  166. Optional second list of IDs for sequence pairs.
  167. already_has_special_tokens (`bool`, *optional*, defaults to `False`):
  168. Whether or not the token list is already formatted with special tokens for the model.
  169. Returns:
  170. `list[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
  171. """
  172. if already_has_special_tokens:
  173. return super().get_special_tokens_mask(
  174. token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
  175. )
  176. if token_ids_1 is None:
  177. return [1] + ([0] * len(token_ids_0))
  178. return [1] + ([0] * len(token_ids_0)) + [1, 1] + ([0] * len(token_ids_1))
  179. def create_token_type_ids_from_sequences(
  180. self, token_ids_0: list[int], token_ids_1: Optional[list[int]] = None
  181. ) -> list[int]:
  182. """
  183. Create a mask from the two sequences passed to be used in a sequence-pair classification task. XLM-RoBERTa does
  184. not make use of token type ids, therefore a list of zeros is returned.
  185. Args:
  186. token_ids_0 (`list[int]`):
  187. List of IDs.
  188. token_ids_1 (`list[int]`, *optional*):
  189. Optional second list of IDs for sequence pairs.
  190. Returns:
  191. `list[int]`: List of zeros.
  192. """
  193. sep = [self.sep_token_id]
  194. if token_ids_1 is None:
  195. return len(sep + token_ids_0) * [0]
  196. return len(sep + token_ids_0 + sep + sep + token_ids_1) * [0]
  197. @property
  198. def vocab_size(self):
  199. return len(self.sp_model) + self.fairseq_offset + self.num_madeup_words
  200. def get_vocab(self):
  201. vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size)}
  202. vocab.update(self.added_tokens_encoder)
  203. return vocab
  204. def _tokenize(self, text: str) -> list[str]:
  205. return self.sp_model.encode(text, out_type=str)
  206. def _convert_token_to_id(self, token):
  207. """Converts a token (str) in an id using the vocab."""
  208. if token in self.fairseq_tokens_to_ids:
  209. return self.fairseq_tokens_to_ids[token]
  210. spm_id = self.sp_model.PieceToId(token)
  211. # Need to return unknown token if the SP model returned 0
  212. return spm_id + self.fairseq_offset if spm_id else self.unk_token_id
  213. def _convert_id_to_token(self, index):
  214. """Converts an index (integer) in a token (str) using the vocab."""
  215. if index in self.fairseq_ids_to_tokens:
  216. return self.fairseq_ids_to_tokens[index]
  217. return self.sp_model.IdToPiece(index - self.fairseq_offset)
  218. def convert_tokens_to_string(self, tokens):
  219. """Converts a sequence of tokens (strings for sub-words) in a single string."""
  220. out_string = "".join(tokens).replace(SPIECE_UNDERLINE, " ").strip()
  221. return out_string
  222. def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> tuple[str]:
  223. if not os.path.isdir(save_directory):
  224. logger.error(f"Vocabulary path ({save_directory}) should be a directory")
  225. return
  226. out_vocab_file = os.path.join(
  227. save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
  228. )
  229. if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file) and os.path.isfile(self.vocab_file):
  230. copyfile(self.vocab_file, out_vocab_file)
  231. elif not os.path.isfile(self.vocab_file):
  232. with open(out_vocab_file, "wb") as fi:
  233. content_spiece_model = self.sp_model.serialized_model_proto()
  234. fi.write(content_spiece_model)
  235. return (out_vocab_file,)
  236. __all__ = ["XGLMTokenizer"]