tokenization_utils_fast.py 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922
  1. # Copyright 2020 The HuggingFace Inc. team.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. """
  15. Tokenization classes for fast tokenizers (provided by HuggingFace's tokenizers library). For slow (python) tokenizers
  16. see tokenization_utils.py
  17. """
  18. import copy
  19. import json
  20. import os
  21. from collections import defaultdict
  22. from collections.abc import Iterable
  23. from typing import Any, Optional, Union
  24. import tokenizers.pre_tokenizers as pre_tokenizers_fast
  25. from tokenizers import Encoding as EncodingFast
  26. from tokenizers import Tokenizer as TokenizerFast
  27. from tokenizers.decoders import Decoder as DecoderFast
  28. from tokenizers.trainers import BpeTrainer, UnigramTrainer, WordLevelTrainer, WordPieceTrainer
  29. from .convert_slow_tokenizer import convert_slow_tokenizer
  30. from .integrations.ggml import convert_gguf_tokenizer
  31. from .modeling_gguf_pytorch_utils import load_gguf_checkpoint
  32. from .tokenization_utils import PreTrainedTokenizer
  33. from .tokenization_utils_base import (
  34. INIT_TOKENIZER_DOCSTRING,
  35. AddedToken,
  36. BatchEncoding,
  37. PreTokenizedInput,
  38. PreTokenizedInputPair,
  39. PreTrainedTokenizerBase,
  40. SpecialTokensMixin,
  41. TextInput,
  42. TextInputPair,
  43. TruncationStrategy,
  44. )
  45. from .utils import PaddingStrategy, add_end_docstrings, logging
  46. logger = logging.get_logger(__name__)
  47. # Fast tokenizers (provided by HuggingFace tokenizer's library) can be saved in a single file
  48. TOKENIZER_FILE = "tokenizer.json"
  49. SPECIAL_TOKENS_MAP_FILE = "special_tokens_map.json"
  50. TOKENIZER_CONFIG_FILE = "tokenizer_config.json"
  51. TIKTOKEN_VOCAB_FILE = "tokenizer.model"
  52. # Slow tokenizers have an additional added tokens files
  53. ADDED_TOKENS_FILE = "added_tokens.json"
  54. INIT_TOKENIZER_DOCSTRING += """
  55. tokenizer_object ([`tokenizers.Tokenizer`]):
  56. A [`tokenizers.Tokenizer`] object from 🤗 tokenizers to instantiate from. See [Using tokenizers from 🤗
  57. tokenizers](../fast_tokenizers) for more information.
  58. tokenizer_file ([`str`]):
  59. A path to a local JSON file representing a previously serialized [`tokenizers.Tokenizer`] object from 🤗
  60. tokenizers.
  61. """
  62. MODEL_TO_TRAINER_MAPPING = {
  63. "BPE": BpeTrainer,
  64. "Unigram": UnigramTrainer,
  65. "WordLevel": WordLevelTrainer,
  66. "WordPiece": WordPieceTrainer,
  67. }
  68. VOCAB_FILES_NAMES = {"tokenizer_file": TOKENIZER_FILE, "vocab_file": TIKTOKEN_VOCAB_FILE}
  69. @add_end_docstrings(INIT_TOKENIZER_DOCSTRING)
  70. class PreTrainedTokenizerFast(PreTrainedTokenizerBase):
  71. """
  72. Base class for all fast tokenizers (wrapping HuggingFace tokenizers library).
  73. Inherits from [`~tokenization_utils_base.PreTrainedTokenizerBase`].
  74. Handles all the shared methods for tokenization and special tokens, as well as methods for
  75. downloading/caching/loading pretrained tokenizers, as well as adding tokens to the vocabulary.
  76. This class also contains the added tokens in a unified way on top of all tokenizers so we don't have to handle the
  77. specific vocabulary augmentation methods of the various underlying dictionary structures (BPE, sentencepiece...).
  78. """
  79. vocab_files_names = VOCAB_FILES_NAMES
  80. slow_tokenizer_class: Optional[type[PreTrainedTokenizer]] = None
  81. def __init__(self, *args, **kwargs):
  82. tokenizer_object = kwargs.pop("tokenizer_object", None)
  83. slow_tokenizer = kwargs.pop("__slow_tokenizer", None)
  84. gguf_file = kwargs.pop("gguf_file", None)
  85. fast_tokenizer_file = kwargs.pop("tokenizer_file", None)
  86. from_slow = kwargs.pop("from_slow", False)
  87. added_tokens_decoder = kwargs.pop("added_tokens_decoder", {})
  88. self.add_prefix_space = kwargs.get("add_prefix_space", False)
  89. if from_slow and slow_tokenizer is None and self.slow_tokenizer_class is None:
  90. raise ValueError(
  91. "Cannot instantiate this tokenizer from a slow version. If it's based on sentencepiece, make sure you "
  92. "have sentencepiece installed."
  93. )
  94. if tokenizer_object is not None:
  95. fast_tokenizer = copy.deepcopy(tokenizer_object)
  96. elif fast_tokenizer_file is not None and not from_slow:
  97. # We have a serialization from tokenizers which let us directly build the backend
  98. fast_tokenizer = TokenizerFast.from_file(fast_tokenizer_file)
  99. elif slow_tokenizer:
  100. # We need to convert a slow tokenizer to build the backend
  101. fast_tokenizer = convert_slow_tokenizer(slow_tokenizer)
  102. elif gguf_file is not None:
  103. # We need to convert a slow tokenizer to build the backend
  104. gguf_param = load_gguf_checkpoint(kwargs.get("vocab_file"))
  105. architecture = gguf_param["config"]["model_type"]
  106. tokenizer_dict = gguf_param["tokenizer"]
  107. tokenizer_config = gguf_param["tokenizer_config"]
  108. fast_tokenizer, additional_kwargs = convert_gguf_tokenizer(architecture, tokenizer_dict)
  109. kwargs.update(tokenizer_config)
  110. if len(additional_kwargs) > 0:
  111. kwargs.update(additional_kwargs)
  112. elif self.slow_tokenizer_class is not None and slow_tokenizer is not False:
  113. # We need to create and convert a slow tokenizer to build the backend
  114. slow_tokenizer = self.slow_tokenizer_class(*args, **kwargs)
  115. fast_tokenizer = convert_slow_tokenizer(slow_tokenizer)
  116. elif not slow_tokenizer:
  117. # We tried loading a slow_tokenizer with spm and failed, try to load with tiktoken
  118. self.vocab_file = kwargs.get("vocab_file")
  119. self.additional_special_tokens = kwargs.get("additional_special_tokens", [])
  120. fast_tokenizer = convert_slow_tokenizer(self, from_tiktoken=True)
  121. slow_tokenizer = None
  122. else:
  123. raise ValueError(
  124. "Couldn't instantiate the backend tokenizer from one of: \n"
  125. "(1) a `tokenizers` library serialization file, \n"
  126. "(2) a slow tokenizer instance to convert or \n"
  127. "(3) an equivalent slow tokenizer class to instantiate and convert. \n"
  128. "You need to have sentencepiece or tiktoken installed to convert a slow tokenizer to a fast one."
  129. )
  130. self._tokenizer = fast_tokenizer
  131. if slow_tokenizer is not None:
  132. kwargs.update(slow_tokenizer.init_kwargs)
  133. self._decode_use_source_tokenizer = False
  134. _truncation = self._tokenizer.truncation
  135. if _truncation is not None:
  136. self._tokenizer.enable_truncation(**_truncation)
  137. kwargs.setdefault("max_length", _truncation["max_length"])
  138. kwargs.setdefault("truncation_side", _truncation["direction"])
  139. kwargs.setdefault("stride", _truncation["stride"])
  140. kwargs.setdefault("truncation_strategy", _truncation["strategy"])
  141. else:
  142. self._tokenizer.no_truncation()
  143. _padding = self._tokenizer.padding
  144. if _padding is not None:
  145. self._tokenizer.enable_padding(**_padding)
  146. kwargs.setdefault("pad_token", _padding["pad_token"])
  147. kwargs.setdefault("pad_token_type_id", _padding["pad_type_id"])
  148. kwargs.setdefault("padding_side", _padding["direction"])
  149. kwargs.setdefault("max_length", _padding["length"])
  150. kwargs.setdefault("pad_to_multiple_of", _padding["pad_to_multiple_of"])
  151. # We call this after having initialized the backend tokenizer because we update it.
  152. super().__init__(**kwargs)
  153. self._tokenizer.encode_special_tokens = self.split_special_tokens
  154. added_tokens_decoder_hash = {hash(repr(token)) for token in self.added_tokens_decoder}
  155. tokens_to_add = [
  156. token
  157. for index, token in sorted(added_tokens_decoder.items(), key=lambda x: x[0])
  158. if hash(repr(token)) not in added_tokens_decoder_hash
  159. ]
  160. encoder = list(self.added_tokens_encoder.keys()) + [str(token) for token in tokens_to_add]
  161. # if some of the special tokens are strings, we check if we don't already have a token
  162. tokens_to_add += [
  163. token for token in self.all_special_tokens_extended if token not in encoder and token not in tokens_to_add
  164. ]
  165. if len(tokens_to_add) > 0:
  166. tokens = []
  167. special_tokens = self.all_special_tokens
  168. for token in tokens_to_add:
  169. is_special = (
  170. (token.special or str(token) in special_tokens)
  171. if isinstance(token, AddedToken)
  172. else str(token) in special_tokens
  173. )
  174. if isinstance(token, str):
  175. token = AddedToken(token, special=is_special)
  176. else:
  177. token.special = is_special
  178. tokens.append(token)
  179. if tokens:
  180. self.add_tokens(tokens)
  181. try:
  182. pre_tok_state = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__())
  183. if pre_tok_state.get("add_prefix_space", self.add_prefix_space) != self.add_prefix_space:
  184. pre_tok_class = getattr(pre_tokenizers_fast, pre_tok_state.pop("type"))
  185. pre_tok_state["add_prefix_space"] = self.add_prefix_space
  186. self.backend_tokenizer.pre_tokenizer = pre_tok_class(**pre_tok_state)
  187. except Exception:
  188. # We'll get an error if there is no pre_tokenizer, or if it's a custom pre_tokenizer that can
  189. # not be serialized. In those cases, we just ignore the error as there's no pre_tokenizer
  190. # for which we need to update the `add_prefix_space` attribute.
  191. pass
  192. @property
  193. def is_fast(self) -> bool:
  194. return True
  195. @property
  196. def can_save_slow_tokenizer(self) -> bool:
  197. """
  198. `bool`: Whether or not the slow tokenizer can be saved. For a sentencepiece based slow tokenizer, this
  199. can only be `True` if the original `"sentencepiece.model"` was not deleted.
  200. """
  201. if "vocab_file" in self.vocab_files_names and self.vocab_files_names["vocab_file"].endswith(".model"):
  202. if hasattr(self, "vocab_file") and self.vocab_file:
  203. # If the vocab file is a sentencepiece model, we can save it
  204. return os.path.isfile(self.vocab_file)
  205. return False
  206. else:
  207. return True
  208. @property
  209. def vocab_size(self) -> int:
  210. """
  211. `int`: Size of the base vocabulary (without the added tokens).
  212. """
  213. return self._tokenizer.get_vocab_size(with_added_tokens=False)
  214. def get_vocab(self) -> dict[str, int]:
  215. return self._tokenizer.get_vocab(with_added_tokens=True)
  216. @property
  217. def vocab(self) -> dict[str, int]:
  218. return self.get_vocab()
  219. @property
  220. def added_tokens_encoder(self) -> dict[str, int]:
  221. """
  222. Returns the sorted mapping from string to index. The added tokens encoder is cached for performance
  223. optimisation in `self._added_tokens_encoder` for the slow tokenizers.
  224. """
  225. return {k.content: v for v, k in sorted(self.added_tokens_decoder.items(), key=lambda item: item[0])}
  226. @property
  227. def added_tokens_decoder(self) -> dict[int, AddedToken]:
  228. """
  229. Returns the added tokens in the vocabulary as a dictionary of index to AddedToken.
  230. Returns:
  231. `dict[str, int]`: The added tokens.
  232. """
  233. return self._tokenizer.get_added_tokens_decoder()
  234. def get_added_vocab(self) -> dict[str, int]:
  235. """
  236. Returns the added tokens in the vocabulary as a dictionary of token to index.
  237. Returns:
  238. `dict[str, int]`: The added tokens.
  239. """
  240. return {k.content: v for v, k in sorted(self.added_tokens_decoder.items(), key=lambda item: item[0])}
  241. def __bool__(self) -> bool:
  242. """
  243. Returns True, to avoid expensive `assert tokenizer` gotchas.
  244. """
  245. return True
  246. def __len__(self) -> int:
  247. """
  248. Size of the full vocabulary with the added tokens.
  249. """
  250. return self._tokenizer.get_vocab_size(with_added_tokens=True)
  251. @property
  252. def backend_tokenizer(self) -> TokenizerFast:
  253. """
  254. `tokenizers.implementations.BaseTokenizer`: The Rust tokenizer used as a backend.
  255. """
  256. return self._tokenizer
  257. @property
  258. def decoder(self) -> DecoderFast:
  259. """
  260. `tokenizers.decoders.Decoder`: The Rust decoder for this tokenizer.
  261. """
  262. return self._tokenizer.decoder
  263. def _convert_encoding(
  264. self,
  265. encoding: EncodingFast,
  266. return_token_type_ids: Optional[bool] = None,
  267. return_attention_mask: Optional[bool] = None,
  268. return_overflowing_tokens: bool = False,
  269. return_special_tokens_mask: bool = False,
  270. return_offsets_mapping: bool = False,
  271. return_length: bool = False,
  272. verbose: bool = True,
  273. ) -> tuple[dict[str, Any], list[EncodingFast]]:
  274. """
  275. Convert the encoding representation (from low-level HuggingFace tokenizer output) to a python Dict and a list
  276. of encodings, take care of building a batch from overflowing tokens.
  277. Overflowing tokens are converted to additional examples (like batches) so the output values of the dict are
  278. lists (overflows) of lists (tokens).
  279. Output shape: (overflows, sequence length)
  280. """
  281. if return_token_type_ids is None:
  282. return_token_type_ids = "token_type_ids" in self.model_input_names
  283. if return_attention_mask is None:
  284. return_attention_mask = "attention_mask" in self.model_input_names
  285. if return_overflowing_tokens and encoding.overflowing is not None:
  286. encodings = [encoding] + encoding.overflowing
  287. else:
  288. encodings = [encoding]
  289. encoding_dict = defaultdict(list)
  290. for e in encodings:
  291. encoding_dict["input_ids"].append(e.ids)
  292. if return_token_type_ids:
  293. encoding_dict["token_type_ids"].append(e.type_ids)
  294. if return_attention_mask:
  295. encoding_dict["attention_mask"].append(e.attention_mask)
  296. if return_special_tokens_mask:
  297. encoding_dict["special_tokens_mask"].append(e.special_tokens_mask)
  298. if return_offsets_mapping:
  299. encoding_dict["offset_mapping"].append(e.offsets)
  300. if return_length:
  301. encoding_dict["length"].append(len(e.ids))
  302. return encoding_dict, encodings
  303. def convert_tokens_to_ids(self, tokens: Union[str, Iterable[str]]) -> Union[int, list[int]]:
  304. """
  305. Converts a token string (or a sequence of tokens) in a single integer id (or a Iterable of ids), using the
  306. vocabulary.
  307. Args:
  308. tokens (`str` or `Iterable[str]`): One or several token(s) to convert to token id(s).
  309. Returns:
  310. `int` or `list[int]`: The token id or list of token ids.
  311. """
  312. if isinstance(tokens, str):
  313. return self._convert_token_to_id_with_added_voc(tokens)
  314. return [self._convert_token_to_id_with_added_voc(token) for token in tokens]
  315. def _convert_token_to_id_with_added_voc(self, token: str) -> int:
  316. index = self._tokenizer.token_to_id(token)
  317. if index is None:
  318. return self.unk_token_id
  319. return index
  320. def _convert_id_to_token(self, index: int) -> Optional[str]:
  321. return self._tokenizer.id_to_token(int(index))
  322. def _add_tokens(self, new_tokens: list[Union[str, AddedToken]], special_tokens=False) -> int:
  323. if special_tokens:
  324. return self._tokenizer.add_special_tokens(new_tokens)
  325. return self._tokenizer.add_tokens(new_tokens)
  326. def num_special_tokens_to_add(self, pair: bool = False) -> int:
  327. """
  328. Returns the number of added tokens when encoding a sequence with special tokens.
  329. <Tip>
  330. This encodes a dummy input and checks the number of added tokens, and is therefore not efficient. Do not put
  331. this inside your training loop.
  332. </Tip>
  333. Args:
  334. pair (`bool`, *optional*, defaults to `False`):
  335. Whether the number of added tokens should be computed in the case of a sequence pair or a single
  336. sequence.
  337. Returns:
  338. `int`: Number of special tokens added to sequences.
  339. """
  340. return self._tokenizer.num_special_tokens_to_add(pair)
  341. def convert_ids_to_tokens(
  342. self, ids: Union[int, list[int]], skip_special_tokens: bool = False
  343. ) -> Union[str, list[str]]:
  344. """
  345. Converts a single index or a sequence of indices in a token or a sequence of tokens, using the vocabulary and
  346. added tokens.
  347. Args:
  348. ids (`int` or `list[int]`):
  349. The token id (or token ids) to convert to tokens.
  350. skip_special_tokens (`bool`, *optional*, defaults to `False`):
  351. Whether or not to remove special tokens in the decoding.
  352. Returns:
  353. `str` or `list[str]`: The decoded token(s).
  354. """
  355. if isinstance(ids, int):
  356. return self._tokenizer.id_to_token(ids)
  357. tokens = []
  358. # self.all_special_ids is an @property which may be slow, so only compute it once before the loop
  359. ids_to_skip = set(self.all_special_ids) if skip_special_tokens else set()
  360. for index in ids:
  361. index = int(index)
  362. if index in ids_to_skip:
  363. continue
  364. tokens.append(self._tokenizer.id_to_token(index))
  365. return tokens
  366. def tokenize(self, text: str, pair: Optional[str] = None, add_special_tokens: bool = False, **kwargs) -> list[str]:
  367. return self.encode_plus(text=text, text_pair=pair, add_special_tokens=add_special_tokens, **kwargs).tokens()
  368. def set_truncation_and_padding(
  369. self,
  370. padding_strategy: PaddingStrategy,
  371. truncation_strategy: TruncationStrategy,
  372. max_length: int,
  373. stride: int,
  374. pad_to_multiple_of: Optional[int],
  375. padding_side: Optional[str],
  376. ):
  377. """
  378. Define the truncation and the padding strategies for fast tokenizers (provided by HuggingFace tokenizers
  379. library) and restore the tokenizer settings afterwards.
  380. The provided tokenizer has no padding / truncation strategy before the managed section. If your tokenizer set a
  381. padding / truncation strategy before, then it will be reset to no padding / truncation when exiting the managed
  382. section.
  383. Args:
  384. padding_strategy ([`~utils.PaddingStrategy`]):
  385. The kind of padding that will be applied to the input
  386. truncation_strategy ([`~tokenization_utils_base.TruncationStrategy`]):
  387. The kind of truncation that will be applied to the input
  388. max_length (`int`):
  389. The maximum size of a sequence.
  390. stride (`int`):
  391. The stride to use when handling overflow.
  392. pad_to_multiple_of (`int`, *optional*):
  393. If set will pad the sequence to a multiple of the provided value. This is especially useful to enable
  394. the use of Tensor Cores on NVIDIA hardware with compute capability `>= 7.5` (Volta).
  395. padding_side (`str`, *optional*):
  396. The side on which the model should have padding applied. Should be selected between ['right', 'left'].
  397. Default value is picked from the class attribute of the same name.
  398. """
  399. _truncation = self._tokenizer.truncation
  400. _padding = self._tokenizer.padding
  401. # Set truncation and padding on the backend tokenizer
  402. if truncation_strategy == TruncationStrategy.DO_NOT_TRUNCATE:
  403. if _truncation is not None:
  404. self._tokenizer.no_truncation()
  405. else:
  406. target = {
  407. "max_length": max_length,
  408. "stride": stride,
  409. "strategy": truncation_strategy.value,
  410. "direction": self.truncation_side,
  411. }
  412. # _truncation might contain more keys that the target `transformers`
  413. # supports. Use only the target keys to trigger `enable_truncation`.
  414. # This should enable this code to works on various `tokenizers`
  415. # targets.
  416. if _truncation is None:
  417. current = None
  418. else:
  419. current = {k: _truncation.get(k, None) for k in target}
  420. if current != target:
  421. self._tokenizer.enable_truncation(**target)
  422. if padding_strategy == PaddingStrategy.DO_NOT_PAD:
  423. if _padding is not None:
  424. self._tokenizer.no_padding()
  425. else:
  426. length = max_length if padding_strategy == PaddingStrategy.MAX_LENGTH else None
  427. target = {
  428. "length": length,
  429. "direction": padding_side if padding_side is not None else self.padding_side,
  430. "pad_id": self.pad_token_id,
  431. "pad_token": self.pad_token,
  432. "pad_type_id": self.pad_token_type_id,
  433. "pad_to_multiple_of": pad_to_multiple_of,
  434. }
  435. if _padding != target:
  436. self._tokenizer.enable_padding(**target)
  437. def _batch_encode_plus(
  438. self,
  439. batch_text_or_text_pairs: Union[
  440. list[TextInput], list[TextInputPair], list[PreTokenizedInput], list[PreTokenizedInputPair]
  441. ],
  442. add_special_tokens: bool = True,
  443. padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
  444. truncation_strategy: TruncationStrategy = TruncationStrategy.DO_NOT_TRUNCATE,
  445. max_length: Optional[int] = None,
  446. stride: int = 0,
  447. is_split_into_words: bool = False,
  448. pad_to_multiple_of: Optional[int] = None,
  449. padding_side: Optional[str] = None,
  450. return_tensors: Optional[str] = None,
  451. return_token_type_ids: Optional[bool] = None,
  452. return_attention_mask: Optional[bool] = None,
  453. return_overflowing_tokens: bool = False,
  454. return_special_tokens_mask: bool = False,
  455. return_offsets_mapping: bool = False,
  456. return_length: bool = False,
  457. verbose: bool = True,
  458. split_special_tokens: bool = False,
  459. ) -> BatchEncoding:
  460. if not isinstance(batch_text_or_text_pairs, (tuple, list)):
  461. raise TypeError(
  462. f"batch_text_or_text_pairs has to be a list or a tuple (got {type(batch_text_or_text_pairs)})"
  463. )
  464. # Set the truncation and padding strategy and restore the initial configuration
  465. self.set_truncation_and_padding(
  466. padding_strategy=padding_strategy,
  467. truncation_strategy=truncation_strategy,
  468. max_length=max_length,
  469. stride=stride,
  470. pad_to_multiple_of=pad_to_multiple_of,
  471. padding_side=padding_side,
  472. )
  473. if self._tokenizer.encode_special_tokens != split_special_tokens:
  474. self._tokenizer.encode_special_tokens = split_special_tokens
  475. encodings = self._tokenizer.encode_batch(
  476. batch_text_or_text_pairs,
  477. add_special_tokens=add_special_tokens,
  478. is_pretokenized=is_split_into_words,
  479. )
  480. # Convert encoding to dict
  481. # `Tokens` has type: tuple[
  482. # list[dict[str, list[list[int]]]] or list[dict[str, 2D-Tensor]],
  483. # list[EncodingFast]
  484. # ]
  485. # with nested dimensions corresponding to batch, overflows, sequence length
  486. tokens_and_encodings = [
  487. self._convert_encoding(
  488. encoding=encoding,
  489. return_token_type_ids=return_token_type_ids,
  490. return_attention_mask=return_attention_mask,
  491. return_overflowing_tokens=return_overflowing_tokens,
  492. return_special_tokens_mask=return_special_tokens_mask,
  493. return_offsets_mapping=return_offsets_mapping,
  494. return_length=return_length,
  495. verbose=verbose,
  496. )
  497. for encoding in encodings
  498. ]
  499. # Convert the output to have dict[list] from list[dict] and remove the additional overflows dimension
  500. # From (variable) shape (batch, overflows, sequence length) to ~ (batch * overflows, sequence length)
  501. # (we say ~ because the number of overflow varies with the example in the batch)
  502. #
  503. # To match each overflowing sample with the original sample in the batch
  504. # we add an overflow_to_sample_mapping array (see below)
  505. sanitized_tokens = {}
  506. for key in tokens_and_encodings[0][0]:
  507. stack = [e for item, _ in tokens_and_encodings for e in item[key]]
  508. sanitized_tokens[key] = stack
  509. sanitized_encodings = [e for _, item in tokens_and_encodings for e in item]
  510. # If returning overflowing tokens, we need to return a mapping
  511. # from the batch idx to the original sample
  512. if return_overflowing_tokens:
  513. overflow_to_sample_mapping = []
  514. for i, (toks, _) in enumerate(tokens_and_encodings):
  515. overflow_to_sample_mapping += [i] * len(toks["input_ids"])
  516. sanitized_tokens["overflow_to_sample_mapping"] = overflow_to_sample_mapping
  517. for input_ids in sanitized_tokens["input_ids"]:
  518. self._eventual_warn_about_too_long_sequence(input_ids, max_length, verbose)
  519. return BatchEncoding(sanitized_tokens, sanitized_encodings, tensor_type=return_tensors)
  520. def _encode_plus(
  521. self,
  522. text: Union[TextInput, PreTokenizedInput],
  523. text_pair: Optional[Union[TextInput, PreTokenizedInput]] = None,
  524. add_special_tokens: bool = True,
  525. padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
  526. truncation_strategy: TruncationStrategy = TruncationStrategy.DO_NOT_TRUNCATE,
  527. max_length: Optional[int] = None,
  528. stride: int = 0,
  529. is_split_into_words: bool = False,
  530. pad_to_multiple_of: Optional[int] = None,
  531. padding_side: Optional[str] = None,
  532. return_tensors: Optional[bool] = None,
  533. return_token_type_ids: Optional[bool] = None,
  534. return_attention_mask: Optional[bool] = None,
  535. return_overflowing_tokens: bool = False,
  536. return_special_tokens_mask: bool = False,
  537. return_offsets_mapping: bool = False,
  538. return_length: bool = False,
  539. verbose: bool = True,
  540. split_special_tokens: bool = False,
  541. **kwargs,
  542. ) -> BatchEncoding:
  543. batched_input = [(text, text_pair)] if text_pair else [text]
  544. batched_output = self._batch_encode_plus(
  545. batched_input,
  546. is_split_into_words=is_split_into_words,
  547. add_special_tokens=add_special_tokens,
  548. padding_strategy=padding_strategy,
  549. truncation_strategy=truncation_strategy,
  550. max_length=max_length,
  551. stride=stride,
  552. pad_to_multiple_of=pad_to_multiple_of,
  553. padding_side=padding_side,
  554. return_tensors=return_tensors,
  555. return_token_type_ids=return_token_type_ids,
  556. return_attention_mask=return_attention_mask,
  557. return_overflowing_tokens=return_overflowing_tokens,
  558. return_special_tokens_mask=return_special_tokens_mask,
  559. return_offsets_mapping=return_offsets_mapping,
  560. return_length=return_length,
  561. verbose=verbose,
  562. split_special_tokens=split_special_tokens,
  563. **kwargs,
  564. )
  565. # Return tensor is None, then we can remove the leading batch axis
  566. # Overflowing tokens are returned as a batch of output so we keep them in this case
  567. if return_tensors is None and not return_overflowing_tokens:
  568. batched_output = BatchEncoding(
  569. {
  570. key: (value[0] if len(value) > 0 and isinstance(value[0], list) else value)
  571. for key, value in batched_output.items()
  572. },
  573. batched_output.encodings,
  574. )
  575. self._eventual_warn_about_too_long_sequence(batched_output["input_ids"], max_length, verbose)
  576. return batched_output
  577. def convert_tokens_to_string(self, tokens: list[str]) -> str:
  578. return (
  579. self.backend_tokenizer.decoder.decode(tokens)
  580. if self.backend_tokenizer.decoder is not None
  581. else " ".join(tokens)
  582. )
  583. def _decode(
  584. self,
  585. token_ids: Union[int, list[int]],
  586. skip_special_tokens: bool = False,
  587. clean_up_tokenization_spaces: Optional[bool] = None,
  588. **kwargs,
  589. ) -> str:
  590. self._decode_use_source_tokenizer = kwargs.pop("use_source_tokenizer", False)
  591. if isinstance(token_ids, int):
  592. token_ids = [token_ids]
  593. text = self._tokenizer.decode(token_ids, skip_special_tokens=skip_special_tokens)
  594. clean_up_tokenization_spaces = (
  595. clean_up_tokenization_spaces
  596. if clean_up_tokenization_spaces is not None
  597. else self.clean_up_tokenization_spaces
  598. )
  599. if clean_up_tokenization_spaces:
  600. clean_text = self.clean_up_tokenization(text)
  601. return clean_text
  602. else:
  603. return text
  604. def _save_pretrained(
  605. self,
  606. save_directory: Union[str, os.PathLike],
  607. file_names: tuple[str, ...],
  608. legacy_format: Optional[bool] = None,
  609. filename_prefix: Optional[str] = None,
  610. ) -> tuple[str, ...]:
  611. """
  612. Save a tokenizer using the slow-tokenizer/legacy format: vocabulary + added tokens as well as in a unique JSON
  613. file containing {config + vocab + added-tokens}.
  614. """
  615. save_directory = str(save_directory)
  616. if self.slow_tokenizer_class is None and legacy_format is True:
  617. raise ValueError(
  618. "Your tokenizer does not have a legacy version defined and therefore cannot register this version. You"
  619. " might consider leaving the legacy_format at `None` or setting it to `False`."
  620. )
  621. save_slow = (
  622. (legacy_format is None or legacy_format is True)
  623. and self.slow_tokenizer_class is not None
  624. and self.can_save_slow_tokenizer
  625. )
  626. save_fast = legacy_format is None or legacy_format is False
  627. if save_slow:
  628. added_tokens_file = os.path.join(
  629. save_directory, (filename_prefix + "-" if filename_prefix else "") + ADDED_TOKENS_FILE
  630. )
  631. # make sure to be forward compatible
  632. added_vocab = {tok: index for tok, index in self.added_tokens_encoder.items() if index >= self.vocab_size}
  633. if added_vocab:
  634. with open(added_tokens_file, "w", encoding="utf-8") as f:
  635. out_str = json.dumps(added_vocab, indent=2, sort_keys=True, ensure_ascii=False) + "\n"
  636. f.write(out_str)
  637. vocab_files = self.save_vocabulary(save_directory, filename_prefix=filename_prefix)
  638. file_names = file_names + vocab_files + (added_tokens_file,)
  639. if save_fast:
  640. tokenizer_file = os.path.join(
  641. save_directory, (filename_prefix + "-" if filename_prefix else "") + TOKENIZER_FILE
  642. )
  643. self.backend_tokenizer.save(tokenizer_file)
  644. file_names = file_names + (tokenizer_file,)
  645. return file_names
  646. def train_new_from_iterator(
  647. self,
  648. text_iterator,
  649. vocab_size,
  650. length=None,
  651. new_special_tokens=None,
  652. special_tokens_map=None,
  653. **kwargs,
  654. ):
  655. """
  656. Trains a tokenizer on a new corpus with the same defaults (in terms of special tokens or tokenization pipeline)
  657. as the current one.
  658. Args:
  659. text_iterator (generator of `list[str]`):
  660. The training corpus. Should be a generator of batches of texts, for instance a list of lists of texts
  661. if you have everything in memory.
  662. vocab_size (`int`):
  663. The size of the vocabulary you want for your tokenizer.
  664. length (`int`, *optional*):
  665. The total number of sequences in the iterator. This is used to provide meaningful progress tracking
  666. new_special_tokens (list of `str` or `AddedToken`, *optional*):
  667. A list of new special tokens to add to the tokenizer you are training.
  668. special_tokens_map (`dict[str, str]`, *optional*):
  669. If you want to rename some of the special tokens this tokenizer uses, pass along a mapping old special
  670. token name to new special token name in this argument.
  671. kwargs (`dict[str, Any]`, *optional*):
  672. Additional keyword arguments passed along to the trainer from the 🤗 Tokenizers library.
  673. Returns:
  674. [`PreTrainedTokenizerFast`]: A new tokenizer of the same type as the original one, trained on
  675. `text_iterator`.
  676. """
  677. tokenizer_json = json.loads(self._tokenizer.to_str())
  678. # Remove added tokens for now (uses IDs of tokens)
  679. added_tokens = tokenizer_json.pop("added_tokens")
  680. # Remove post processor for now (uses IDs of tokens)
  681. post_processor = tokenizer_json.pop("post_processor")
  682. unk_token = None
  683. # Remove vocab
  684. if tokenizer_json["model"]["type"] == "BPE":
  685. tokenizer_json["model"]["vocab"] = {}
  686. tokenizer_json["model"]["merges"] = []
  687. elif tokenizer_json["model"]["type"] == "Unigram":
  688. if tokenizer_json["model"]["unk_id"] is not None:
  689. unk_id = tokenizer_json["model"]["unk_id"]
  690. unk_token = tokenizer_json["model"]["vocab"][unk_id][0]
  691. if special_tokens_map is not None and unk_token in special_tokens_map:
  692. unk_token = special_tokens_map[unk_token]
  693. tokenizer_json["model"]["unk_id"] = 0
  694. tokenizer_json["model"]["vocab"] = [[unk_token, 0.0]]
  695. elif tokenizer_json["model"]["type"] in ["WordLevel", "WordPiece"]:
  696. tokenizer_json["model"]["vocab"] = {}
  697. else:
  698. raise ValueError(
  699. f"This method does not support this type of tokenizer (found {tokenizer_json['model']['type']}) "
  700. "only BPE, Unigram, WordLevel and WordPiece."
  701. )
  702. if (
  703. special_tokens_map is not None
  704. and "unk_token" in tokenizer_json["model"]
  705. and tokenizer_json["model"]["unk_token"] in special_tokens_map
  706. ):
  707. tokenizer_json["model"]["unk_token"] = special_tokens_map[tokenizer_json["model"]["unk_token"]]
  708. tokenizer = TokenizerFast.from_str(json.dumps(tokenizer_json))
  709. # Get the special tokens from the current tokenizer if none are specified.
  710. special_tokens = []
  711. for added_token in added_tokens:
  712. special = added_token.pop("special", None)
  713. _ = added_token.pop("id", None)
  714. if tokenizer_json["model"]["type"] != "Unigram" and not special:
  715. continue
  716. if special_tokens_map is not None and added_token["content"] in special_tokens_map:
  717. added_token["content"] = special_tokens_map[added_token["content"]]
  718. special_tokens.append(AddedToken(**added_token))
  719. if new_special_tokens is not None:
  720. special_tokens.extend(new_special_tokens)
  721. # Trainer needs to know the end of word / continuing subword thingies in BPE
  722. if (
  723. tokenizer_json["model"]["type"] == "BPE"
  724. and "continuing_subword_prefix" not in kwargs
  725. and tokenizer_json["model"]["continuing_subword_prefix"] is not None
  726. ):
  727. kwargs["continuing_subword_prefix"] = tokenizer_json["model"]["continuing_subword_prefix"]
  728. if (
  729. tokenizer_json["model"]["type"] == "BPE"
  730. and "end_of_word_suffix" not in kwargs
  731. and tokenizer_json["model"]["end_of_word_suffix"] is not None
  732. ):
  733. kwargs["end_of_word_suffix"] = tokenizer_json["model"]["end_of_word_suffix"]
  734. if tokenizer_json["model"]["type"] == "Unigram" and unk_token is not None:
  735. kwargs["unk_token"] = unk_token
  736. if tokenizer_json["pre_tokenizer"] is not None:
  737. if (
  738. tokenizer_json["pre_tokenizer"]["type"] == "ByteLevel"
  739. or tokenizer_json["pre_tokenizer"]["type"] == "Sequence"
  740. and "pretokenizers" in tokenizer_json["pre_tokenizer"]
  741. and any(
  742. pretokenizer["type"] == "ByteLevel"
  743. for pretokenizer in tokenizer_json["pre_tokenizer"]["pretokenizers"]
  744. )
  745. ):
  746. kwargs["initial_alphabet"] = pre_tokenizers_fast.ByteLevel.alphabet()
  747. trainer_class = MODEL_TO_TRAINER_MAPPING[tokenizer_json["model"]["type"]]
  748. trainer = trainer_class(vocab_size=vocab_size, special_tokens=special_tokens, **kwargs)
  749. tokenizer.train_from_iterator(text_iterator, length=length, trainer=trainer)
  750. if post_processor is not None:
  751. trained_tokenizer_json = json.loads(tokenizer.to_str())
  752. # Almost done, we just have to adjust the token IDs in the post processor
  753. if "special_tokens" in post_processor:
  754. for key in post_processor["special_tokens"]:
  755. tokens = post_processor["special_tokens"][key]["tokens"]
  756. if special_tokens_map is not None:
  757. tokens = [special_tokens_map.get(token, token) for token in tokens]
  758. post_processor["special_tokens"][key]["tokens"] = tokens
  759. for token in tokens:
  760. token_id = tokenizer.token_to_id(token)
  761. if token_id is None:
  762. raise ValueError(
  763. "Attempted to set a token in the post processor that does not exist in the mapping"
  764. )
  765. post_processor["special_tokens"][key]["ids"] = [tokenizer.token_to_id(token) for token in tokens]
  766. for special_token in ["cls", "sep"]:
  767. if special_token in post_processor:
  768. token, _ = post_processor[special_token]
  769. if special_tokens_map is not None and token in special_tokens_map:
  770. token = special_tokens_map[token]
  771. token_id = tokenizer.token_to_id(token)
  772. if token_id is None:
  773. raise ValueError(
  774. "Attempted to set a token in the post processor that does not exist in the mapping"
  775. )
  776. post_processor[special_token] = [token, token_id]
  777. trained_tokenizer_json["post_processor"] = post_processor
  778. tokenizer = TokenizerFast.from_str(json.dumps(trained_tokenizer_json))
  779. kwargs = self.init_kwargs.copy()
  780. # Map pad/cls/mask token at the Transformers level
  781. special_tokens_list = SpecialTokensMixin.SPECIAL_TOKENS_ATTRIBUTES.copy()
  782. special_tokens_list.remove("additional_special_tokens")
  783. for token in special_tokens_list:
  784. if getattr(self, token) is not None:
  785. special_token = getattr(self, token)
  786. if special_tokens_map is not None and special_token in special_tokens_map:
  787. special_token = special_tokens_map[special_token]
  788. special_token_full = self._special_tokens_map.get(token, None)
  789. if isinstance(special_token_full, AddedToken):
  790. # Create an added token with the same parameters except the content
  791. kwargs[token] = AddedToken(
  792. special_token,
  793. single_word=special_token_full.single_word,
  794. lstrip=special_token_full.lstrip,
  795. rstrip=special_token_full.rstrip,
  796. normalized=special_token_full.normalized,
  797. special=True,
  798. )
  799. else:
  800. kwargs[token] = special_token
  801. additional_special_tokens = self.additional_special_tokens
  802. if new_special_tokens is not None:
  803. additional_special_tokens.extend(new_special_tokens)
  804. if len(additional_special_tokens) > 0:
  805. kwargs["additional_special_tokens"] = additional_special_tokens
  806. return self.__class__(tokenizer_object=tokenizer, **kwargs)