tokenization_python.py 61 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418
  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_tokenizers.py
  17. """
  18. import bisect
  19. import unicodedata
  20. from collections import OrderedDict
  21. from typing import Any, overload
  22. from .tokenization_utils_base import (
  23. INIT_TOKENIZER_DOCSTRING,
  24. AddedToken,
  25. BatchEncoding,
  26. EncodedInput,
  27. PreTokenizedInput,
  28. PreTrainedTokenizerBase,
  29. TextInput,
  30. TruncationStrategy,
  31. )
  32. from .utils import PaddingStrategy, TensorType, add_end_docstrings, logging
  33. logger = logging.get_logger(__name__)
  34. # Slow tokenizers are saved in a vocabulary plus three separated files
  35. SPECIAL_TOKENS_MAP_FILE = "special_tokens_map.json"
  36. ADDED_TOKENS_FILE = "added_tokens.json"
  37. TOKENIZER_CONFIG_FILE = "tokenizer_config.json"
  38. class Trie:
  39. """
  40. Trie in Python. Creates a Trie out of a list of words. The trie is used to split on `added_tokens` in one pass
  41. Loose reference https://en.wikipedia.org/wiki/Trie
  42. """
  43. def __init__(self, *args):
  44. self.data = {}
  45. self._tokens = set()
  46. self._termination_char = ""
  47. self.update(*args)
  48. def update(self, *args):
  49. """
  50. Updates the Trie with new tokens provided as arguments.
  51. Args:
  52. *args: Variable number of words to be added to the Trie.
  53. """
  54. for token in tuple(*args):
  55. self.add(token)
  56. def add(self, word: str):
  57. """
  58. Passes over every char (utf-8 char) on word and recursively adds it to the internal `data` trie representation.
  59. The special key `""` in `self._termination_char` is used to represent termination.
  60. This function is idempotent, adding twice the same word will leave the trie unchanged
  61. Example:
  62. ```python
  63. >>> trie = Trie()
  64. >>> trie.add("Hello 友達")
  65. >>> trie.data
  66. {"H": {"e": {"l": {"l": {"o": {" ": {"友": {"達": {"": 1}}}}}}}}}
  67. >>> trie.add("Hello")
  68. >>> trie.data
  69. {"H": {"e": {"l": {"l": {"o": {"": 1, " ": {"友": {"達": {"": 1}}}}}}}}}
  70. ```
  71. """
  72. if not word:
  73. # Prevent empty string
  74. return
  75. self._tokens.add(word)
  76. ref = self.data
  77. for char in word:
  78. ref[char] = ref.setdefault(char, {})
  79. ref = ref[char]
  80. ref[self._termination_char] = 1
  81. def split(self, text: str) -> list[str]:
  82. """
  83. Will look for the words added to the trie within `text`. Output is the original string split along the
  84. boundaries of the words found.
  85. This trie will match the longest possible word first !
  86. Example:
  87. ```python
  88. >>> trie = Trie()
  89. >>> trie.split("[CLS] This is a extra_id_100")
  90. ["[CLS] This is a extra_id_100"]
  91. >>> trie.add("[CLS]")
  92. >>> trie.add("extra_id_1")
  93. >>> trie.add("extra_id_100")
  94. >>> trie.split("[CLS] This is a extra_id_100")
  95. ["[CLS]", " This is a ", "extra_id_100"]
  96. ```
  97. """
  98. # indexes are counted left of the chars index.
  99. # "hello", index 0, is left of h, index 1 is between h and e.
  100. # index 5 is right of the "o".
  101. # States are going to capture every possible start (indexes as above)
  102. # as keys, and have as values, a pointer to the position in the trie
  103. # where we're at. This is a partial match for now.
  104. # This enables to keep track of multiple matches while we're iterating
  105. # the string
  106. # If the trie contains, "blowing", and "lower" and we encounter the
  107. # string "blower", we need to split into ["b", "lower"].
  108. # This is where we need to keep track of multiple possible starts.
  109. states = OrderedDict()
  110. # This will contain every indices where we need
  111. # to cut.
  112. # We force to cut at offset 0 and len(text) (added later)
  113. offsets = [0]
  114. # This is used by the lookahead which needs to skip over
  115. # some text where the full match exceeded the place in the initial
  116. # for loop
  117. skip = 0
  118. # Main loop, Giving this algorithm O(n) complexity
  119. for current, current_char in enumerate(text):
  120. if skip and current < skip:
  121. # Prevents the lookahead for matching twice
  122. # like extra_id_100 and id_100
  123. continue
  124. # This will track every state
  125. # that stop matching, we need to stop tracking them.
  126. # If we look at "lowball", we're going to match "l" (add it to states), "o", "w", then
  127. # fail on "b", we need to remove 0 from the valid states.
  128. to_remove = set()
  129. # Whenever we found a match, we need to drop everything
  130. # this is a greedy algorithm, it will match on the first found token
  131. reset = False
  132. # In this case, we already have partial matches (But unfinished)
  133. for start, trie_pointer in states.items():
  134. if "" in trie_pointer:
  135. # This is a final match, we need to reset and
  136. # store the results in `offsets`.
  137. # Lookahead to match longest first
  138. # Important in case of extra_id_1 vs extra_id_100
  139. # Here we are also actively looking for other earlier partial
  140. # matches
  141. # "[CLS]", "L", we need to match CLS even if L is special
  142. for lookstart, looktrie_pointer in states.items():
  143. if lookstart > start:
  144. # This partial match is later, we can stop looking
  145. break
  146. elif lookstart < start:
  147. # This partial match is earlier, the trie pointer
  148. # was already updated, so index is + 1
  149. lookahead_index = current + 1
  150. end = current + 1
  151. else:
  152. # Here lookstart == start and
  153. # looktrie_pointer == trie_pointer
  154. # It wasn't updated yet so indices are current ones
  155. lookahead_index = current
  156. end = current
  157. next_char = text[lookahead_index] if lookahead_index < len(text) else None
  158. if "" in looktrie_pointer:
  159. start = lookstart
  160. end = lookahead_index
  161. skip = lookahead_index
  162. while next_char in looktrie_pointer:
  163. looktrie_pointer = looktrie_pointer[next_char]
  164. lookahead_index += 1
  165. if "" in looktrie_pointer:
  166. start = lookstart
  167. end = lookahead_index
  168. skip = lookahead_index
  169. if lookahead_index == len(text):
  170. # End of string
  171. break
  172. next_char = text[lookahead_index]
  173. # End lookahead
  174. # Storing and resetting
  175. offsets.append(start)
  176. offsets.append(end)
  177. reset = True
  178. break
  179. elif current_char in trie_pointer:
  180. # The current character being looked at has a match within the trie
  181. # update the pointer (it will be stored back into states later).
  182. trie_pointer = trie_pointer[current_char]
  183. # Storing back the new pointer into the states.
  184. # Partial matches got longer by one.
  185. states[start] = trie_pointer
  186. else:
  187. # The new character has not match in the trie, we need
  188. # to stop keeping track of this partial match.
  189. # We can't do it directly within the loop because of how
  190. # python iteration works
  191. to_remove.add(start)
  192. # Either clearing the full start (we found a real match)
  193. # Or clearing only the partial matches that didn't work.
  194. if reset:
  195. states = {}
  196. else:
  197. for start in to_remove:
  198. del states[start]
  199. # If this character is a starting character within the trie
  200. # start keeping track of this partial match.
  201. if current >= skip and current_char in self.data:
  202. states[current] = self.data[current_char]
  203. # We have a cut at the end with states.
  204. for start, trie_pointer in states.items():
  205. if "" in trie_pointer:
  206. # This is a final match, we need to reset and
  207. # store the results in `offsets`.
  208. end = len(text)
  209. offsets.append(start)
  210. offsets.append(end)
  211. # Longest cut is always the one with lower start so the first
  212. # item so we need to break.
  213. break
  214. return self.cut_text(text, offsets)
  215. def cut_text(self, text, offsets):
  216. # We have all the offsets now, we just need to do the actual splitting.
  217. # We need to eventually add the first part of the string and the eventual
  218. # last part.
  219. offsets.append(len(text))
  220. tokens = []
  221. start = 0
  222. for end in offsets:
  223. if start > end:
  224. logger.error(
  225. "There was a bug in Trie algorithm in tokenization. Attempting to recover. Please report it"
  226. " anyway."
  227. )
  228. continue
  229. elif start == end:
  230. # This might happen if there's a match at index 0
  231. # we're also preventing zero-width cuts in case of two
  232. # consecutive matches
  233. continue
  234. tokens.append(text[start:end])
  235. start = end
  236. return tokens
  237. class ExtensionsTrie(Trie):
  238. def __init__(self, *args):
  239. super().__init__(*args)
  240. def extensions(self, prefix: str):
  241. """
  242. Generates all extensions of a given prefix token in the Trie.
  243. Example:
  244. ```python
  245. >>> trie = Trie()
  246. >>> trie.add("apple")
  247. >>> trie.add("app")
  248. >>> trie.add("application")
  249. >>> trie.extensions("app")
  250. ['app', 'apple', 'application']
  251. ```
  252. """
  253. prefix_node = self._get_node(prefix)
  254. ret = self._collect_tokens(prefix_node)
  255. return [prefix + token for token in ret]
  256. def _get_node(self, token: str) -> dict:
  257. """
  258. Retrieves the node corresponding to the given token in the Trie.
  259. Args:
  260. token (str): The token for which the corresponding node needs to be retrieved.
  261. Returns:
  262. dict: The node in the Trie corresponding to the given token.
  263. """
  264. node = self.data
  265. for char in token:
  266. if char not in node:
  267. break
  268. node = node[char]
  269. return node
  270. def _collect_tokens(self, node: dict) -> list:
  271. """
  272. Generates all tokens in the Trie starting from a given node.
  273. Args:
  274. node (dict): The node in the Trie from which tokens need to be generated.
  275. Returns:
  276. list: List of tokens generated from the given node.
  277. """
  278. tokens = [self._termination_char] if self._termination_char in node else []
  279. for token, subtrie_head in node.items():
  280. if token != self._termination_char:
  281. subtokens = self._collect_tokens(subtrie_head)
  282. tokens.extend([token + subtoken for subtoken in subtokens])
  283. return tokens
  284. def _is_whitespace(char):
  285. """Checks whether `char` is a whitespace character."""
  286. # \t, \n, and \r are technically control characters but we treat them
  287. # as whitespace since they are generally considered as such.
  288. if char == " " or char == "\t" or char == "\n" or char == "\r":
  289. return True
  290. cat = unicodedata.category(char)
  291. if cat == "Zs":
  292. return True
  293. return False
  294. def _is_control(char):
  295. """Checks whether `char` is a control character."""
  296. # These are technically control characters but we count them as whitespace
  297. # characters.
  298. if char == "\t" or char == "\n" or char == "\r":
  299. return False
  300. cat = unicodedata.category(char)
  301. if cat.startswith("C"):
  302. return True
  303. return False
  304. def _is_punctuation(char):
  305. """Checks whether `char` is a punctuation character."""
  306. cp = ord(char)
  307. # We treat all non-letter/number ASCII as punctuation.
  308. # Characters such as "^", "$", and "`" are not in the Unicode
  309. # Punctuation class but we treat them as punctuation anyways, for
  310. # consistency.
  311. if (cp >= 33 and cp <= 47) or (cp >= 58 and cp <= 64) or (cp >= 91 and cp <= 96) or (cp >= 123 and cp <= 126):
  312. return True
  313. cat = unicodedata.category(char)
  314. if cat.startswith("P"):
  315. return True
  316. return False
  317. def _is_end_of_word(text):
  318. """Checks whether the last character in text is one of a punctuation, control or whitespace character."""
  319. last_char = text[-1]
  320. return bool(_is_control(last_char) | _is_punctuation(last_char) | _is_whitespace(last_char))
  321. def _is_start_of_word(text):
  322. """Checks whether the first character in text is one of a punctuation, control or whitespace character."""
  323. first_char = text[0]
  324. return bool(_is_control(first_char) | _is_punctuation(first_char) | _is_whitespace(first_char))
  325. def _insert_one_token_to_ordered_list(token_list: list[str], new_token: str):
  326. """
  327. Inserts one token to an ordered list if it does not already exist. Note: token_list must be sorted.
  328. """
  329. insertion_idx = bisect.bisect_left(token_list, new_token)
  330. # Checks if new_token is already in the ordered token_list
  331. if insertion_idx < len(token_list) and token_list[insertion_idx] == new_token:
  332. # new_token is in token_list, don't add
  333. return
  334. else:
  335. token_list.insert(insertion_idx, new_token)
  336. @add_end_docstrings(INIT_TOKENIZER_DOCSTRING)
  337. class PythonBackend(PreTrainedTokenizerBase):
  338. """
  339. Base class for all slow tokenizers.
  340. Inherits from [`~tokenization_utils_base.PreTrainedTokenizerBase`].
  341. Handle all the shared methods for tokenization and special tokens as well as methods downloading/caching/loading
  342. pretrained tokenizers as well as adding tokens to the vocabulary.
  343. This class also contain the added tokens in a unified way on top of all tokenizers so we don't have to handle the
  344. specific vocabulary augmentation methods of the various underlying dictionary structures (BPE, sentencepiece...).
  345. """
  346. def __init__(self, **kwargs):
  347. # 1. Init the parent class
  348. self.tokens_trie = Trie()
  349. # Initialize total_vocab_size early to avoid issues if get_vocab() is called early (custom tokenizers)
  350. self.total_vocab_size = 0
  351. # 2. init `_added_tokens_decoder` if child class did not
  352. if not hasattr(self, "_added_tokens_decoder"):
  353. self._added_tokens_decoder: dict[int, AddedToken] = {}
  354. # 3. if a `added_tokens_decoder` is passed, we are loading from a saved tokenizer, we overwrite
  355. self._added_tokens_decoder.update(kwargs.pop("added_tokens_decoder", {}))
  356. self._added_tokens_encoder: dict[str, int] = {k.content: v for v, k in self._added_tokens_decoder.items()}
  357. # 4. Token type ID configuration for dynamic mask building
  358. # These can be overridden by subclasses to avoid overriding create_token_type_ids_from_sequences
  359. self.token_type_ids_pattern = kwargs.pop("token_type_ids_pattern", "bert_style") # "all_zeros" or "bert_style"
  360. self.token_type_ids_include_special_tokens = kwargs.pop("token_type_ids_include_special_tokens", True)
  361. # 5. Special tokens mask configuration
  362. # Patterns: "none", "cls_sep", "eos", "bos", "bos_eos", "cls_double_sep", "prefix_suffix"
  363. self.special_tokens_pattern = kwargs.pop("special_tokens_pattern", None)
  364. # 6. Set backend to "custom" if not already set (for direct PreTrainedTokenizer subclasses)
  365. if "backend" not in kwargs:
  366. kwargs["backend"] = "custom"
  367. # 7. init the parent class
  368. super().__init__(**kwargs)
  369. # 4. If some of the special tokens are not part of the vocab, we add them, at the end.
  370. # V5: the order of addition follows self.SPECIAL_TOKENS_ATTRIBUTES, then extra special tokens
  371. # Note: _add_tokens will automatically skip tokens that are already in the base vocab
  372. self._add_tokens(
  373. [token for token in self.all_special_tokens if token not in self._added_tokens_encoder],
  374. special_tokens=True,
  375. )
  376. @property
  377. def is_fast(self) -> bool:
  378. return False
  379. @property
  380. def added_tokens_encoder(self) -> dict[str, int]:
  381. """
  382. Returns the sorted mapping from string to index. The added tokens encoder is cached for performance
  383. optimisation in `self._added_tokens_encoder` for the slow tokenizers.
  384. """
  385. return {k.content: v for v, k in sorted(self._added_tokens_decoder.items(), key=lambda item: item[0])}
  386. @property
  387. def added_tokens_decoder(self) -> dict[int, AddedToken]:
  388. """
  389. Returns the added tokens in the vocabulary as a dictionary of index to AddedToken.
  390. Returns:
  391. `dict[str, int]`: The added tokens.
  392. """
  393. return dict(sorted(self._added_tokens_decoder.items(), key=lambda item: item[0]))
  394. @added_tokens_decoder.setter
  395. def added_tokens_decoder(self, value: dict[int, AddedToken | str]) -> dict[int, AddedToken]:
  396. # Always raise an error if string because users should define the behavior
  397. for index, token in value.items():
  398. if not isinstance(token, (str, AddedToken)) or not isinstance(index, int):
  399. raise TypeError(
  400. f"The provided `added_tokens_decoder` has an element of type {index.__class__, token.__class__}, should be a dict of {int, AddedToken | str}"
  401. )
  402. self._added_tokens_decoder[index] = AddedToken(token) if isinstance(token, str) else token
  403. self._added_tokens_encoder[str(token)] = index
  404. self._update_total_vocab_size()
  405. def get_added_vocab(self) -> dict[str, int]:
  406. """
  407. Returns the added tokens in the vocabulary as a dictionary of token to index. Results might be different from
  408. the fast call because for now we always add the tokens even if they are already in the vocabulary. This is
  409. something we should change.
  410. Returns:
  411. `dict[str, int]`: The added tokens.
  412. """
  413. return self._added_tokens_encoder
  414. def __len__(self):
  415. """
  416. Size of the full vocabulary with the added tokens.
  417. """
  418. # Lazy evaluation: compute if not already set (e.g., during initialization)
  419. if self.total_vocab_size == 0:
  420. self._update_total_vocab_size()
  421. return self.total_vocab_size
  422. def _update_total_vocab_size(self):
  423. """
  424. Update the size of the full vocabulary with the added tokens. Counts the `keys` and not the `values` because
  425. otherwise if there is a hole in the vocab, we will add tokenizers at a wrong index. This operation is slow and
  426. is only updated when adding tokens.
  427. """
  428. self.total_vocab_size = len(self.get_vocab())
  429. def _add_tokens(self, new_tokens: list[str] | list[AddedToken], special_tokens: bool = False) -> int:
  430. """
  431. Add a list of new tokens to the tokenizer class. If the new tokens are not in the vocabulary, they are added to
  432. it with indices starting from length of the current vocabulary. Special tokens are sometimes already in the
  433. vocab which is why they have to be handled specifically.
  434. Args:
  435. new_tokens (`list[str]`or `list[tokenizers.AddedToken]`):
  436. Token(s) to add in vocabulary. A token is counted as added if it's not already in the vocabulary
  437. (tested by checking if the tokenizer assign the index of the `unk_token` to them). If a token is part
  438. of the vocabulary then we simply mark this token as an `AddedToken` which allows to control the
  439. stripping and normalization of this token. This is NOT possible in `tokenizers`.
  440. special_tokens (`bool`, *optional*, defaults to `False`):
  441. Whether or not the tokens should be added as special tokens.
  442. Returns:
  443. `int`: The number of tokens actually added to the vocabulary.
  444. Examples:
  445. ```python
  446. # Let's see how to increase the vocabulary of Bert model and tokenizer
  447. tokenizer = BertTokenizer.from_pretrained("google-bert/bert-base-uncased")
  448. model = BertModel.from_pretrained("google-bert/bert-base-uncased")
  449. num_added_toks = tokenizer.add_tokens(["new_tok1", "my_new-tok2"])
  450. print("We have added", num_added_toks, "tokens")
  451. # Note: resize_token_embeddings expects to receive the full size of the new vocabulary, i.e. the length of the tokenizer.
  452. model.resize_token_embeddings(len(tokenizer))
  453. ```"""
  454. added_tokens = 0
  455. if new_tokens is None:
  456. return added_tokens
  457. # TODO this is fairly slow to improve!
  458. current_vocab = self.get_vocab().copy()
  459. new_idx = len(current_vocab) # only call this once, len gives the last index + 1
  460. for token in new_tokens:
  461. if not isinstance(token, (str, AddedToken)):
  462. raise TypeError(f"Token {token} is not a string but a {type(token)}.")
  463. if str(token) == "":
  464. continue
  465. if isinstance(token, str):
  466. if token in self._added_tokens_encoder:
  467. continue
  468. else:
  469. # very important for fast and slow equivalence!
  470. is_special = token in self.all_special_tokens or special_tokens
  471. token = AddedToken(
  472. token, rstrip=False, lstrip=False, normalized=not is_special, special=is_special
  473. )
  474. elif special_tokens:
  475. # doing token.special=True changes the normalization! will fix in rust
  476. # this is important and the only reason why the AddedTokens in each class are normalized by default
  477. token.__setstate__({"special": True, "normalized": token.normalized})
  478. if token in self._added_tokens_decoder:
  479. continue
  480. if not token.special and token.normalized and getattr(self, "do_lower_case", False):
  481. # Normalize if requested
  482. token.content = token.content.lower()
  483. if token.content not in current_vocab:
  484. token_index = new_idx + added_tokens
  485. current_vocab[token.content] = token_index
  486. added_tokens += 1
  487. else:
  488. token_index = current_vocab[token.content]
  489. if token.special and str(token) not in self.all_special_tokens:
  490. self._extra_special_tokens.append(token)
  491. # the setter automatically updates the reverse map
  492. self._added_tokens_decoder[token_index] = token
  493. self._added_tokens_encoder[token.content] = token_index
  494. if self.verbose:
  495. logger.info(f"Adding {token} to the vocabulary")
  496. self._update_trie()
  497. self._update_total_vocab_size()
  498. return added_tokens
  499. def _update_trie(self, unique_no_split_tokens: list[str] | None = None):
  500. for token in self._added_tokens_decoder.values():
  501. if token.content not in self.tokens_trie._tokens:
  502. self.tokens_trie.add(token.content)
  503. for token in unique_no_split_tokens or []:
  504. if token not in self.tokens_trie._tokens:
  505. self.tokens_trie.add(token)
  506. def num_special_tokens_to_add(self, pair: bool = False) -> int:
  507. """
  508. Returns the number of added tokens when encoding a sequence with special tokens.
  509. <Tip>
  510. This encodes a dummy input and checks the number of added tokens, and is therefore not efficient. Do not put
  511. this inside your training loop.
  512. </Tip>
  513. Args:
  514. pair (`bool`, *optional*, defaults to `False`):
  515. Whether the number of added tokens should be computed in the case of a sequence pair or a single
  516. sequence.
  517. Returns:
  518. `int`: Number of special tokens added to sequences.
  519. """
  520. token_ids_0 = []
  521. token_ids_1 = []
  522. return len(self.build_inputs_with_special_tokens(token_ids_0, token_ids_1 if pair else None))
  523. def tokenize(self, text: TextInput, **kwargs) -> list[str]:
  524. """
  525. Converts a string into a sequence of tokens, using the tokenizer.
  526. Args:
  527. text: The sequence to be encoded.
  528. **kwargs: Passed along to the model-specific `prepare_for_tokenization` preprocessing method.
  529. Returns:
  530. The list of tokens.
  531. """
  532. split_special_tokens = kwargs.pop("split_special_tokens", self.split_special_tokens)
  533. text, kwargs = self.prepare_for_tokenization(text, **kwargs)
  534. if split_special_tokens:
  535. # Don't split on any tokens - just tokenize directly
  536. return self._tokenize(text)
  537. # Split on added tokens
  538. tokens = self.tokens_trie.split(text)
  539. no_split_token = self._added_tokens_encoder.keys()
  540. # Handle added token properties (lstrip, rstrip, single_word)
  541. for i, token in enumerate(tokens):
  542. if token in no_split_token:
  543. tok_extended = self._added_tokens_decoder.get(self._added_tokens_encoder[token])
  544. left = tokens[i - 1] if i > 0 else None
  545. right = tokens[i + 1] if i < len(tokens) - 1 else None
  546. if isinstance(tok_extended, AddedToken):
  547. if tok_extended.rstrip and right:
  548. tokens[i + 1] = right.lstrip()
  549. if tok_extended.lstrip and left:
  550. tokens[i - 1] = left.rstrip()
  551. if tok_extended.single_word:
  552. if left and left[-1] != " ":
  553. tokens[i - 1] += token
  554. tokens[i] = ""
  555. elif right and right[0] != " ":
  556. tokens[i + 1] = token + tokens[i + 1]
  557. tokens[i] = ""
  558. # Tokenize non-added tokens
  559. result = []
  560. all_special_tokens_set = set(self.all_special_tokens)
  561. for token in tokens:
  562. if not token:
  563. continue
  564. if token in no_split_token or token in all_special_tokens_set:
  565. result.append(token)
  566. else:
  567. result.extend(self._tokenize(token))
  568. return result
  569. def _tokenize(self, text, **kwargs):
  570. """
  571. Converts a string into a sequence of tokens (string), using the tokenizer. Split in words for word-based
  572. vocabulary or sub-words for sub-word-based vocabularies (BPE/SentencePieces/WordPieces).
  573. Do NOT take care of added tokens.
  574. """
  575. raise NotImplementedError
  576. def _convert_token_to_id_with_added_voc(self, token):
  577. if token in self.added_tokens_encoder:
  578. return self.added_tokens_encoder[token]
  579. return self._convert_token_to_id(token)
  580. def _convert_token_to_id(self, token):
  581. raise NotImplementedError
  582. def _encode_plus(
  583. self,
  584. text: TextInput | PreTokenizedInput | EncodedInput,
  585. text_pair: TextInput | PreTokenizedInput | EncodedInput | None = None,
  586. add_special_tokens: bool = True,
  587. padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
  588. truncation_strategy: TruncationStrategy = TruncationStrategy.DO_NOT_TRUNCATE,
  589. max_length: int | None = None,
  590. stride: int = 0,
  591. is_split_into_words: bool = False,
  592. pad_to_multiple_of: int | None = None,
  593. padding_side: str | None = None,
  594. return_tensors: str | TensorType | None = None,
  595. return_token_type_ids: bool | None = None,
  596. return_attention_mask: bool | None = None,
  597. return_overflowing_tokens: bool = False,
  598. return_special_tokens_mask: bool = False,
  599. return_length: bool = False,
  600. verbose: bool = True,
  601. **kwargs,
  602. ) -> BatchEncoding:
  603. # Detect batched inputs (list of sequences)
  604. is_batched = isinstance(text, (list, tuple)) and (
  605. (not text and not is_split_into_words)
  606. or (text and is_split_into_words and isinstance(text[0], (list, tuple)))
  607. or (text and not is_split_into_words and isinstance(text[0], (str, list, tuple)))
  608. )
  609. if is_batched:
  610. if text_pair is not None:
  611. if not isinstance(text_pair, (list, tuple)) or len(text_pair) != len(text):
  612. raise ValueError("If `text` is a batch, `text_pair` must also be a batch of the same length.")
  613. pairs = text_pair if text_pair is not None else [None] * len(text)
  614. batch_outputs = {}
  615. for current_text, current_pair in zip(text, pairs):
  616. # Handle tuples/lists as sequence pairs like ("text1", "text2")
  617. # For is_split_into_words=True: only unpack if it's a tuple of exactly 2 sequences (pair)
  618. # Otherwise, treat the list as a single pretokenized sequence
  619. if (
  620. isinstance(current_text, (list, tuple))
  621. and current_text
  622. and not isinstance(current_text[0], int)
  623. and current_pair is None
  624. ):
  625. # Check if this looks like a pair: tuple/list of length 2 where elements are strings or lists/tuples
  626. is_pair = (
  627. len(current_text) == 2
  628. and (isinstance(current_text[0], str) or isinstance(current_text[0], (list, tuple)))
  629. and (isinstance(current_text[1], str) or isinstance(current_text[1], (list, tuple)))
  630. )
  631. if is_pair:
  632. current_text, current_pair = current_text
  633. elif len(current_text) == 1:
  634. current_text = current_text[0]
  635. elif not is_split_into_words:
  636. # Only raise error for non-pretokenized input
  637. raise ValueError(f"Expected a pair of sequences, got {len(current_text)} sequences.")
  638. current_output = self._encode_plus(
  639. text=current_text,
  640. text_pair=current_pair,
  641. add_special_tokens=add_special_tokens,
  642. padding_strategy=PaddingStrategy.DO_NOT_PAD, # we pad in batch afterward
  643. truncation_strategy=truncation_strategy,
  644. max_length=max_length,
  645. stride=stride,
  646. is_split_into_words=is_split_into_words,
  647. pad_to_multiple_of=None, # we pad in batch afterward
  648. padding_side=None, # we pad in batch afterward
  649. return_tensors=None, # We convert the whole batch to tensors at the end
  650. return_token_type_ids=return_token_type_ids,
  651. return_attention_mask=False, # we pad in batch afterward
  652. return_overflowing_tokens=return_overflowing_tokens,
  653. return_special_tokens_mask=return_special_tokens_mask,
  654. return_length=return_length,
  655. verbose=verbose,
  656. **kwargs,
  657. )
  658. for key, value in current_output.items():
  659. batch_outputs.setdefault(key, []).append(value)
  660. # Remove overflow-related keys before tensor conversion if return_tensors is set
  661. # Slow tokenizers don't support returning these as tensors
  662. if return_tensors and return_overflowing_tokens:
  663. batch_outputs.pop("overflowing_tokens", None)
  664. batch_outputs.pop("num_truncated_tokens", None)
  665. batch_outputs = self.pad(
  666. batch_outputs,
  667. padding=padding_strategy.value,
  668. max_length=max_length,
  669. pad_to_multiple_of=pad_to_multiple_of,
  670. padding_side=padding_side,
  671. return_attention_mask=return_attention_mask,
  672. )
  673. return BatchEncoding(batch_outputs, tensor_type=return_tensors)
  674. # Single sequence handling
  675. def get_input_ids(text):
  676. if isinstance(text, str):
  677. # Normal case: tokenize string
  678. return self.convert_tokens_to_ids(self.tokenize(text, **kwargs))
  679. if isinstance(text, (list, tuple)) and text:
  680. if isinstance(text[0], int):
  681. return text
  682. # Pre-tokenized strings
  683. if isinstance(text[0], str):
  684. if is_split_into_words:
  685. return self.convert_tokens_to_ids(
  686. [tok for word in text for tok in self.tokenize(word, **kwargs)]
  687. )
  688. return self.convert_tokens_to_ids(text)
  689. raise ValueError(f"Input must be a string, list of strings, or list of ints, got: {type(text)}")
  690. first_ids = get_input_ids(text)
  691. second_ids = get_input_ids(text_pair) if text_pair is not None else None
  692. return self.prepare_for_model(
  693. first_ids,
  694. pair_ids=second_ids,
  695. add_special_tokens=add_special_tokens,
  696. padding=padding_strategy.value,
  697. truncation=truncation_strategy.value,
  698. max_length=max_length,
  699. stride=stride,
  700. pad_to_multiple_of=pad_to_multiple_of,
  701. padding_side=padding_side,
  702. return_tensors=return_tensors,
  703. prepend_batch_axis=True,
  704. return_attention_mask=return_attention_mask,
  705. return_token_type_ids=return_token_type_ids,
  706. return_overflowing_tokens=return_overflowing_tokens,
  707. return_special_tokens_mask=return_special_tokens_mask,
  708. return_length=return_length,
  709. verbose=verbose,
  710. )
  711. def prepare_for_tokenization(
  712. self, text: str, is_split_into_words: bool = False, **kwargs
  713. ) -> tuple[str, dict[str, Any]]:
  714. """
  715. Performs any necessary transformations before tokenization.
  716. This method should pop the arguments from kwargs and return the remaining `kwargs` as well. We test the
  717. `kwargs` at the end of the encoding process to be sure all the arguments have been used.
  718. Args:
  719. text (`str`):
  720. The text to prepare.
  721. is_split_into_words (`bool`, *optional*, defaults to `False`):
  722. Whether or not the input is already pre-tokenized (e.g., split into words). If set to `True`, the
  723. tokenizer assumes the input is already split into words (for instance, by splitting it on whitespace)
  724. which it will tokenize. This is useful for NER or token classification.
  725. kwargs (`dict[str, Any]`, *optional*):
  726. Keyword arguments to use for the tokenization.
  727. Returns:
  728. `tuple[str, dict[str, Any]]`: The prepared text and the unused kwargs.
  729. """
  730. return (text, kwargs)
  731. def build_inputs_with_special_tokens(
  732. self, token_ids_0: list[int], token_ids_1: list[int] | None = None
  733. ) -> list[int]:
  734. """
  735. Build model inputs from a sequence or a pair of sequences by adding special tokens.
  736. This method dynamically builds inputs based on the tokenizer's `special_tokens_pattern`:
  737. - `"none"`: No special tokens
  738. - `"cls_sep"`: [CLS] seq0 [SEP] or [CLS] seq0 [SEP] seq1 [SEP]
  739. - `"eos"`: seq0 [EOS] or seq0 [EOS] seq1 [EOS]
  740. - `"bos"`: [BOS] seq0 or [BOS] seq0 [BOS] seq1
  741. - `"bos_eos"`: [BOS] seq0 [EOS] or [BOS] seq0 [EOS] seq1 [EOS]
  742. - `"cls_double_sep"`: [CLS] seq0 [SEP] or [CLS] seq0 [SEP] [SEP] seq1 [SEP]
  743. - `"prefix_suffix"`: `<prefix_tokens> seq0 [seq1] <suffix_tokens>` (custom prefix/suffix stored on the tokenizer)
  744. Args:
  745. token_ids_0 (`list[int]`):
  746. List of IDs to which the special tokens will be added.
  747. token_ids_1 (`list[int]`, *optional*):
  748. Optional second list of IDs for sequence pairs.
  749. Returns:
  750. `list[int]`: List of input IDs with the appropriate special tokens.
  751. """
  752. if self.special_tokens_pattern == "cls_sep":
  753. # [CLS] seq0 [SEP] or [CLS] seq0 [SEP] seq1 [SEP]
  754. if self.cls_token_id is None and self.sep_token_id is None:
  755. raise ValueError(
  756. "Cannot add special tokens following 'cls_sep' pattern because one or several special tokens "
  757. f"are not defined (cls_token_id={self.cls_token_id}; sep_token_id={self.sep_token_id})"
  758. "Set the required special tokens in tokenizer or update `tokenizer.special_tokens_pattern`"
  759. )
  760. if token_ids_1 is None:
  761. return [self.cls_token_id] + token_ids_0 + [self.sep_token_id]
  762. return [self.cls_token_id] + token_ids_0 + [self.sep_token_id] + token_ids_1 + [self.sep_token_id]
  763. elif self.special_tokens_pattern == "eos":
  764. # seq0 [EOS] or seq0 [EOS] seq1 [EOS]
  765. if self.eos_token_id is None:
  766. raise ValueError(
  767. "Cannot add special tokens following 'eos' pattern because eos token is not defined "
  768. f"(eos_token_id={self.eos_token_id})."
  769. "Set the required special tokens in tokenizer or update `tokenizer.special_tokens_pattern`"
  770. )
  771. if token_ids_1 is None:
  772. return token_ids_0 + [self.eos_token_id]
  773. return token_ids_0 + [self.eos_token_id] + token_ids_1 + [self.eos_token_id]
  774. elif self.special_tokens_pattern == "bos":
  775. # [BOS] seq0 or [BOS] seq0 [BOS] seq1
  776. if self.bos_token_id is None:
  777. raise ValueError(
  778. "Cannot add special tokens following 'bos' pattern because bos token is not defined "
  779. f"(bos_token_id={self.bos_token_id})."
  780. "Set the required special tokens in tokenizer or update `tokenizer.special_tokens_pattern`"
  781. )
  782. if token_ids_1 is None:
  783. return [self.bos_token_id] + token_ids_0
  784. return [self.bos_token_id] + token_ids_0 + [self.bos_token_id] + token_ids_1
  785. elif self.special_tokens_pattern == "bos_eos":
  786. # [BOS] seq0 [EOS] or [BOS] seq0 [EOS] seq1 [EOS]
  787. if self.bos_token_id is None and self.eos_token_id is None:
  788. raise ValueError(
  789. "Cannot add special tokens following 'bos_eos' pattern because one or several special tokens "
  790. f"are not defined (bos_token_id={self.bos_token_id}; eos_token_id={self.eos_token_id})"
  791. "Set the required special tokens in tokenizer or update `tokenizer.special_tokens_pattern`"
  792. )
  793. return token_ids_0 if token_ids_1 is None else token_ids_0 + token_ids_1
  794. if token_ids_1 is None:
  795. return [self.bos_token_id] + token_ids_0 + [self.eos_token_id]
  796. return [self.bos_token_id] + token_ids_0 + [self.eos_token_id] + token_ids_1 + [self.eos_token_id]
  797. elif self.special_tokens_pattern == "cls_double_sep":
  798. # [CLS] seq0 [SEP] or [CLS] seq0 [SEP] [SEP] seq1 [SEP]
  799. if self.cls_token_id is None and self.sep_token_id is None:
  800. raise ValueError(
  801. "Cannot add special tokens following 'cls_double_sep' pattern because one or several special tokens "
  802. f"are not defined (cls_token_id={self.cls_token_id}; sep_token_id={self.sep_token_id})"
  803. "Set the required special tokens in tokenizer or update `tokenizer.special_tokens_pattern`"
  804. )
  805. if token_ids_1 is None:
  806. return [self.cls_token_id] + token_ids_0 + [self.sep_token_id]
  807. return (
  808. [self.cls_token_id]
  809. + token_ids_0
  810. + [self.sep_token_id, self.sep_token_id]
  811. + token_ids_1
  812. + [self.sep_token_id]
  813. )
  814. elif self.special_tokens_pattern == "prefix_suffix":
  815. prefix_tokens = getattr(self, "prefix_tokens", [])
  816. suffix_tokens = getattr(self, "suffix_tokens", [])
  817. if token_ids_1 is None:
  818. return prefix_tokens + token_ids_0 + suffix_tokens
  819. return prefix_tokens + token_ids_0 + token_ids_1 + suffix_tokens
  820. else: # "none" or any other value
  821. # No special tokens
  822. if token_ids_1 is None:
  823. return token_ids_0
  824. return token_ids_0 + token_ids_1
  825. def get_special_tokens_mask(
  826. self, token_ids_0: list, token_ids_1: list | None = None, already_has_special_tokens: bool = False
  827. ) -> list[int]:
  828. """
  829. Retrieves sequence ids from a token list that has no special tokens added. This method is called when adding
  830. special tokens using the tokenizer `prepare_for_model` or `encode_plus` methods.
  831. This method dynamically builds the special tokens mask based on the tokenizer's `special_tokens_pattern`:
  832. - `"none"`: No special tokens (default, returns all 0s)
  833. - `"cls_sep"`: [CLS] seq0 [SEP] or [CLS] seq0 [SEP] seq1 [SEP]
  834. - `"eos"`: seq0 [EOS] or seq0 [EOS] seq1 [EOS]
  835. - `"bos"`: [BOS] seq0 or [BOS] seq0 [BOS] seq1
  836. - `"bos_eos"`: [BOS] seq0 [EOS] or [BOS] seq0 [EOS] seq1 [EOS]
  837. - `"cls_double_sep"`: [CLS] seq0 [SEP] or [CLS] seq0 [SEP] [SEP] seq1 [SEP]
  838. - `"prefix_suffix"`: `<prefix_tokens> seq0 [seq1] <suffix_tokens>`
  839. Args:
  840. token_ids_0 (`list[int]`):
  841. List of ids of the first sequence.
  842. token_ids_1 (`list[int]`, *optional*):
  843. List of ids of the second sequence.
  844. already_has_special_tokens (`bool`, *optional*, defaults to `False`):
  845. Whether or not the token list is already formatted with special tokens for the model.
  846. Returns:
  847. A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
  848. """
  849. if already_has_special_tokens:
  850. if token_ids_1 is not None:
  851. raise ValueError(
  852. "You should not supply a second sequence if the provided sequence of "
  853. "ids is already formatted with special tokens for the model."
  854. )
  855. return super().get_special_tokens_mask(
  856. token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
  857. )
  858. if self.special_tokens_pattern == "cls_sep":
  859. # [CLS] seq0 [SEP] or [CLS] seq0 [SEP] seq1 [SEP]
  860. if token_ids_1 is None:
  861. return [1] + ([0] * len(token_ids_0)) + [1]
  862. return [1] + ([0] * len(token_ids_0)) + [1] + ([0] * len(token_ids_1)) + [1]
  863. elif self.special_tokens_pattern == "eos":
  864. # seq0 [EOS] or seq0 [EOS] seq1 [EOS]
  865. if token_ids_1 is None:
  866. return ([0] * len(token_ids_0)) + [1]
  867. return ([0] * len(token_ids_0)) + [1] + ([0] * len(token_ids_1)) + [1]
  868. elif self.special_tokens_pattern == "bos":
  869. # [BOS] seq0 or [BOS] seq0 [BOS] seq1
  870. if token_ids_1 is None:
  871. return [1] + ([0] * len(token_ids_0))
  872. return [1] + ([0] * len(token_ids_0)) + [1] + ([0] * len(token_ids_1))
  873. elif self.special_tokens_pattern == "bos_eos":
  874. # [BOS] seq0 [EOS] or [BOS] seq0 [EOS] seq1 [EOS]
  875. if token_ids_1 is None:
  876. return [1] + ([0] * len(token_ids_0)) + [1]
  877. return [1] + ([0] * len(token_ids_0)) + [1] + ([0] * len(token_ids_1)) + [1]
  878. elif self.special_tokens_pattern == "cls_double_sep":
  879. # [CLS] seq0 [SEP] or [CLS] seq0 [SEP] [SEP] seq1 [SEP]
  880. if token_ids_1 is None:
  881. return [1] + ([0] * len(token_ids_0)) + [1]
  882. return [1] + ([0] * len(token_ids_0)) + [1, 1] + ([0] * len(token_ids_1)) + [1]
  883. elif self.special_tokens_pattern == "prefix_suffix":
  884. prefix_len = len(getattr(self, "prefix_tokens", []))
  885. suffix_len = len(getattr(self, "suffix_tokens", []))
  886. mask = [1] * prefix_len + ([0] * len(token_ids_0))
  887. if token_ids_1 is not None:
  888. mask += [0] * len(token_ids_1)
  889. mask += [1] * suffix_len
  890. return mask
  891. else:
  892. return [0] * ((len(token_ids_1) if token_ids_1 else 0) + len(token_ids_0))
  893. @overload
  894. def convert_ids_to_tokens(self, ids: int, skip_special_tokens: bool = False) -> str: ...
  895. @overload
  896. def convert_ids_to_tokens(self, ids: list[int], skip_special_tokens: bool = False) -> list[str]: ...
  897. def convert_ids_to_tokens(self, ids: int | list[int], skip_special_tokens: bool = False) -> str | list[str]:
  898. """
  899. Converts a single index or a sequence of indices in a token or a sequence of tokens, using the vocabulary and
  900. added tokens.
  901. Args:
  902. ids (`int` or `list[int]`):
  903. The token id (or token ids) to convert to tokens.
  904. skip_special_tokens (`bool`, *optional*, defaults to `False`):
  905. Whether or not to remove special tokens in the decoding.
  906. Returns:
  907. `str` or `list[str]`: The decoded token(s).
  908. """
  909. if isinstance(ids, int):
  910. return (
  911. self._added_tokens_decoder[ids].content
  912. if ids in self._added_tokens_decoder
  913. else self._convert_id_to_token(ids)
  914. )
  915. tokens = []
  916. for index in ids:
  917. index = int(index)
  918. if skip_special_tokens and index in self.all_special_ids:
  919. continue
  920. tokens.append(
  921. self._added_tokens_decoder[index].content
  922. if index in self._added_tokens_decoder
  923. else self._convert_id_to_token(index)
  924. )
  925. return tokens
  926. def _convert_id_to_token(self, index: int) -> str:
  927. raise NotImplementedError
  928. def convert_tokens_to_string(self, tokens: list[str]) -> str:
  929. return " ".join(tokens)
  930. def _decode(
  931. self,
  932. token_ids: int | list[int],
  933. skip_special_tokens: bool = False,
  934. clean_up_tokenization_spaces: bool | None = None,
  935. **kwargs,
  936. ) -> str:
  937. """Decode token ids to string."""
  938. filtered_tokens = self.convert_ids_to_tokens(token_ids, skip_special_tokens=skip_special_tokens)
  939. if isinstance(filtered_tokens, str):
  940. filtered_tokens = [filtered_tokens]
  941. text = self.convert_tokens_to_string(filtered_tokens)
  942. # Apply tokenizer-specific cleanup if available and requested
  943. clean_up_tokenization_spaces = (
  944. clean_up_tokenization_spaces
  945. if clean_up_tokenization_spaces is not None
  946. else self.clean_up_tokenization_spaces
  947. )
  948. if clean_up_tokenization_spaces:
  949. text = self.clean_up_tokenization(text)
  950. return text
  951. def prepare_for_model(
  952. self,
  953. ids: list[int],
  954. pair_ids: list[int] | None = None,
  955. add_special_tokens: bool = True,
  956. padding: bool | str | PaddingStrategy = False,
  957. truncation: bool | str | TruncationStrategy = False,
  958. max_length: int | None = None,
  959. stride: int = 0,
  960. pad_to_multiple_of: int | None = None,
  961. padding_side: str | None = None,
  962. return_tensors: str | TensorType | None = None,
  963. return_token_type_ids: bool | None = None,
  964. return_attention_mask: bool | None = None,
  965. return_overflowing_tokens: bool = False,
  966. return_special_tokens_mask: bool = False,
  967. return_length: bool = False,
  968. verbose: bool = True,
  969. prepend_batch_axis: bool = False,
  970. **kwargs,
  971. ) -> BatchEncoding:
  972. """
  973. Prepares a sequence of input ids so it can be used by the model. Adds special tokens, truncates, and pads.
  974. Args:
  975. ids: Tokenized input ids of the first sequence.
  976. pair_ids: Tokenized input ids of the second sequence (optional).
  977. """
  978. # Get padding/truncation strategies
  979. padding_strategy, truncation_strategy, max_length, _ = self._get_padding_truncation_strategies(
  980. padding=padding,
  981. truncation=truncation,
  982. max_length=max_length,
  983. pad_to_multiple_of=pad_to_multiple_of,
  984. verbose=verbose,
  985. **kwargs,
  986. )
  987. # Validation
  988. if (
  989. return_overflowing_tokens
  990. and truncation_strategy == TruncationStrategy.LONGEST_FIRST
  991. and pair_ids is not None
  992. ):
  993. raise ValueError(
  994. "Not possible to return overflowing tokens for pair of sequences with the "
  995. "`longest_first`. Please select another truncation strategy than `longest_first`, "
  996. "for instance `only_second` or `only_first`."
  997. )
  998. # Defaults
  999. if return_token_type_ids is None:
  1000. return_token_type_ids = "token_type_ids" in self.model_input_names
  1001. if return_attention_mask is None:
  1002. return_attention_mask = "attention_mask" in self.model_input_names
  1003. # Truncation
  1004. pair = pair_ids is not None
  1005. num_special = self.num_special_tokens_to_add(pair=pair) if add_special_tokens else 0
  1006. total_len = len(ids) + len(pair_ids or []) + num_special
  1007. overflowing_tokens = []
  1008. if truncation_strategy != TruncationStrategy.DO_NOT_TRUNCATE and max_length and total_len > max_length:
  1009. ids, pair_ids, overflowing_tokens = self.truncate_sequences(
  1010. ids,
  1011. pair_ids=pair_ids,
  1012. num_tokens_to_remove=total_len - max_length,
  1013. truncation_strategy=truncation_strategy,
  1014. stride=stride,
  1015. )
  1016. # Add special tokens
  1017. if add_special_tokens:
  1018. sequence = self.build_inputs_with_special_tokens(ids, pair_ids)
  1019. token_type_ids = self.create_token_type_ids_from_sequences(ids, pair_ids)
  1020. else:
  1021. sequence = ids + (pair_ids if pair_ids else [])
  1022. token_type_ids = [0] * len(sequence)
  1023. # Build output
  1024. encoded_inputs = {"input_ids": sequence}
  1025. if return_token_type_ids:
  1026. encoded_inputs["token_type_ids"] = token_type_ids
  1027. if return_special_tokens_mask:
  1028. encoded_inputs["special_tokens_mask"] = (
  1029. self.get_special_tokens_mask(ids, pair_ids) if add_special_tokens else [0] * len(sequence)
  1030. )
  1031. if return_overflowing_tokens and not return_tensors and overflowing_tokens:
  1032. encoded_inputs["overflowing_tokens"] = overflowing_tokens
  1033. encoded_inputs["num_truncated_tokens"] = total_len - max_length if max_length else 0
  1034. # Check sequence length and warn if needed
  1035. self._eventual_warn_about_too_long_sequence(encoded_inputs["input_ids"], max_length, verbose)
  1036. # Pad
  1037. if padding_strategy != PaddingStrategy.DO_NOT_PAD or return_attention_mask:
  1038. encoded_inputs = self.pad(
  1039. encoded_inputs,
  1040. max_length=max_length,
  1041. padding=padding_strategy.value,
  1042. pad_to_multiple_of=pad_to_multiple_of,
  1043. padding_side=padding_side,
  1044. return_attention_mask=return_attention_mask,
  1045. )
  1046. if return_length:
  1047. encoded_inputs["length"] = len(encoded_inputs["input_ids"])
  1048. return BatchEncoding(encoded_inputs, tensor_type=return_tensors, prepend_batch_axis=prepend_batch_axis)
  1049. def truncate_sequences(
  1050. self,
  1051. ids: list[int],
  1052. pair_ids: list[int] | None = None,
  1053. num_tokens_to_remove: int = 0,
  1054. truncation_strategy: str | TruncationStrategy = "longest_first",
  1055. stride: int = 0,
  1056. ) -> tuple[list[int], list[int], list[int]]:
  1057. """Truncates sequences according to the specified strategy."""
  1058. if num_tokens_to_remove <= 0:
  1059. return ids, pair_ids, []
  1060. if not isinstance(truncation_strategy, TruncationStrategy):
  1061. truncation_strategy = TruncationStrategy(truncation_strategy)
  1062. overflowing_tokens = []
  1063. # ONLY_FIRST or LONGEST_FIRST with single sequence
  1064. if truncation_strategy == TruncationStrategy.ONLY_FIRST or (
  1065. truncation_strategy == TruncationStrategy.LONGEST_FIRST and pair_ids is None
  1066. ):
  1067. window_len = min(len(ids), stride + num_tokens_to_remove)
  1068. if self.truncation_side == "left":
  1069. overflowing_tokens = ids[:window_len]
  1070. ids = ids[num_tokens_to_remove:]
  1071. else:
  1072. overflowing_tokens = ids[-window_len:]
  1073. ids = ids[:-num_tokens_to_remove]
  1074. # LONGEST_FIRST with pair
  1075. elif truncation_strategy == TruncationStrategy.LONGEST_FIRST:
  1076. logger.warning(
  1077. "Be aware, overflowing tokens are not returned for the setting you have chosen,"
  1078. f" i.e. sequence pairs with the '{TruncationStrategy.LONGEST_FIRST.value}' "
  1079. "truncation strategy. So the returned list will always be empty even if some "
  1080. "tokens have been removed."
  1081. )
  1082. len_ids, len_pair = len(ids), len(pair_ids) if pair_ids else 0
  1083. first_remove = min(abs(len_pair - len_ids), num_tokens_to_remove)
  1084. second_remove = num_tokens_to_remove - first_remove
  1085. if len_ids > len_pair:
  1086. ids_to_move = first_remove + second_remove // 2
  1087. pair_ids_to_move = second_remove - second_remove // 2
  1088. else:
  1089. ids_to_move = second_remove // 2
  1090. pair_ids_to_move = first_remove + second_remove - (second_remove // 2)
  1091. if self.truncation_side == "right":
  1092. ids = ids[:-ids_to_move] if ids_to_move > 0 else ids
  1093. pair_ids = pair_ids[:-pair_ids_to_move] if pair_ids and pair_ids_to_move > 0 else pair_ids
  1094. else:
  1095. ids = ids[ids_to_move:]
  1096. pair_ids = pair_ids[pair_ids_to_move:] if pair_ids else None
  1097. # ONLY_SECOND
  1098. elif truncation_strategy == TruncationStrategy.ONLY_SECOND and pair_ids:
  1099. window_len = min(len(pair_ids), stride + num_tokens_to_remove)
  1100. if self.truncation_side == "right":
  1101. overflowing_tokens = pair_ids[-window_len:]
  1102. pair_ids = pair_ids[:-num_tokens_to_remove]
  1103. else:
  1104. overflowing_tokens = pair_ids[:window_len]
  1105. pair_ids = pair_ids[num_tokens_to_remove:]
  1106. return ids, pair_ids, overflowing_tokens
  1107. def create_token_type_ids_from_sequences(
  1108. self, token_ids_0: list[int], token_ids_1: list[int] | None = None
  1109. ) -> list[int]:
  1110. """
  1111. Create a mask from the two sequences passed to be used in a sequence-pair classification task.
  1112. This method dynamically builds the token type IDs based on the tokenizer's configuration attributes:
  1113. - `token_type_ids_pattern`: Pattern to use ("all_zeros" or "bert_style")
  1114. - `token_type_ids_include_special_tokens`: Whether to account for special tokens in length calculation
  1115. Args:
  1116. token_ids_0 (`list[int]`):
  1117. List of IDs.
  1118. token_ids_1 (`list[int]`, *optional*):
  1119. Optional second list of IDs for sequence pairs.
  1120. Returns:
  1121. `list[int]`: Token type IDs according to the configured pattern.
  1122. Examples:
  1123. ```python
  1124. # All zeros pattern (default, used by RoBERTa, BART, etc.)
  1125. tokenizer.token_type_ids_pattern = "all_zeros"
  1126. # Returns: [0, 0, 0, ...] for both sequences
  1127. # BERT-style pattern (first sequence gets 0s, second gets 1s)
  1128. tokenizer.token_type_ids_pattern = "bert_style"
  1129. # Returns: [0, 0, 0, ..., 1, 1, 1, ...] for sequence pairs
  1130. ```
  1131. """
  1132. # Calculate lengths - account for special tokens if configured
  1133. if self.token_type_ids_include_special_tokens:
  1134. # Build the full sequence to get accurate length
  1135. if token_ids_1 is None:
  1136. sequence = self.build_inputs_with_special_tokens(token_ids_0)
  1137. seq0_len = len(sequence)
  1138. seq1_len = 0
  1139. else:
  1140. full_sequence = self.build_inputs_with_special_tokens(token_ids_0, token_ids_1)
  1141. # Approximate split - this works for most tokenizers
  1142. # For more complex cases, subclasses should still override
  1143. seq0_with_special = self.build_inputs_with_special_tokens(token_ids_0)
  1144. seq0_len = len(seq0_with_special)
  1145. seq1_len = len(full_sequence) - seq0_len
  1146. else:
  1147. # Use raw token lengths
  1148. seq0_len = len(token_ids_0)
  1149. seq1_len = len(token_ids_1) if token_ids_1 is not None else 0
  1150. # Build token type IDs based on pattern
  1151. if self.special_tokens_pattern == "prefix_suffix":
  1152. total_len = len(getattr(self, "prefix_tokens", [])) + len(token_ids_0)
  1153. if token_ids_1 is not None:
  1154. total_len += len(token_ids_1)
  1155. total_len += len(getattr(self, "suffix_tokens", []))
  1156. return [0] * total_len
  1157. if self.token_type_ids_pattern == "bert_style" and token_ids_1 is not None:
  1158. # BERT-style: first sequence gets 0s, second sequence gets 1s
  1159. return [0] * seq0_len + [1] * seq1_len
  1160. else:
  1161. # All zeros pattern (default): everything gets 0s
  1162. return [0] * (seq0_len + seq1_len)
  1163. def save_vocabulary(self, save_directory: str, filename_prefix: str | None = None) -> tuple[str, ...]:
  1164. """
  1165. Default implementation for common vocabulary saving patterns.
  1166. Saves self.encoder/self.vocab as JSON, optionally with self.bpe_ranks as merges.
  1167. Returns empty tuple if no vocabulary exists.
  1168. Override this method if your tokenizer needs custom saving logic (e.g., SentencePiece models,
  1169. multiple vocabulary files, or special file formats).
  1170. Args:
  1171. save_directory (`str`):
  1172. The directory in which to save the vocabulary.
  1173. filename_prefix (`str`, *optional*):
  1174. An optional prefix to add to the named of the saved files.
  1175. Returns:
  1176. `tuple[str, ...]`: Paths to the files saved, or empty tuple if no files saved.
  1177. """
  1178. import json
  1179. import os
  1180. vocab_attr = getattr(self, "encoder", None) or getattr(self, "vocab", None)
  1181. if vocab_attr is None:
  1182. return ()
  1183. if not os.path.isdir(save_directory):
  1184. logger.error(f"Vocabulary path ({save_directory}) should be a directory")
  1185. return ()
  1186. vocab_files_names = getattr(self, "vocab_files_names", {})
  1187. prefix = f"{filename_prefix}-" if filename_prefix else ""
  1188. # Save vocabulary
  1189. vocab_file = os.path.join(save_directory, prefix + vocab_files_names.get("vocab_file", "vocab.json"))
  1190. with open(vocab_file, "w", encoding="utf-8") as f:
  1191. f.write(json.dumps(vocab_attr, indent=2, sort_keys=True, ensure_ascii=False) + "\n")
  1192. # Save BPE merges if present
  1193. bpe_ranks = getattr(self, "bpe_ranks", None)
  1194. if bpe_ranks is None:
  1195. return (vocab_file,)
  1196. merge_file = os.path.join(save_directory, prefix + vocab_files_names.get("merges_file", "merges.txt"))
  1197. with open(merge_file, "w", encoding="utf-8") as writer:
  1198. if getattr(self, "add_bpe_version_header", False):
  1199. writer.write("#version: 0.2\n")
  1200. index = 0
  1201. for bpe_tokens, token_index in sorted(bpe_ranks.items(), key=lambda kv: kv[1]):
  1202. if index != token_index:
  1203. logger.warning(
  1204. f"Saving vocabulary to {merge_file}: BPE merge indices are not consecutive."
  1205. " Please check that the tokenizer is not corrupted!"
  1206. )
  1207. index = token_index
  1208. writer.write(" ".join(bpe_tokens) + "\n")
  1209. index += 1
  1210. return (vocab_file, merge_file)
  1211. # Backward compatibility alias
  1212. PreTrainedTokenizer = PythonBackend