tokenization_utils.py 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135
  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 python tokenizers. For fast tokenizers (provided by HuggingFace's tokenizers library) see
  16. tokenization_utils_fast.py
  17. """
  18. import bisect
  19. import itertools
  20. import re
  21. import unicodedata
  22. from collections import OrderedDict
  23. from typing import Any, Optional, Union, overload
  24. from .tokenization_utils_base import (
  25. ENCODE_KWARGS_DOCSTRING,
  26. ENCODE_PLUS_ADDITIONAL_KWARGS_DOCSTRING,
  27. INIT_TOKENIZER_DOCSTRING,
  28. AddedToken,
  29. BatchEncoding,
  30. EncodedInput,
  31. EncodedInputPair,
  32. PreTokenizedInput,
  33. PreTokenizedInputPair,
  34. PreTrainedTokenizerBase,
  35. TextInput,
  36. TextInputPair,
  37. TruncationStrategy,
  38. )
  39. from .utils import PaddingStrategy, TensorType, add_end_docstrings, logging
  40. logger = logging.get_logger(__name__)
  41. # Slow tokenizers are saved in a vocabulary plus three separated files
  42. SPECIAL_TOKENS_MAP_FILE = "special_tokens_map.json"
  43. ADDED_TOKENS_FILE = "added_tokens.json"
  44. TOKENIZER_CONFIG_FILE = "tokenizer_config.json"
  45. class Trie:
  46. """
  47. Trie in Python. Creates a Trie out of a list of words. The trie is used to split on `added_tokens` in one pass
  48. Loose reference https://en.wikipedia.org/wiki/Trie
  49. """
  50. def __init__(self, *args):
  51. self.data = {}
  52. self._tokens = set()
  53. self._termination_char = ""
  54. self.update(*args)
  55. def update(self, *args):
  56. """
  57. Updates the Trie with new tokens provided as arguments.
  58. Args:
  59. *args: Variable number of words to be added to the Trie.
  60. """
  61. for token in tuple(*args):
  62. self.add(token)
  63. def add(self, word: str):
  64. """
  65. Passes over every char (utf-8 char) on word and recursively adds it to the internal `data` trie representation.
  66. The special key `""` in `self._termination_char` is used to represent termination.
  67. This function is idempotent, adding twice the same word will leave the trie unchanged
  68. Example:
  69. ```python
  70. >>> trie = Trie()
  71. >>> trie.add("Hello 友達")
  72. >>> trie.data
  73. {"H": {"e": {"l": {"l": {"o": {" ": {"友": {"達": {"": 1}}}}}}}}}
  74. >>> trie.add("Hello")
  75. >>> trie.data
  76. {"H": {"e": {"l": {"l": {"o": {"": 1, " ": {"友": {"達": {"": 1}}}}}}}}}
  77. ```
  78. """
  79. if not word:
  80. # Prevent empty string
  81. return
  82. self._tokens.add(word)
  83. ref = self.data
  84. for char in word:
  85. ref[char] = ref.setdefault(char, {})
  86. ref = ref[char]
  87. ref[self._termination_char] = 1
  88. def split(self, text: str) -> list[str]:
  89. """
  90. Will look for the words added to the trie within `text`. Output is the original string split along the
  91. boundaries of the words found.
  92. This trie will match the longest possible word first !
  93. Example:
  94. ```python
  95. >>> trie = Trie()
  96. >>> trie.split("[CLS] This is a extra_id_100")
  97. ["[CLS] This is a extra_id_100"]
  98. >>> trie.add("[CLS]")
  99. >>> trie.add("extra_id_1")
  100. >>> trie.add("extra_id_100")
  101. >>> trie.split("[CLS] This is a extra_id_100")
  102. ["[CLS]", " This is a ", "extra_id_100"]
  103. ```
  104. """
  105. # indexes are counted left of the chars index.
  106. # "hello", index 0, is left of h, index 1 is between h and e.
  107. # index 5 is right of the "o".
  108. # States are going to capture every possible start (indexes as above)
  109. # as keys, and have as values, a pointer to the position in the trie
  110. # where we're at. This is a partial match for now.
  111. # This enables to keep track of multiple matches while we're iterating
  112. # the string
  113. # If the trie contains, "blowing", and "lower" and we encounter the
  114. # string "blower", we need to split into ["b", "lower"].
  115. # This is where we need to keep track of multiple possible starts.
  116. states = OrderedDict()
  117. # This will contain every indices where we need
  118. # to cut.
  119. # We force to cut at offset 0 and len(text) (added later)
  120. offsets = [0]
  121. # This is used by the lookahead which needs to skip over
  122. # some text where the full match exceeded the place in the initial
  123. # for loop
  124. skip = 0
  125. # Main loop, Giving this algorithm O(n) complexity
  126. for current, current_char in enumerate(text):
  127. if skip and current < skip:
  128. # Prevents the lookahead for matching twice
  129. # like extra_id_100 and id_100
  130. continue
  131. # This will track every state
  132. # that stop matching, we need to stop tracking them.
  133. # If we look at "lowball", we're going to match "l" (add it to states), "o", "w", then
  134. # fail on "b", we need to remove 0 from the valid states.
  135. to_remove = set()
  136. # Whenever we found a match, we need to drop everything
  137. # this is a greedy algorithm, it will match on the first found token
  138. reset = False
  139. # In this case, we already have partial matches (But unfinished)
  140. for start, trie_pointer in states.items():
  141. if "" in trie_pointer:
  142. # This is a final match, we need to reset and
  143. # store the results in `offsets`.
  144. # Lookahead to match longest first
  145. # Important in case of extra_id_1 vs extra_id_100
  146. # Here we are also actively looking for other earlier partial
  147. # matches
  148. # "[CLS]", "L", we need to match CLS even if L is special
  149. for lookstart, looktrie_pointer in states.items():
  150. if lookstart > start:
  151. # This partial match is later, we can stop looking
  152. break
  153. elif lookstart < start:
  154. # This partial match is earlier, the trie pointer
  155. # was already updated, so index is + 1
  156. lookahead_index = current + 1
  157. end = current + 1
  158. else:
  159. # Here lookstart == start and
  160. # looktrie_pointer == trie_pointer
  161. # It wasn't updated yet so indices are current ones
  162. lookahead_index = current
  163. end = current
  164. next_char = text[lookahead_index] if lookahead_index < len(text) else None
  165. if "" in looktrie_pointer:
  166. start = lookstart
  167. end = lookahead_index
  168. skip = lookahead_index
  169. while next_char in looktrie_pointer:
  170. looktrie_pointer = looktrie_pointer[next_char]
  171. lookahead_index += 1
  172. if "" in looktrie_pointer:
  173. start = lookstart
  174. end = lookahead_index
  175. skip = lookahead_index
  176. if lookahead_index == len(text):
  177. # End of string
  178. break
  179. next_char = text[lookahead_index]
  180. # End lookahead
  181. # Storing and resetting
  182. offsets.append(start)
  183. offsets.append(end)
  184. reset = True
  185. break
  186. elif current_char in trie_pointer:
  187. # The current character being looked at has a match within the trie
  188. # update the pointer (it will be stored back into states later).
  189. trie_pointer = trie_pointer[current_char]
  190. # Storing back the new pointer into the states.
  191. # Partial matches got longer by one.
  192. states[start] = trie_pointer
  193. else:
  194. # The new character has not match in the trie, we need
  195. # to stop keeping track of this partial match.
  196. # We can't do it directly within the loop because of how
  197. # python iteration works
  198. to_remove.add(start)
  199. # Either clearing the full start (we found a real match)
  200. # Or clearing only the partial matches that didn't work.
  201. if reset:
  202. states = {}
  203. else:
  204. for start in to_remove:
  205. del states[start]
  206. # If this character is a starting character within the trie
  207. # start keeping track of this partial match.
  208. if current >= skip and current_char in self.data:
  209. states[current] = self.data[current_char]
  210. # We have a cut at the end with states.
  211. for start, trie_pointer in states.items():
  212. if "" in trie_pointer:
  213. # This is a final match, we need to reset and
  214. # store the results in `offsets`.
  215. end = len(text)
  216. offsets.append(start)
  217. offsets.append(end)
  218. # Longest cut is always the one with lower start so the first
  219. # item so we need to break.
  220. break
  221. return self.cut_text(text, offsets)
  222. def cut_text(self, text, offsets):
  223. # We have all the offsets now, we just need to do the actual splitting.
  224. # We need to eventually add the first part of the string and the eventual
  225. # last part.
  226. offsets.append(len(text))
  227. tokens = []
  228. start = 0
  229. for end in offsets:
  230. if start > end:
  231. logger.error(
  232. "There was a bug in Trie algorithm in tokenization. Attempting to recover. Please report it"
  233. " anyway."
  234. )
  235. continue
  236. elif start == end:
  237. # This might happen if there's a match at index 0
  238. # we're also preventing zero-width cuts in case of two
  239. # consecutive matches
  240. continue
  241. tokens.append(text[start:end])
  242. start = end
  243. return tokens
  244. class ExtensionsTrie(Trie):
  245. def __init__(self, *args):
  246. super().__init__(*args)
  247. def extensions(self, prefix: str):
  248. """
  249. Generates all extensions of a given prefix token in the Trie.
  250. Example:
  251. ```python
  252. >>> trie = Trie()
  253. >>> trie.add("apple")
  254. >>> trie.add("app")
  255. >>> trie.add("application")
  256. >>> trie.extensions("app")
  257. ['app', 'apple', 'application']
  258. ```
  259. """
  260. prefix_node = self._get_node(prefix)
  261. ret = self._collect_tokens(prefix_node)
  262. return [prefix + token for token in ret]
  263. def _get_node(self, token: str) -> dict:
  264. """
  265. Retrieves the node corresponding to the given token in the Trie.
  266. Args:
  267. token (str): The token for which the corresponding node needs to be retrieved.
  268. Returns:
  269. dict: The node in the Trie corresponding to the given token.
  270. """
  271. node = self.data
  272. for char in token:
  273. if char not in node:
  274. break
  275. node = node[char]
  276. return node
  277. def _collect_tokens(self, node: dict) -> list:
  278. """
  279. Generates all tokens in the Trie starting from a given node.
  280. Args:
  281. node (dict): The node in the Trie from which tokens need to be generated.
  282. Returns:
  283. list: List of tokens generated from the given node.
  284. """
  285. tokens = [self._termination_char] if self._termination_char in node else []
  286. for token, subtrie_head in node.items():
  287. if token != self._termination_char:
  288. subtokens = self._collect_tokens(subtrie_head)
  289. tokens.extend([token + subtoken for subtoken in subtokens])
  290. return tokens
  291. def _is_whitespace(char):
  292. """Checks whether `char` is a whitespace character."""
  293. # \t, \n, and \r are technically control characters but we treat them
  294. # as whitespace since they are generally considered as such.
  295. if char == " " or char == "\t" or char == "\n" or char == "\r":
  296. return True
  297. cat = unicodedata.category(char)
  298. if cat == "Zs":
  299. return True
  300. return False
  301. def _is_control(char):
  302. """Checks whether `char` is a control character."""
  303. # These are technically control characters but we count them as whitespace
  304. # characters.
  305. if char == "\t" or char == "\n" or char == "\r":
  306. return False
  307. cat = unicodedata.category(char)
  308. if cat.startswith("C"):
  309. return True
  310. return False
  311. def _is_punctuation(char):
  312. """Checks whether `char` is a punctuation character."""
  313. cp = ord(char)
  314. # We treat all non-letter/number ASCII as punctuation.
  315. # Characters such as "^", "$", and "`" are not in the Unicode
  316. # Punctuation class but we treat them as punctuation anyways, for
  317. # consistency.
  318. if (cp >= 33 and cp <= 47) or (cp >= 58 and cp <= 64) or (cp >= 91 and cp <= 96) or (cp >= 123 and cp <= 126):
  319. return True
  320. cat = unicodedata.category(char)
  321. if cat.startswith("P"):
  322. return True
  323. return False
  324. def _is_end_of_word(text):
  325. """Checks whether the last character in text is one of a punctuation, control or whitespace character."""
  326. last_char = text[-1]
  327. return bool(_is_control(last_char) | _is_punctuation(last_char) | _is_whitespace(last_char))
  328. def _is_start_of_word(text):
  329. """Checks whether the first character in text is one of a punctuation, control or whitespace character."""
  330. first_char = text[0]
  331. return bool(_is_control(first_char) | _is_punctuation(first_char) | _is_whitespace(first_char))
  332. def _insert_one_token_to_ordered_list(token_list: list[str], new_token: str):
  333. """
  334. Inserts one token to an ordered list if it does not already exist. Note: token_list must be sorted.
  335. """
  336. insertion_idx = bisect.bisect_left(token_list, new_token)
  337. # Checks if new_token is already in the ordered token_list
  338. if insertion_idx < len(token_list) and token_list[insertion_idx] == new_token:
  339. # new_token is in token_list, don't add
  340. return
  341. else:
  342. token_list.insert(insertion_idx, new_token)
  343. @add_end_docstrings(INIT_TOKENIZER_DOCSTRING)
  344. class PreTrainedTokenizer(PreTrainedTokenizerBase):
  345. """
  346. Base class for all slow tokenizers.
  347. Inherits from [`~tokenization_utils_base.PreTrainedTokenizerBase`].
  348. Handle all the shared methods for tokenization and special tokens as well as methods downloading/caching/loading
  349. pretrained tokenizers as well as adding tokens to the vocabulary.
  350. This class also contain the added tokens in a unified way on top of all tokenizers so we don't have to handle the
  351. specific vocabulary augmentation methods of the various underlying dictionary structures (BPE, sentencepiece...).
  352. """
  353. def __init__(self, **kwargs):
  354. # 1. Init the parent class
  355. self.tokens_trie = Trie()
  356. # 2. init `_added_tokens_decoder` if child class did not
  357. if not hasattr(self, "_added_tokens_decoder"):
  358. self._added_tokens_decoder: dict[int, AddedToken] = {}
  359. # 3. if a `added_tokens_decoder` is passed, we are loading from a saved tokenizer, we overwrite
  360. self._added_tokens_decoder.update(kwargs.pop("added_tokens_decoder", {}))
  361. self._added_tokens_encoder: dict[str, int] = {k.content: v for v, k in self._added_tokens_decoder.items()}
  362. # 4 init the parent class
  363. super().__init__(**kwargs)
  364. # 4. If some of the special tokens are not part of the vocab, we add them, at the end.
  365. # the order of addition is the same as self.SPECIAL_TOKENS_ATTRIBUTES following `tokenizers`
  366. self._add_tokens(
  367. [token for token in self.all_special_tokens_extended if token not in self._added_tokens_encoder],
  368. special_tokens=True,
  369. )
  370. self._decode_use_source_tokenizer = False
  371. @property
  372. def is_fast(self) -> bool:
  373. return False
  374. @property
  375. def vocab_size(self) -> int:
  376. """
  377. `int`: Size of the base vocabulary (without the added tokens).
  378. """
  379. raise NotImplementedError
  380. @property
  381. def added_tokens_encoder(self) -> dict[str, int]:
  382. """
  383. Returns the sorted mapping from string to index. The added tokens encoder is cached for performance
  384. optimisation in `self._added_tokens_encoder` for the slow tokenizers.
  385. """
  386. return {k.content: v for v, k in sorted(self._added_tokens_decoder.items(), key=lambda item: item[0])}
  387. @property
  388. def added_tokens_decoder(self) -> dict[int, AddedToken]:
  389. """
  390. Returns the added tokens in the vocabulary as a dictionary of index to AddedToken.
  391. Returns:
  392. `dict[str, int]`: The added tokens.
  393. """
  394. return dict(sorted(self._added_tokens_decoder.items(), key=lambda item: item[0]))
  395. @added_tokens_decoder.setter
  396. def added_tokens_decoder(self, value: dict[int, Union[AddedToken, str]]) -> dict[int, AddedToken]:
  397. # Always raise an error if string because users should define the behavior
  398. for index, token in value.items():
  399. if not isinstance(token, (str, AddedToken)) or not isinstance(index, int):
  400. raise TypeError(
  401. f"The provided `added_tokens_decoder` has an element of type {index.__class__, token.__class__}, should be a dict of {int, Union[AddedToken, str]}"
  402. )
  403. self._added_tokens_decoder[index] = AddedToken(token) if isinstance(token, str) else token
  404. self._added_tokens_encoder[str(token)] = index
  405. self._update_total_vocab_size()
  406. def get_added_vocab(self) -> dict[str, int]:
  407. """
  408. Returns the added tokens in the vocabulary as a dictionary of token to index. Results might be different from
  409. the fast call because for now we always add the tokens even if they are already in the vocabulary. This is
  410. something we should change.
  411. Returns:
  412. `dict[str, int]`: The added tokens.
  413. """
  414. return self._added_tokens_encoder
  415. def __len__(self):
  416. """
  417. Size of the full vocabulary with the added tokens.
  418. """
  419. return self.total_vocab_size
  420. def _update_total_vocab_size(self):
  421. """
  422. Update the size of the full vocabulary with the added tokens. Counts the `keys` and not the `values` because
  423. otherwise if there is a hole in the vocab, we will add tokenizers at a wrong index. This operation is slow and
  424. is only updated when adding tokens.
  425. """
  426. self.total_vocab_size = len(self.get_vocab())
  427. def _add_tokens(self, new_tokens: Union[list[str], list[AddedToken]], special_tokens: bool = False) -> int:
  428. """
  429. Add a list of new tokens to the tokenizer class. If the new tokens are not in the vocabulary, they are added to
  430. it with indices starting from length of the current vocabulary. Special tokens are sometimes already in the
  431. vocab which is why they have to be handled specifically.
  432. Args:
  433. new_tokens (`list[str]`or `list[tokenizers.AddedToken]`):
  434. Token(s) to add in vocabulary. A token is counted as added if it's not already in the vocabulary
  435. (tested by checking if the tokenizer assign the index of the `unk_token` to them). If a token is part
  436. of the vocabulary then we simply mark this token as an `AddedToken` which allows to control the
  437. stripping and normalization of this token. This is NOT possible in `tokenizers`.
  438. special_tokens (`bool`, *optional*, defaults to `False`):
  439. Whether or not the tokens should be added as special tokens.
  440. Returns:
  441. `int`: The number of tokens actually added to the vocabulary.
  442. Examples:
  443. ```python
  444. # Let's see how to increase the vocabulary of Bert model and tokenizer
  445. tokenizer = BertTokenizer.from_pretrained("google-bert/bert-base-uncased")
  446. model = BertModel.from_pretrained("google-bert/bert-base-uncased")
  447. num_added_toks = tokenizer.add_tokens(["new_tok1", "my_new-tok2"])
  448. print("We have added", num_added_toks, "tokens")
  449. # Note: resize_token_embeddings expects to receive the full size of the new vocabulary, i.e. the length of the tokenizer.
  450. model.resize_token_embeddings(len(tokenizer))
  451. ```"""
  452. added_tokens = 0
  453. if new_tokens is None:
  454. return added_tokens
  455. # TODO this is fairly slow to improve!
  456. current_vocab = self.get_vocab().copy()
  457. new_idx = len(current_vocab) # only call this once, len gives the last index + 1
  458. for token in new_tokens:
  459. if not isinstance(token, (str, AddedToken)):
  460. raise TypeError(f"Token {token} is not a string but a {type(token)}.")
  461. if str(token) == "":
  462. continue
  463. if isinstance(token, str):
  464. if token in self._added_tokens_encoder:
  465. continue
  466. else:
  467. # very important for fast and slow equivalence!
  468. is_special = token in self.all_special_tokens or special_tokens
  469. token = AddedToken(
  470. token, rstrip=False, lstrip=False, normalized=not is_special, special=is_special
  471. )
  472. elif special_tokens:
  473. # doing token.special=True changes the normalization! will fix in rust
  474. # this is important and the only reason why the AddedTokens in each class are normalized by default
  475. token.__setstate__({"special": True, "normalized": token.normalized})
  476. if token in self._added_tokens_decoder:
  477. continue
  478. if not token.special and token.normalized and getattr(self, "do_lower_case", False):
  479. # Normalize if requested
  480. token.content = token.content.lower()
  481. if token.content not in current_vocab:
  482. token_index = new_idx + added_tokens
  483. current_vocab[token.content] = token_index
  484. added_tokens += 1
  485. else:
  486. token_index = current_vocab[token.content]
  487. if token.special and str(token) not in self.all_special_tokens:
  488. self._special_tokens_map["additional_special_tokens"].append(token)
  489. # the setter automatically updates the reverse map
  490. self._added_tokens_decoder[token_index] = token
  491. self._added_tokens_encoder[token.content] = token_index
  492. if self.verbose:
  493. logger.info(f"Adding {token} to the vocabulary")
  494. self._update_trie()
  495. self._update_total_vocab_size()
  496. return added_tokens
  497. def _update_trie(self, unique_no_split_tokens: Optional[list[str]] = None):
  498. for token in self._added_tokens_decoder.values():
  499. if token.content not in self.tokens_trie._tokens:
  500. self.tokens_trie.add(token.content)
  501. for token in unique_no_split_tokens or []:
  502. if token not in self.tokens_trie._tokens:
  503. self.tokens_trie.add(token)
  504. def num_special_tokens_to_add(self, pair: bool = False) -> int:
  505. """
  506. Returns the number of added tokens when encoding a sequence with special tokens.
  507. <Tip>
  508. This encodes a dummy input and checks the number of added tokens, and is therefore not efficient. Do not put
  509. this inside your training loop.
  510. </Tip>
  511. Args:
  512. pair (`bool`, *optional*, defaults to `False`):
  513. Whether the number of added tokens should be computed in the case of a sequence pair or a single
  514. sequence.
  515. Returns:
  516. `int`: Number of special tokens added to sequences.
  517. """
  518. token_ids_0 = []
  519. token_ids_1 = []
  520. return len(self.build_inputs_with_special_tokens(token_ids_0, token_ids_1 if pair else None))
  521. def tokenize(self, text: TextInput, **kwargs) -> list[str]:
  522. """
  523. Converts a string into a sequence of tokens, using the tokenizer.
  524. Split in words for word-based vocabulary or sub-words for sub-word-based vocabularies
  525. (BPE/SentencePieces/WordPieces). Takes care of added tokens.
  526. Args:
  527. text (`str`):
  528. The sequence to be encoded.
  529. **kwargs (additional keyword arguments):
  530. Passed along to the model-specific `prepare_for_tokenization` preprocessing method.
  531. Returns:
  532. `list[str]`: The list of tokens.
  533. """
  534. split_special_tokens = kwargs.pop("split_special_tokens", self.split_special_tokens)
  535. text, kwargs = self.prepare_for_tokenization(text, **kwargs)
  536. if kwargs:
  537. logger.warning(f"Keyword arguments {kwargs} not recognized.")
  538. if hasattr(self, "do_lower_case") and self.do_lower_case:
  539. # convert non-special tokens to lowercase. Might be super slow as well?
  540. escaped_special_toks = [re.escape(s_tok) for s_tok in (self.all_special_tokens)]
  541. escaped_special_toks += [
  542. re.escape(s_tok.content)
  543. for s_tok in (self._added_tokens_decoder.values())
  544. if not s_tok.special and s_tok.normalized
  545. ]
  546. pattern = r"(" + r"|".join(escaped_special_toks) + r")|" + r"(.+?)"
  547. text = re.sub(pattern, lambda m: m.groups()[0] or m.groups()[1].lower(), text)
  548. if split_special_tokens:
  549. no_split_token = []
  550. tokens = [text]
  551. else:
  552. no_split_token = self._added_tokens_encoder.keys() # don't split on any of the added tokens
  553. # "This is something<special_token_1> else"
  554. tokens = self.tokens_trie.split(text)
  555. # ["This is something", "<special_token_1>", " else"]
  556. for i, token in enumerate(tokens):
  557. if token in no_split_token:
  558. tok_extended = self._added_tokens_decoder.get(self._added_tokens_encoder[token], None)
  559. left = tokens[i - 1] if i > 0 else None
  560. right = tokens[i + 1] if i < len(tokens) - 1 else None
  561. if isinstance(tok_extended, AddedToken):
  562. if tok_extended.rstrip and right:
  563. # A bit counter-intuitive but we strip the left of the string
  564. # since tok_extended.rstrip means the special token is eating all white spaces on its right
  565. tokens[i + 1] = right.lstrip()
  566. # Strip white spaces on the left
  567. if tok_extended.lstrip and left:
  568. tokens[i - 1] = left.rstrip() # Opposite here
  569. if tok_extended.single_word and left and left[-1] != " ":
  570. tokens[i - 1] += token
  571. tokens[i] = ""
  572. elif tok_extended.single_word and right and right[0] != " ":
  573. tokens[i + 1] = token + tokens[i + 1]
  574. tokens[i] = ""
  575. else:
  576. raise ValueError(
  577. f"{tok_extended} cannot be tokenized because it was not properly added"
  578. f" to the tokenizer. This means that it is not an `AddedToken` but a {type(tok_extended)}"
  579. )
  580. # ["This is something", "<special_token_1>", "else"]
  581. tokenized_text = []
  582. for token in tokens:
  583. # Need to skip eventual empty (fully stripped) tokens
  584. if not token:
  585. continue
  586. if token in no_split_token:
  587. tokenized_text.append(token)
  588. else:
  589. tokenized_text.extend(self._tokenize(token))
  590. # ["This", " is", " something", "<special_token_1>", "else"]
  591. return tokenized_text
  592. def _tokenize(self, text, **kwargs):
  593. """
  594. Converts a string into a sequence of tokens (string), using the tokenizer. Split in words for word-based
  595. vocabulary or sub-words for sub-word-based vocabularies (BPE/SentencePieces/WordPieces).
  596. Do NOT take care of added tokens.
  597. """
  598. raise NotImplementedError
  599. def convert_tokens_to_ids(self, tokens: Union[str, list[str]]) -> Union[int, list[int]]:
  600. """
  601. Converts a token string (or a sequence of tokens) in a single integer id (or a sequence of ids), using the
  602. vocabulary.
  603. Args:
  604. tokens (`str` or `list[str]`): One or several token(s) to convert to token id(s).
  605. Returns:
  606. `int` or `list[int]`: The token id or list of token ids.
  607. """
  608. if tokens is None:
  609. return None
  610. if isinstance(tokens, str):
  611. return self._convert_token_to_id_with_added_voc(tokens)
  612. ids = []
  613. for token in tokens:
  614. ids.append(self._convert_token_to_id_with_added_voc(token))
  615. return ids
  616. def _convert_token_to_id_with_added_voc(self, token):
  617. if token is None:
  618. return None
  619. if token in self._added_tokens_encoder:
  620. return self._added_tokens_encoder[token]
  621. return self._convert_token_to_id(token)
  622. def _convert_token_to_id(self, token):
  623. raise NotImplementedError
  624. def _encode_plus(
  625. self,
  626. text: Union[TextInput, PreTokenizedInput, EncodedInput],
  627. text_pair: Optional[Union[TextInput, PreTokenizedInput, EncodedInput]] = None,
  628. add_special_tokens: bool = True,
  629. padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
  630. truncation_strategy: TruncationStrategy = TruncationStrategy.DO_NOT_TRUNCATE,
  631. max_length: Optional[int] = None,
  632. stride: int = 0,
  633. is_split_into_words: bool = False,
  634. pad_to_multiple_of: Optional[int] = None,
  635. padding_side: Optional[str] = None,
  636. return_tensors: Optional[Union[str, TensorType]] = None,
  637. return_token_type_ids: Optional[bool] = None,
  638. return_attention_mask: Optional[bool] = None,
  639. return_overflowing_tokens: bool = False,
  640. return_special_tokens_mask: bool = False,
  641. return_offsets_mapping: bool = False,
  642. return_length: bool = False,
  643. verbose: bool = True,
  644. **kwargs,
  645. ) -> BatchEncoding:
  646. def get_input_ids(text):
  647. if isinstance(text, str):
  648. tokens = self.tokenize(text, **kwargs)
  649. return self.convert_tokens_to_ids(tokens)
  650. elif isinstance(text, (list, tuple)) and len(text) > 0 and isinstance(text[0], str):
  651. if is_split_into_words:
  652. tokens = list(
  653. itertools.chain(*(self.tokenize(t, is_split_into_words=True, **kwargs) for t in text))
  654. )
  655. return self.convert_tokens_to_ids(tokens)
  656. else:
  657. return self.convert_tokens_to_ids(text)
  658. elif isinstance(text, (list, tuple)) and len(text) > 0 and isinstance(text[0], int):
  659. return text
  660. else:
  661. if is_split_into_words:
  662. raise ValueError(
  663. f"Input {text} is not valid. Should be a string or a list/tuple of strings when"
  664. " `is_split_into_words=True`."
  665. )
  666. else:
  667. raise ValueError(
  668. f"Input {text} is not valid. Should be a string, a list/tuple of strings or a list/tuple of"
  669. " integers."
  670. )
  671. if return_offsets_mapping:
  672. raise NotImplementedError(
  673. "return_offset_mapping is not available when using Python tokenizers. "
  674. "To use this feature, change your tokenizer to one deriving from "
  675. "transformers.PreTrainedTokenizerFast. "
  676. "More information on available tokenizers at "
  677. "https://github.com/huggingface/transformers/pull/2674"
  678. )
  679. first_ids = get_input_ids(text)
  680. second_ids = get_input_ids(text_pair) if text_pair is not None else None
  681. return self.prepare_for_model(
  682. first_ids,
  683. pair_ids=second_ids,
  684. add_special_tokens=add_special_tokens,
  685. padding=padding_strategy.value,
  686. truncation=truncation_strategy.value,
  687. max_length=max_length,
  688. stride=stride,
  689. pad_to_multiple_of=pad_to_multiple_of,
  690. padding_side=padding_side,
  691. return_tensors=return_tensors,
  692. prepend_batch_axis=True,
  693. return_attention_mask=return_attention_mask,
  694. return_token_type_ids=return_token_type_ids,
  695. return_overflowing_tokens=return_overflowing_tokens,
  696. return_special_tokens_mask=return_special_tokens_mask,
  697. return_length=return_length,
  698. verbose=verbose,
  699. )
  700. def _batch_encode_plus(
  701. self,
  702. batch_text_or_text_pairs: Union[
  703. list[TextInput],
  704. list[TextInputPair],
  705. list[PreTokenizedInput],
  706. list[PreTokenizedInputPair],
  707. list[EncodedInput],
  708. list[EncodedInputPair],
  709. ],
  710. add_special_tokens: bool = True,
  711. padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
  712. truncation_strategy: TruncationStrategy = TruncationStrategy.DO_NOT_TRUNCATE,
  713. max_length: Optional[int] = None,
  714. stride: int = 0,
  715. is_split_into_words: bool = False,
  716. pad_to_multiple_of: Optional[int] = None,
  717. padding_side: Optional[str] = None,
  718. return_tensors: Optional[Union[str, TensorType]] = None,
  719. return_token_type_ids: Optional[bool] = None,
  720. return_attention_mask: Optional[bool] = None,
  721. return_overflowing_tokens: bool = False,
  722. return_special_tokens_mask: bool = False,
  723. return_offsets_mapping: bool = False,
  724. return_length: bool = False,
  725. verbose: bool = True,
  726. split_special_tokens: bool = False,
  727. **kwargs,
  728. ) -> BatchEncoding:
  729. def get_input_ids(text):
  730. if isinstance(text, str):
  731. tokens = self.tokenize(text, **kwargs)
  732. return self.convert_tokens_to_ids(tokens)
  733. elif isinstance(text, (list, tuple)) and len(text) > 0 and isinstance(text[0], str):
  734. if is_split_into_words:
  735. tokens = list(
  736. itertools.chain(*(self.tokenize(t, is_split_into_words=True, **kwargs) for t in text))
  737. )
  738. return self.convert_tokens_to_ids(tokens)
  739. else:
  740. return self.convert_tokens_to_ids(text)
  741. elif isinstance(text, (list, tuple)) and len(text) > 0 and isinstance(text[0], int):
  742. return text
  743. else:
  744. raise ValueError(
  745. "Input is not valid. Should be a string, a list/tuple of strings or a list/tuple of integers."
  746. )
  747. if return_offsets_mapping:
  748. raise NotImplementedError(
  749. "return_offset_mapping is not available when using Python tokenizers. "
  750. "To use this feature, change your tokenizer to one deriving from "
  751. "transformers.PreTrainedTokenizerFast."
  752. )
  753. input_ids = []
  754. for ids_or_pair_ids in batch_text_or_text_pairs:
  755. if (
  756. not isinstance(ids_or_pair_ids, (list, tuple))
  757. or is_split_into_words
  758. and not isinstance(ids_or_pair_ids[0], (list, tuple))
  759. ):
  760. ids, pair_ids = ids_or_pair_ids, None
  761. else:
  762. ids, pair_ids = ids_or_pair_ids
  763. first_ids = get_input_ids(ids)
  764. second_ids = get_input_ids(pair_ids) if pair_ids is not None else None
  765. input_ids.append((first_ids, second_ids))
  766. batch_outputs = self._batch_prepare_for_model(
  767. input_ids,
  768. add_special_tokens=add_special_tokens,
  769. padding_strategy=padding_strategy,
  770. truncation_strategy=truncation_strategy,
  771. max_length=max_length,
  772. stride=stride,
  773. pad_to_multiple_of=pad_to_multiple_of,
  774. padding_side=padding_side,
  775. return_attention_mask=return_attention_mask,
  776. return_token_type_ids=return_token_type_ids,
  777. return_overflowing_tokens=return_overflowing_tokens,
  778. return_special_tokens_mask=return_special_tokens_mask,
  779. return_length=return_length,
  780. return_tensors=return_tensors,
  781. verbose=verbose,
  782. split_special_tokens=split_special_tokens,
  783. )
  784. return BatchEncoding(batch_outputs)
  785. @add_end_docstrings(ENCODE_KWARGS_DOCSTRING, ENCODE_PLUS_ADDITIONAL_KWARGS_DOCSTRING)
  786. def _batch_prepare_for_model(
  787. self,
  788. batch_ids_pairs: list[Union[PreTokenizedInputPair, tuple[list[int], None]]],
  789. add_special_tokens: bool = True,
  790. padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
  791. truncation_strategy: TruncationStrategy = TruncationStrategy.DO_NOT_TRUNCATE,
  792. max_length: Optional[int] = None,
  793. stride: int = 0,
  794. pad_to_multiple_of: Optional[int] = None,
  795. padding_side: Optional[str] = None,
  796. return_tensors: Optional[str] = None,
  797. return_token_type_ids: Optional[bool] = None,
  798. return_attention_mask: Optional[bool] = None,
  799. return_overflowing_tokens: bool = False,
  800. return_special_tokens_mask: bool = False,
  801. return_length: bool = False,
  802. verbose: bool = True,
  803. split_special_tokens: bool = False,
  804. ) -> BatchEncoding:
  805. """
  806. Prepares a sequence of input id, or a pair of sequences of inputs ids so that it can be used by the model. It
  807. adds special tokens, truncates sequences if overflowing while taking into account the special tokens and
  808. manages a moving window (with user defined stride) for overflowing tokens
  809. Args:
  810. batch_ids_pairs: list of tokenized input ids or input ids pairs
  811. """
  812. batch_outputs = {}
  813. for first_ids, second_ids in batch_ids_pairs:
  814. outputs = self.prepare_for_model(
  815. first_ids,
  816. second_ids,
  817. add_special_tokens=add_special_tokens,
  818. padding=PaddingStrategy.DO_NOT_PAD.value, # we pad in batch afterward
  819. truncation=truncation_strategy.value,
  820. max_length=max_length,
  821. stride=stride,
  822. pad_to_multiple_of=None, # we pad in batch afterward
  823. padding_side=None, # we pad in batch afterward
  824. return_attention_mask=False, # we pad in batch afterward
  825. return_token_type_ids=return_token_type_ids,
  826. return_overflowing_tokens=return_overflowing_tokens,
  827. return_special_tokens_mask=return_special_tokens_mask,
  828. return_length=return_length,
  829. return_tensors=None, # We convert the whole batch to tensors at the end
  830. prepend_batch_axis=False,
  831. verbose=verbose,
  832. split_special_tokens=split_special_tokens,
  833. )
  834. for key, value in outputs.items():
  835. if key not in batch_outputs:
  836. batch_outputs[key] = []
  837. batch_outputs[key].append(value)
  838. batch_outputs = self.pad(
  839. batch_outputs,
  840. padding=padding_strategy.value,
  841. max_length=max_length,
  842. pad_to_multiple_of=pad_to_multiple_of,
  843. padding_side=padding_side,
  844. return_attention_mask=return_attention_mask,
  845. )
  846. batch_outputs = BatchEncoding(batch_outputs, tensor_type=return_tensors)
  847. return batch_outputs
  848. def prepare_for_tokenization(
  849. self, text: str, is_split_into_words: bool = False, **kwargs
  850. ) -> tuple[str, dict[str, Any]]:
  851. """
  852. Performs any necessary transformations before tokenization.
  853. This method should pop the arguments from kwargs and return the remaining `kwargs` as well. We test the
  854. `kwargs` at the end of the encoding process to be sure all the arguments have been used.
  855. Args:
  856. text (`str`):
  857. The text to prepare.
  858. is_split_into_words (`bool`, *optional*, defaults to `False`):
  859. Whether or not the input is already pre-tokenized (e.g., split into words). If set to `True`, the
  860. tokenizer assumes the input is already split into words (for instance, by splitting it on whitespace)
  861. which it will tokenize. This is useful for NER or token classification.
  862. kwargs (`dict[str, Any]`, *optional*):
  863. Keyword arguments to use for the tokenization.
  864. Returns:
  865. `tuple[str, dict[str, Any]]`: The prepared text and the unused kwargs.
  866. """
  867. return (text, kwargs)
  868. def get_special_tokens_mask(
  869. self, token_ids_0: list, token_ids_1: Optional[list] = None, already_has_special_tokens: bool = False
  870. ) -> list[int]:
  871. """
  872. Retrieves sequence ids from a token list that has no special tokens added. This method is called when adding
  873. special tokens using the tokenizer `prepare_for_model` or `encode_plus` methods.
  874. Args:
  875. token_ids_0 (`list[int]`):
  876. List of ids of the first sequence.
  877. token_ids_1 (`list[int]`, *optional*):
  878. List of ids of the second sequence.
  879. already_has_special_tokens (`bool`, *optional*, defaults to `False`):
  880. Whether or not the token list is already formatted with special tokens for the model.
  881. Returns:
  882. A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
  883. """
  884. if already_has_special_tokens:
  885. if token_ids_1 is not None:
  886. raise ValueError(
  887. "You should not supply a second sequence if the provided sequence of "
  888. "ids is already formatted with special tokens for the model."
  889. )
  890. return super().get_special_tokens_mask(
  891. token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
  892. )
  893. return [0] * ((len(token_ids_1) if token_ids_1 else 0) + len(token_ids_0))
  894. @overload
  895. def convert_ids_to_tokens(self, ids: int, skip_special_tokens: bool = False) -> str: ...
  896. @overload
  897. def convert_ids_to_tokens(self, ids: list[int], skip_special_tokens: bool = False) -> list[str]: ...
  898. def convert_ids_to_tokens(
  899. self, ids: Union[int, list[int]], skip_special_tokens: bool = False
  900. ) -> Union[str, list[str]]:
  901. """
  902. Converts a single index or a sequence of indices in a token or a sequence of tokens, using the vocabulary and
  903. added tokens.
  904. Args:
  905. ids (`int` or `list[int]`):
  906. The token id (or token ids) to convert to tokens.
  907. skip_special_tokens (`bool`, *optional*, defaults to `False`):
  908. Whether or not to remove special tokens in the decoding.
  909. Returns:
  910. `str` or `list[str]`: The decoded token(s).
  911. """
  912. if isinstance(ids, int):
  913. if ids in self._added_tokens_decoder:
  914. return self._added_tokens_decoder[ids].content
  915. else:
  916. return self._convert_id_to_token(ids)
  917. tokens = []
  918. for index in ids:
  919. index = int(index)
  920. if skip_special_tokens and index in self.all_special_ids:
  921. continue
  922. if index in self._added_tokens_decoder:
  923. tokens.append(self._added_tokens_decoder[index].content)
  924. else:
  925. tokens.append(self._convert_id_to_token(index))
  926. return tokens
  927. def _convert_id_to_token(self, index: int) -> str:
  928. raise NotImplementedError
  929. def convert_tokens_to_string(self, tokens: list[str]) -> str:
  930. return " ".join(tokens)
  931. def _decode(
  932. self,
  933. token_ids: Union[int, list[int]],
  934. skip_special_tokens: bool = False,
  935. clean_up_tokenization_spaces: Optional[bool] = None,
  936. spaces_between_special_tokens: bool = True,
  937. **kwargs,
  938. ) -> str:
  939. self._decode_use_source_tokenizer = kwargs.pop("use_source_tokenizer", False)
  940. filtered_tokens = self.convert_ids_to_tokens(token_ids, skip_special_tokens=skip_special_tokens)
  941. # If given is a single id, prevents splitting the string in upcoming loop
  942. if isinstance(filtered_tokens, str):
  943. filtered_tokens = [filtered_tokens]
  944. legacy_added_tokens = set(self._added_tokens_encoder.keys()) - set(self.all_special_tokens) | {
  945. token for token in self.additional_special_tokens if self.convert_tokens_to_ids(token) >= self.vocab_size
  946. }
  947. # To avoid mixing byte-level and unicode for byte-level BPT
  948. # we need to build string separately for added tokens and byte-level tokens
  949. # cf. https://github.com/huggingface/transformers/issues/1133
  950. sub_texts = []
  951. current_sub_text = []
  952. # TODO @ArthurZ in version 5, special tokens should be handled in convert_tokens_to_string, while _convert_tokens_to_string
  953. for token in filtered_tokens:
  954. if skip_special_tokens and token in self.all_special_tokens:
  955. continue
  956. if token in legacy_added_tokens:
  957. if current_sub_text:
  958. string = self.convert_tokens_to_string(current_sub_text)
  959. if len(string) > 0:
  960. sub_texts.append(string)
  961. current_sub_text = []
  962. sub_texts.append(token)
  963. else:
  964. current_sub_text.append(token)
  965. if current_sub_text:
  966. sub_texts.append(self.convert_tokens_to_string(current_sub_text))
  967. if spaces_between_special_tokens:
  968. text = " ".join(sub_texts)
  969. else:
  970. text = "".join(sub_texts)
  971. clean_up_tokenization_spaces = (
  972. clean_up_tokenization_spaces
  973. if clean_up_tokenization_spaces is not None
  974. else self.clean_up_tokenization_spaces
  975. )
  976. if clean_up_tokenization_spaces:
  977. clean_text = self.clean_up_tokenization(text)
  978. return clean_text
  979. else:
  980. return text