tokenization_t5.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  1. # coding=utf-8
  2. # Copyright 2018 T5 Authors and 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 class for model T5."""
  16. import os
  17. import re
  18. import warnings
  19. from shutil import copyfile
  20. from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple
  21. import sentencepiece as spm
  22. from ...convert_slow_tokenizer import import_protobuf
  23. from ...tokenization_utils import PreTrainedTokenizer
  24. from ...tokenization_utils_base import AddedToken
  25. if TYPE_CHECKING:
  26. from ...tokenization_utils_base import TextInput
  27. from ...utils import logging
  28. logger = logging.get_logger(__name__)
  29. VOCAB_FILES_NAMES = {"vocab_file": "spiece.model"}
  30. # TODO(PVP) - this should be removed in Transformers v5
  31. SPIECE_UNDERLINE = "▁"
  32. class T5Tokenizer(PreTrainedTokenizer):
  33. """
  34. Construct a T5 tokenizer. Based on [SentencePiece](https://github.com/google/sentencepiece).
  35. This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
  36. this superclass for more information regarding those methods.
  37. Args:
  38. vocab_file (`str`):
  39. [SentencePiece](https://github.com/google/sentencepiece) file (generally has a *.spm* extension) that
  40. contains the vocabulary necessary to instantiate a tokenizer.
  41. eos_token (`str`, *optional*, defaults to `"</s>"`):
  42. The end of sequence token.
  43. <Tip>
  44. When building a sequence using special tokens, this is not the token that is used for the end of sequence.
  45. The token used is the `sep_token`.
  46. </Tip>
  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. pad_token (`str`, *optional*, defaults to `"<pad>"`):
  51. The token used for padding, for example when batching sequences of different lengths.
  52. extra_ids (`int`, *optional*, defaults to 100):
  53. Add a number of extra ids added to the vocabulary for use as sentinels. These tokens are
  54. accessible as "<extra_id_{%d}>" where "{%d}" is a number between 0 and extra_ids-1. These tokens can be
  55. retrieved by calling get_sentinel_tokens method and token ids can be by calling get_sentinel_token_ids
  56. method
  57. additional_special_tokens (`List[str]`, *optional*):
  58. Additional special tokens used by the tokenizer.
  59. sp_model_kwargs (`dict`, *optional*):
  60. Will be passed to the `SentencePieceProcessor.__init__()` method. The [Python wrapper for
  61. SentencePiece](https://github.com/google/sentencepiece/tree/master/python) can be used, among other things,
  62. to set:
  63. - `enable_sampling`: Enable subword regularization.
  64. - `nbest_size`: Sampling parameters for unigram. Invalid for BPE-Dropout.
  65. - `nbest_size = {0,1}`: No sampling is performed.
  66. - `nbest_size > 1`: samples from the nbest_size results.
  67. - `nbest_size < 0`: assuming that nbest_size is infinite and samples from the all hypothesis (lattice)
  68. using forward-filtering-and-backward-sampling algorithm.
  69. - `alpha`: Smoothing parameter for unigram sampling, and dropout probability of merge operations for
  70. BPE-dropout.
  71. legacy (`bool`, *optional*):
  72. Whether or not the `legacy` behaviour of the tokenizer should be used. Legacy is before the merge of #24622
  73. and #25224 which includes fixes to properly handle tokens that appear after special tokens. A simple
  74. example:
  75. - `legacy=True`:
  76. ```python
  77. >>> from transformers import T5Tokenizer
  78. >>> tokenizer = T5Tokenizer.from_pretrained("google-t5/t5-base", legacy=True)
  79. >>> tokenizer.encode("Hello <extra_id_0>.")
  80. [8774, 32099, 3, 5, 1]
  81. ```
  82. - `legacy=False`:
  83. ```python
  84. >>> from transformers import T5Tokenizer
  85. >>> tokenizer = T5Tokenizer.from_pretrained("google-t5/t5-base", legacy=False)
  86. >>> tokenizer.encode("Hello <extra_id_0>.") # the extra space `[3]` is no longer here
  87. [8774, 32099, 5, 1]
  88. ```
  89. Checkout the [pull request](https://github.com/huggingface/transformers/pull/24565) for more details.
  90. add_prefix_space (`bool`, *optional*, defaults to `False`):
  91. Whether or not to add an initial space to the input. This allows to treat the leading word just as any
  92. other word.
  93. Attributes:
  94. sp_model (`SentencePieceProcessor`):
  95. The *SentencePiece* processor that is used for every conversion (string, tokens and IDs).
  96. """
  97. vocab_files_names = VOCAB_FILES_NAMES
  98. model_input_names = ["input_ids", "attention_mask"]
  99. def __init__(
  100. self,
  101. vocab_file,
  102. eos_token="</s>",
  103. unk_token="<unk>",
  104. pad_token="<pad>",
  105. extra_ids=100,
  106. additional_special_tokens=None,
  107. sp_model_kwargs: Optional[Dict[str, Any]] = None,
  108. legacy=None,
  109. add_prefix_space=True,
  110. **kwargs,
  111. ) -> None:
  112. pad_token = AddedToken(pad_token, special=True) if isinstance(pad_token, str) else pad_token
  113. unk_token = AddedToken(unk_token, special=True) if isinstance(unk_token, str) else unk_token
  114. eos_token = AddedToken(eos_token, special=True) if isinstance(eos_token, str) else eos_token
  115. self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs
  116. self.vocab_file = vocab_file
  117. self._extra_ids = extra_ids
  118. self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
  119. self.sp_model.Load(vocab_file)
  120. if additional_special_tokens is not None:
  121. extra_tokens = [x for x in additional_special_tokens if "<extra_id_" in str(x)]
  122. if len(extra_tokens) < 1:
  123. additional_special_tokens += [f"<extra_id_{i}>" for i in range(extra_ids)]
  124. elif extra_ids > 0 and extra_ids != len(extra_tokens):
  125. raise ValueError(
  126. f"Both extra_ids ({extra_ids}) and additional_special_tokens ({additional_special_tokens}) are"
  127. " provided to T5Tokenizer. In this case the additional_special_tokens must include the extra_ids"
  128. " tokens"
  129. )
  130. else:
  131. extra_tokens = [f"<extra_id_{i}>" for i in range(extra_ids)]
  132. additional_special_tokens = extra_tokens
  133. # for legacy purpose, we keep this. Will be removed and tests updated. (when `added_tokens_decoder` is not passed as kwargs)
  134. self._added_tokens_decoder = {}
  135. for i in range(len(extra_tokens)):
  136. self._added_tokens_decoder[len(self.sp_model) - 1 + extra_ids - i] = AddedToken(
  137. f"<extra_id_{i}>", single_word=False, lstrip=True, rstrip=True, special=True, normalized=False
  138. )
  139. if legacy is None:
  140. logger.warning_once(
  141. f"You are using the default legacy behaviour of the {self.__class__}. This is"
  142. " expected, and simply means that the `legacy` (previous) behavior will be used so nothing changes for you."
  143. " If you want to use the new behaviour, set `legacy=False`. This should only be set if you understand what it"
  144. " means, and thoroughly read the reason why this was added as explained in"
  145. " https://github.com/huggingface/transformers/pull/24565"
  146. )
  147. legacy = True
  148. self.legacy = legacy
  149. self.sp_model = self.get_spm_processor(kwargs.pop("from_slow", False))
  150. self.vocab_file = vocab_file
  151. self._extra_ids = extra_ids
  152. self.add_prefix_space = add_prefix_space
  153. super().__init__(
  154. eos_token=eos_token,
  155. unk_token=unk_token,
  156. pad_token=pad_token,
  157. extra_ids=extra_ids,
  158. additional_special_tokens=additional_special_tokens,
  159. sp_model_kwargs=self.sp_model_kwargs,
  160. legacy=legacy,
  161. add_prefix_space=add_prefix_space,
  162. **kwargs,
  163. )
  164. # Copied from transformers.models.t5.tokenization_t5.T5Tokenizer.get_spm_processor
  165. def get_spm_processor(self, from_slow=False):
  166. tokenizer = spm.SentencePieceProcessor(**self.sp_model_kwargs)
  167. if self.legacy or from_slow: # no dependency on protobuf
  168. tokenizer.Load(self.vocab_file)
  169. return tokenizer
  170. with open(self.vocab_file, "rb") as f:
  171. sp_model = f.read()
  172. model_pb2 = import_protobuf(f"The new behaviour of {self.__class__.__name__} (with `self.legacy = False`)")
  173. model = model_pb2.ModelProto.FromString(sp_model)
  174. normalizer_spec = model_pb2.NormalizerSpec()
  175. normalizer_spec.add_dummy_prefix = False
  176. model.normalizer_spec.MergeFrom(normalizer_spec)
  177. sp_model = model.SerializeToString()
  178. tokenizer.LoadFromSerializedProto(sp_model)
  179. return tokenizer
  180. @staticmethod
  181. def _eventually_correct_t5_max_length(pretrained_model_name_or_path, max_model_length, init_max_model_length):
  182. if pretrained_model_name_or_path in T5Tokenizer.max_model_input_sizes:
  183. deprecated_max_model_length = T5Tokenizer.max_model_input_sizes[pretrained_model_name_or_path]
  184. if init_max_model_length is not None and init_max_model_length != max_model_length:
  185. return init_max_model_length
  186. elif init_max_model_length is None:
  187. warnings.warn(
  188. "This tokenizer was incorrectly instantiated with a model max length of"
  189. f" {deprecated_max_model_length} which will be corrected in Transformers v5.\nFor now, this"
  190. " behavior is kept to avoid breaking backwards compatibility when padding/encoding with"
  191. " `truncation is True`.\n- Be aware that you SHOULD NOT rely on"
  192. f" {pretrained_model_name_or_path} automatically truncating your input to"
  193. f" {deprecated_max_model_length} when padding/encoding.\n- If you want to encode/pad to sequences"
  194. f" longer than {deprecated_max_model_length} you can either instantiate this tokenizer with"
  195. " `model_max_length` or pass `max_length` when encoding/padding.\n- To avoid this warning, please"
  196. " instantiate this tokenizer with `model_max_length` set to your preferred value.",
  197. FutureWarning,
  198. )
  199. return max_model_length
  200. @property
  201. def vocab_size(self):
  202. return self.sp_model.get_piece_size()
  203. def get_vocab(self):
  204. vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size)}
  205. vocab.update(self.added_tokens_encoder)
  206. return vocab
  207. def get_special_tokens_mask(
  208. self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
  209. ) -> List[int]:
  210. """
  211. Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
  212. special tokens using the tokenizer `prepare_for_model` method.
  213. Args:
  214. token_ids_0 (`List[int]`):
  215. List of IDs.
  216. token_ids_1 (`List[int]`, *optional*):
  217. Optional second list of IDs for sequence pairs.
  218. already_has_special_tokens (`bool`, *optional*, defaults to `False`):
  219. Whether or not the token list is already formatted with special tokens for the model.
  220. Returns:
  221. `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
  222. """
  223. if already_has_special_tokens:
  224. return super().get_special_tokens_mask(
  225. token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
  226. )
  227. # normal case: some special tokens
  228. if token_ids_1 is None:
  229. return ([0] * len(token_ids_0)) + [1]
  230. return ([0] * len(token_ids_0)) + [1] + ([0] * len(token_ids_1)) + [1]
  231. def get_sentinel_tokens(self):
  232. return list(
  233. set(filter(lambda x: bool(re.search(r"<extra_id_\d+>", x)) is not None, self.additional_special_tokens))
  234. )
  235. def get_sentinel_token_ids(self):
  236. return [self.convert_tokens_to_ids(token) for token in self.get_sentinel_tokens()]
  237. def _add_eos_if_not_present(self, token_ids: List[int]) -> List[int]:
  238. """Do not add eos again if user already added it."""
  239. if len(token_ids) > 0 and token_ids[-1] == self.eos_token_id:
  240. warnings.warn(
  241. f"This sequence already has {self.eos_token}. In future versions this behavior may lead to duplicated"
  242. " eos tokens being added."
  243. )
  244. return token_ids
  245. else:
  246. return token_ids + [self.eos_token_id]
  247. def create_token_type_ids_from_sequences(
  248. self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
  249. ) -> List[int]:
  250. """
  251. Create a mask from the two sequences passed to be used in a sequence-pair classification task. T5 does not make
  252. use of token type ids, therefore a list of zeros is returned.
  253. Args:
  254. token_ids_0 (`List[int]`):
  255. List of IDs.
  256. token_ids_1 (`List[int]`, *optional*):
  257. Optional second list of IDs for sequence pairs.
  258. Returns:
  259. `List[int]`: List of zeros.
  260. """
  261. eos = [self.eos_token_id]
  262. if token_ids_1 is None:
  263. return len(token_ids_0 + eos) * [0]
  264. return len(token_ids_0 + eos + token_ids_1 + eos) * [0]
  265. def build_inputs_with_special_tokens(
  266. self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
  267. ) -> List[int]:
  268. """
  269. Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
  270. adding special tokens. A sequence has the following format:
  271. - single sequence: `X </s>`
  272. - pair of sequences: `A </s> B </s>`
  273. Args:
  274. token_ids_0 (`List[int]`):
  275. List of IDs to which the special tokens will be added.
  276. token_ids_1 (`List[int]`, *optional*):
  277. Optional second list of IDs for sequence pairs.
  278. Returns:
  279. `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
  280. """
  281. token_ids_0 = self._add_eos_if_not_present(token_ids_0)
  282. if token_ids_1 is None:
  283. return token_ids_0
  284. else:
  285. token_ids_1 = self._add_eos_if_not_present(token_ids_1)
  286. return token_ids_0 + token_ids_1
  287. def __getstate__(self):
  288. state = self.__dict__.copy()
  289. state["sp_model"] = None
  290. return state
  291. def __setstate__(self, d):
  292. self.__dict__ = d
  293. # for backward compatibility
  294. if not hasattr(self, "sp_model_kwargs"):
  295. self.sp_model_kwargs = {}
  296. self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
  297. self.sp_model.Load(self.vocab_file)
  298. def tokenize(self, text: "TextInput", **kwargs) -> List[str]:
  299. """
  300. Converts a string to a list of tokens. If `self.legacy` is set to `False`, a prefix token is added unless the
  301. first token is special.
  302. """
  303. if self.legacy or len(text) == 0:
  304. return super().tokenize(text, **kwargs)
  305. text = text.replace(SPIECE_UNDERLINE, " ")
  306. if self.add_prefix_space:
  307. text = SPIECE_UNDERLINE + text
  308. tokens = super().tokenize(text, **kwargs)
  309. if len(tokens) > 1 and tokens[0] == SPIECE_UNDERLINE and tokens[1] in self.all_special_tokens:
  310. tokens = tokens[1:]
  311. return tokens
  312. @property
  313. def unk_token_length(self):
  314. return len(self.sp_model.encode(str(self.unk_token)))
  315. def _tokenize(self, text, **kwargs):
  316. """
  317. Returns a tokenized string.
  318. We de-activated the `add_dummy_prefix` option, thus the sentencepiece internals will always strip any
  319. SPIECE_UNDERLINE. For example: `self.sp_model.encode(f"{SPIECE_UNDERLINE}Hey", out_type = str)` will give
  320. `['H', 'e', 'y']` instead of `['▁He', 'y']`. Thus we always encode `f"{unk_token}text"` and strip the
  321. `unk_token`. Here is an example with `unk_token = "<unk>"` and `unk_token_length = 4`.
  322. `self.tokenizer.sp_model.encode("<unk> Hey", out_type = str)[4:]`.
  323. """
  324. if self.legacy or not text.startswith((SPIECE_UNDERLINE, " ")):
  325. return self.sp_model.encode(text, out_type=str)
  326. # 1. Encode string + prefix ex: "<unk> Hey"
  327. tokens = self.sp_model.encode(self.unk_token + text, out_type=str)
  328. # 2. Remove self.unk_token from ['<','unk','>', '▁Hey']
  329. return tokens[self.unk_token_length :] if len(tokens) >= self.unk_token_length else tokens
  330. def _convert_token_to_id(self, token):
  331. """Converts a token (str) in an id using the vocab."""
  332. return self.sp_model.piece_to_id(token)
  333. def _convert_id_to_token(self, index):
  334. """Converts an index (integer) in a token (str) using the vocab."""
  335. token = self.sp_model.IdToPiece(index)
  336. return token
  337. def convert_tokens_to_string(self, tokens):
  338. """Converts a sequence of tokens (string) in a single string."""
  339. # since we manually add the prefix space, we have to remove it when decoding
  340. if tokens[0].startswith(SPIECE_UNDERLINE) and self.add_prefix_space:
  341. tokens[0] = tokens[0][1:]
  342. current_sub_tokens = []
  343. out_string = ""
  344. prev_is_special = False
  345. for token in tokens:
  346. # make sure that special tokens are not decoded using sentencepiece model
  347. if token in self.all_special_tokens:
  348. if not prev_is_special:
  349. out_string += " "
  350. out_string += self.sp_model.decode(current_sub_tokens) + token
  351. prev_is_special = True
  352. current_sub_tokens = []
  353. else:
  354. current_sub_tokens.append(token)
  355. prev_is_special = False
  356. out_string += self.sp_model.decode(current_sub_tokens)
  357. return out_string.strip()
  358. def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
  359. if not os.path.isdir(save_directory):
  360. logger.error(f"Vocabulary path ({save_directory}) should be a directory")
  361. return
  362. out_vocab_file = os.path.join(
  363. save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
  364. )
  365. if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file) and os.path.isfile(self.vocab_file):
  366. copyfile(self.vocab_file, out_vocab_file)
  367. elif not os.path.isfile(self.vocab_file):
  368. with open(out_vocab_file, "wb") as fi:
  369. content_spiece_model = self.sp_model.serialized_model_proto()
  370. fi.write(content_spiece_model)
  371. return (out_vocab_file,)