tokenization_t5.py 19 KB

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