tokenization_udop.py 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031
  1. # Copyright 2024 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. """Tokenization classes for UDOP model."""
  15. from tokenizers import Tokenizer, decoders, pre_tokenizers, processors
  16. from tokenizers.models import Unigram
  17. from ...tokenization_utils_base import (
  18. BatchEncoding,
  19. EncodedInput,
  20. PreTokenizedInput,
  21. TextInput,
  22. TextInputPair,
  23. TruncationStrategy,
  24. )
  25. from ...tokenization_utils_tokenizers import TokenizersBackend
  26. from ...utils import PaddingStrategy, TensorType, add_end_docstrings, logging
  27. VOCAB_FILES_NAMES = {"vocab_file": "spiece.model", "tokenizer_file": "tokenizer.json"}
  28. logger = logging.get_logger(__name__)
  29. UDOP_ENCODE_KWARGS_DOCSTRING = r"""
  30. add_special_tokens (`bool`, *optional*, defaults to `True`):
  31. Whether or not to encode the sequences with the special tokens relative to their model.
  32. padding (`bool`, `str` or [`~file_utils.PaddingStrategy`], *optional*, defaults to `False`):
  33. Activates and controls padding. Accepts the following values:
  34. - `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single
  35. sequence if provided).
  36. - `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum
  37. acceptable input length for the model if that argument is not provided.
  38. - `False` or `'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of different
  39. lengths).
  40. truncation (`bool`, `str` or [`~tokenization_utils_base.TruncationStrategy`], *optional*, defaults to `False`):
  41. Activates and controls truncation. Accepts the following values:
  42. - `True` or `'longest_first'`: Truncate to a maximum length specified with the argument `max_length` or
  43. to the maximum acceptable input length for the model if that argument is not provided. This will
  44. truncate token by token, removing a token from the longest sequence in the pair if a pair of
  45. sequences (or a batch of pairs) is provided.
  46. - `'only_first'`: Truncate to a maximum length specified with the argument `max_length` or to the
  47. maximum acceptable input length for the model if that argument is not provided. This will only
  48. truncate the first sequence of a pair if a pair of sequences (or a batch of pairs) is provided.
  49. - `'only_second'`: Truncate to a maximum length specified with the argument `max_length` or to the
  50. maximum acceptable input length for the model if that argument is not provided. This will only
  51. truncate the second sequence of a pair if a pair of sequences (or a batch of pairs) is provided.
  52. - `False` or `'do_not_truncate'` (default): No truncation (i.e., can output batch with sequence lengths
  53. greater than the model maximum admissible input size).
  54. max_length (`int`, *optional*):
  55. Controls the maximum length to use by one of the truncation/padding parameters.
  56. If left unset or set to `None`, this will use the predefined model maximum length if a maximum length
  57. is required by one of the truncation/padding parameters. If the model has no specific maximum input
  58. length (like XLNet) truncation/padding to a maximum length will be deactivated.
  59. stride (`int`, *optional*, defaults to 0):
  60. If set to a number along with `max_length`, the overflowing tokens returned when
  61. `return_overflowing_tokens=True` will contain some tokens from the end of the truncated sequence
  62. returned to provide some overlap between truncated and overflowing sequences. The value of this
  63. argument defines the number of overlapping tokens.
  64. pad_to_multiple_of (`int`, *optional*):
  65. If set will pad the sequence to a multiple of the provided value. This is especially useful to enable
  66. the use of Tensor Cores on NVIDIA hardware with compute capability `>= 7.5` (Volta).
  67. return_tensors (`str` or [`~file_utils.TensorType`], *optional*):
  68. If set, will return tensors instead of list of python integers. Acceptable values are:
  69. - `'pt'`: Return PyTorch `torch.Tensor` objects.
  70. - `'np'`: Return Numpy `np.ndarray` objects.
  71. return_token_type_ids (`bool`, *optional*):
  72. Whether to return token type IDs. If left to the default, will return the token type IDs according to
  73. the specific tokenizer's default, defined by the `return_outputs` attribute.
  74. [What are token type IDs?](../glossary#token-type-ids)
  75. return_attention_mask (`bool`, *optional*):
  76. Whether to return the attention mask. If left to the default, will return the attention mask according
  77. to the specific tokenizer's default, defined by the `return_outputs` attribute.
  78. [What are attention masks?](../glossary#attention-mask)
  79. return_overflowing_tokens (`bool`, *optional*, defaults to `False`):
  80. Whether or not to return overflowing token sequences. If a pair of sequences of input ids (or a batch
  81. of pairs) is provided with `truncation_strategy = longest_first` or `True`, an error is raised instead
  82. of returning overflowing tokens.
  83. return_special_tokens_mask (`bool`, *optional*, defaults to `False`):
  84. Whether or not to return special tokens mask information.
  85. return_offsets_mapping (`bool`, *optional*, defaults to `False`):
  86. Whether or not to return `(char_start, char_end)` for each token.
  87. This is only available on fast tokenizers inheriting from [`PreTrainedTokenizerFast`], if using
  88. Python's tokenizer, this method will raise `NotImplementedError`.
  89. return_length (`bool`, *optional*, defaults to `False`):
  90. Whether or not to return the lengths of the encoded inputs.
  91. verbose (`bool`, *optional*, defaults to `True`):
  92. Whether or not to print more information and warnings.
  93. **kwargs: passed to the `self.tokenize()` method
  94. Return:
  95. [`BatchEncoding`]: A [`BatchEncoding`] with the following fields:
  96. - **input_ids** -- List of token ids to be fed to a model.
  97. [What are input IDs?](../glossary#input-ids)
  98. - **bbox** -- List of bounding boxes to be fed to a model.
  99. - **token_type_ids** -- List of token type ids to be fed to a model (when `return_token_type_ids=True` or
  100. if *"token_type_ids"* is in `self.model_input_names`).
  101. [What are token type IDs?](../glossary#token-type-ids)
  102. - **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
  103. `return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names`).
  104. [What are attention masks?](../glossary#attention-mask)
  105. - **labels** -- List of labels to be fed to a model. (when `word_labels` is specified).
  106. - **overflowing_tokens** -- List of overflowing tokens sequences (when a `max_length` is specified and
  107. `return_overflowing_tokens=True`).
  108. - **num_truncated_tokens** -- Number of tokens truncated (when a `max_length` is specified and
  109. `return_overflowing_tokens=True`).
  110. - **special_tokens_mask** -- List of 0s and 1s, with 1 specifying added special tokens and 0 specifying
  111. regular sequence tokens (when `add_special_tokens=True` and `return_special_tokens_mask=True`).
  112. - **length** -- The length of the inputs (when `return_length=True`).
  113. """
  114. class UdopTokenizer(TokenizersBackend):
  115. """
  116. Construct a "fast" UDOP tokenizer (backed by HuggingFace's *tokenizers* library). Adapted from
  117. [`LayoutXLMTokenizer`] and [`T5Tokenizer`]. Based on
  118. [BPE](https://huggingface.co/docs/tokenizers/python/latest/components.html?highlight=BPE#models).
  119. This tokenizer inherits from [`TokenizersBackend`] which contains most of the main methods. Users should
  120. refer to this superclass for more information regarding those methods.
  121. Args:
  122. eos_token (`str`, *optional*, defaults to `"</s>"`):
  123. The end of sequence token.
  124. <Tip>
  125. When building a sequence using special tokens, this is not the token that is used for the end of sequence.
  126. The token used is the `sep_token`.
  127. </Tip>
  128. sep_token (`str`, *optional*, defaults to `"</s>"`):
  129. The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
  130. sequence classification or for a text and a question for question answering. It is also used as the last
  131. token of a sequence built with special tokens.
  132. unk_token (`str`, *optional*, defaults to `"<unk>"`):
  133. The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
  134. token instead.
  135. pad_token (`str`, *optional*, defaults to `"<pad>"`):
  136. The token used for padding, for example when batching sequences of different lengths.
  137. sep_token_box (`list[int]`, *optional*, defaults to `[1000, 1000, 1000, 1000]`):
  138. The bounding box to use for the special [SEP] token.
  139. pad_token_box (`list[int]`, *optional*, defaults to `[0, 0, 0, 0]`):
  140. The bounding box to use for the special [PAD] token.
  141. pad_token_label (`int`, *optional*, defaults to -100):
  142. The label to use for padding tokens. Defaults to -100, which is the `ignore_index` of PyTorch's
  143. CrossEntropyLoss.
  144. only_label_first_subword (`bool`, *optional*, defaults to `True`):
  145. Whether or not to only label the first subword, in case word labels are provided.
  146. extra_special_tokens (`list[str]`, *optional*, defaults to `["<s>NOTUSED", "</s>NOTUSED"]`):
  147. Extra special tokens used by the tokenizer.
  148. """
  149. vocab_files_names = VOCAB_FILES_NAMES
  150. model_input_names = ["input_ids", "attention_mask"]
  151. model = Unigram
  152. def __init__(
  153. self,
  154. vocab: str | list[tuple[str, float]] | None = None,
  155. eos_token="</s>",
  156. sep_token="</s>",
  157. unk_token="<unk>",
  158. pad_token="<pad>",
  159. sep_token_box=[1000, 1000, 1000, 1000],
  160. pad_token_box=[0, 0, 0, 0],
  161. pad_token_label=-100,
  162. only_label_first_subword=True,
  163. extra_special_tokens=None,
  164. **kwargs,
  165. ):
  166. if "additional_special_tokens" in kwargs and "extra_special_tokens" not in kwargs:
  167. kwargs["extra_special_tokens"] = kwargs.pop("additional_special_tokens")
  168. if extra_special_tokens is not None:
  169. kwargs["extra_special_tokens"] = extra_special_tokens
  170. if vocab is None:
  171. vocab = [(str(pad_token), 0.0), (str(eos_token), 0.0), (str(unk_token), 0.0), ("▁", -2.0)]
  172. unk_id = 2
  173. for idx, (token, _) in enumerate(vocab):
  174. if token == str(unk_token):
  175. unk_id = idx
  176. break
  177. self._tokenizer = Tokenizer(
  178. Unigram(
  179. vocab,
  180. unk_id=unk_id,
  181. byte_fallback=False,
  182. )
  183. )
  184. self._tokenizer.normalizer = None
  185. self._tokenizer.pre_tokenizer = pre_tokenizers.Sequence(
  186. [
  187. pre_tokenizers.WhitespaceSplit(),
  188. pre_tokenizers.Metaspace(replacement="▁", prepend_scheme="always", split=True),
  189. ]
  190. )
  191. self._tokenizer.decoder = decoders.Metaspace(replacement="▁", prepend_scheme="always", split=True)
  192. super().__init__(
  193. eos_token=eos_token,
  194. sep_token=sep_token,
  195. unk_token=unk_token,
  196. pad_token=pad_token,
  197. sep_token_box=sep_token_box,
  198. pad_token_box=pad_token_box,
  199. pad_token_label=pad_token_label,
  200. only_label_first_subword=only_label_first_subword,
  201. **kwargs,
  202. )
  203. self._tokenizer.post_processor = processors.TemplateProcessing(
  204. single=["$A", "</s>"],
  205. pair=["$A", "</s>", "$B", "</s>"],
  206. special_tokens=[
  207. ("</s>", self.eos_token_id),
  208. ],
  209. )
  210. self.sep_token_box = sep_token_box
  211. self.pad_token_box = pad_token_box
  212. self.pad_token_label = pad_token_label
  213. self.only_label_first_subword = only_label_first_subword
  214. self.init_kwargs["vocab"] = vocab
  215. self._tokenizer.encode_special_tokens = self.split_special_tokens
  216. @add_end_docstrings(UDOP_ENCODE_KWARGS_DOCSTRING)
  217. def __call__(
  218. self,
  219. text: TextInput | PreTokenizedInput | list[TextInput] | list[PreTokenizedInput] = None,
  220. text_pair: PreTokenizedInput | list[PreTokenizedInput] | None = None,
  221. boxes: list[list[int]] | list[list[list[int]]] | None = None,
  222. word_labels: list[int] | list[list[int]] | None = None,
  223. text_target: TextInput | PreTokenizedInput | list[TextInput] | list[PreTokenizedInput] = None,
  224. text_pair_target: TextInput | PreTokenizedInput | list[TextInput] | list[PreTokenizedInput] | None = None,
  225. **kwargs,
  226. ) -> BatchEncoding:
  227. if text is None and text_target is None:
  228. raise ValueError("You need to specify either `text` or `text_target`.")
  229. if text is not None:
  230. # The context manager will send the inputs as normal texts and not text_target, but we shouldn't change the
  231. # input mode in this case.
  232. if not self._in_target_context_manager and hasattr(self, "_switch_to_input_mode"):
  233. self._switch_to_input_mode()
  234. encodings = self.call_boxes(text=text, text_pair=text_pair, boxes=boxes, word_labels=word_labels, **kwargs)
  235. if text_target is not None:
  236. if hasattr(self, "_switch_to_target_mode"):
  237. self._switch_to_target_mode()
  238. target_encodings = self._encode_plus(
  239. text=text_target,
  240. text_pair=text_pair_target,
  241. **kwargs,
  242. )
  243. # Leave back tokenizer in input mode
  244. if hasattr(self, "_switch_to_input_mode"):
  245. self._switch_to_input_mode()
  246. if text_target is None:
  247. return encodings
  248. elif text is None:
  249. return target_encodings
  250. else:
  251. encodings["labels"] = target_encodings["input_ids"]
  252. return encodings
  253. @add_end_docstrings(UDOP_ENCODE_KWARGS_DOCSTRING)
  254. def call_boxes(
  255. self,
  256. text: TextInput | PreTokenizedInput | list[TextInput] | list[PreTokenizedInput],
  257. text_pair: PreTokenizedInput | list[PreTokenizedInput] | None = None,
  258. boxes: list[list[int]] | list[list[list[int]]] | None = None,
  259. word_labels: list[int] | list[list[int]] | None = None,
  260. add_special_tokens: bool = True,
  261. padding: bool | str | PaddingStrategy = False,
  262. truncation: bool | str | TruncationStrategy = None,
  263. max_length: int | None = None,
  264. stride: int = 0,
  265. pad_to_multiple_of: int | None = None,
  266. padding_side: str | None = None,
  267. return_tensors: str | TensorType | None = None,
  268. return_token_type_ids: bool | None = None,
  269. return_attention_mask: bool | None = None,
  270. return_overflowing_tokens: bool = False,
  271. return_special_tokens_mask: bool = False,
  272. return_offsets_mapping: bool = False,
  273. return_length: bool = False,
  274. verbose: bool = True,
  275. **kwargs,
  276. ) -> BatchEncoding:
  277. """
  278. Main method to tokenize and prepare for the model one or several sequence(s) or one or several pair(s) of
  279. sequences with word-level normalized bounding boxes and optional labels.
  280. Args:
  281. text (`str`, `list[str]`, `list[list[str]]`):
  282. The sequence or batch of sequences to be encoded. Each sequence can be a string, a list of strings
  283. (words of a single example or questions of a batch of examples) or a list of list of strings (batch of
  284. words).
  285. text_pair (`list[str]`, `list[list[str]]`):
  286. The sequence or batch of sequences to be encoded. Each sequence should be a list of strings
  287. (pretokenized string).
  288. boxes (`list[list[int]]`, `list[list[list[int]]]`):
  289. Word-level bounding boxes. Each bounding box should be normalized to be on a 0-1000 scale.
  290. word_labels (`list[int]`, `list[list[int]]`, *optional*):
  291. Word-level integer labels (for token classification tasks such as FUNSD, CORD).
  292. """
  293. # Input type checking for clearer error
  294. def _is_valid_text_input(t):
  295. if isinstance(t, str):
  296. # Strings are fine
  297. return True
  298. elif isinstance(t, (list, tuple)):
  299. # List are fine as long as they are...
  300. if len(t) == 0:
  301. # ... empty
  302. return True
  303. elif isinstance(t[0], str):
  304. # ... list of strings
  305. return True
  306. elif isinstance(t[0], (list, tuple)):
  307. # ... list with an empty list or with a list of strings
  308. return len(t[0]) == 0 or isinstance(t[0][0], str)
  309. else:
  310. return False
  311. else:
  312. return False
  313. if text_pair is not None:
  314. # in case text + text_pair are provided, text = questions, text_pair = words
  315. if not _is_valid_text_input(text):
  316. raise ValueError("text input must of type `str` (single example) or `list[str]` (batch of examples). ")
  317. if not isinstance(text_pair, (list, tuple)):
  318. raise ValueError(
  319. "words must of type `list[str]` (single pretokenized example), "
  320. "or `list[list[str]]` (batch of pretokenized examples)."
  321. )
  322. else:
  323. # in case only text is provided => must be words
  324. if not isinstance(text, (list, tuple)):
  325. raise ValueError(
  326. "Words must of type `list[str]` (single pretokenized example), "
  327. "or `list[list[str]]` (batch of pretokenized examples)."
  328. )
  329. if text_pair is not None:
  330. is_batched = isinstance(text, (list, tuple))
  331. else:
  332. is_batched = isinstance(text, (list, tuple)) and text and isinstance(text[0], (list, tuple))
  333. words = text if text_pair is None else text_pair
  334. if boxes is None:
  335. raise ValueError("You must provide corresponding bounding boxes")
  336. if is_batched:
  337. if len(words) != len(boxes):
  338. raise ValueError("You must provide words and boxes for an equal amount of examples")
  339. for words_example, boxes_example in zip(words, boxes):
  340. if len(words_example) != len(boxes_example):
  341. raise ValueError("You must provide as many words as there are bounding boxes")
  342. else:
  343. if len(words) != len(boxes):
  344. raise ValueError("You must provide as many words as there are bounding boxes")
  345. if is_batched:
  346. if text_pair is not None and len(text) != len(text_pair):
  347. raise ValueError(
  348. f"batch length of `text`: {len(text)} does not match batch length of `text_pair`:"
  349. f" {len(text_pair)}."
  350. )
  351. batch_text_or_text_pairs = list(zip(text, text_pair)) if text_pair is not None else text
  352. is_pair = bool(text_pair is not None)
  353. return self.batch_encode_plus_boxes(
  354. batch_text_or_text_pairs=batch_text_or_text_pairs,
  355. is_pair=is_pair,
  356. boxes=boxes,
  357. word_labels=word_labels,
  358. add_special_tokens=add_special_tokens,
  359. padding=padding,
  360. truncation=truncation,
  361. max_length=max_length,
  362. stride=stride,
  363. pad_to_multiple_of=pad_to_multiple_of,
  364. padding_side=padding_side,
  365. return_tensors=return_tensors,
  366. return_token_type_ids=return_token_type_ids,
  367. return_attention_mask=return_attention_mask,
  368. return_overflowing_tokens=return_overflowing_tokens,
  369. return_special_tokens_mask=return_special_tokens_mask,
  370. return_offsets_mapping=return_offsets_mapping,
  371. return_length=return_length,
  372. verbose=verbose,
  373. **kwargs,
  374. )
  375. else:
  376. return self.encode_plus_boxes(
  377. text=text,
  378. text_pair=text_pair,
  379. boxes=boxes,
  380. word_labels=word_labels,
  381. add_special_tokens=add_special_tokens,
  382. padding=padding,
  383. truncation=truncation,
  384. max_length=max_length,
  385. stride=stride,
  386. pad_to_multiple_of=pad_to_multiple_of,
  387. padding_side=padding_side,
  388. return_tensors=return_tensors,
  389. return_token_type_ids=return_token_type_ids,
  390. return_attention_mask=return_attention_mask,
  391. return_overflowing_tokens=return_overflowing_tokens,
  392. return_special_tokens_mask=return_special_tokens_mask,
  393. return_offsets_mapping=return_offsets_mapping,
  394. return_length=return_length,
  395. verbose=verbose,
  396. **kwargs,
  397. )
  398. def tokenize(self, text: str, pair: str | None = None, add_special_tokens: bool = False, **kwargs) -> list[str]:
  399. batched_input = [(text, pair)] if pair else [text]
  400. self._tokenizer.encode_special_tokens = kwargs.pop("split_special_tokens", self.split_special_tokens)
  401. encodings = self._tokenizer.encode_batch(
  402. batched_input, add_special_tokens=add_special_tokens, is_pretokenized=False, **kwargs
  403. )
  404. return encodings[0].tokens
  405. def batch_encode_plus_boxes(
  406. self,
  407. batch_text_or_text_pairs: list[TextInput] | list[TextInputPair] | list[PreTokenizedInput],
  408. is_pair: bool | None = None,
  409. boxes: list[list[list[int]]] | None = None,
  410. word_labels: list[list[int]] | None = None,
  411. add_special_tokens: bool = True,
  412. padding: bool | str | PaddingStrategy = False,
  413. truncation: bool | str | TruncationStrategy = None,
  414. max_length: int | None = None,
  415. stride: int = 0,
  416. is_split_into_words: bool = False,
  417. pad_to_multiple_of: int | None = None,
  418. padding_side: str | None = None,
  419. return_tensors: str | TensorType | None = None,
  420. return_token_type_ids: bool | None = None,
  421. return_attention_mask: bool | None = None,
  422. return_overflowing_tokens: bool = False,
  423. return_special_tokens_mask: bool = False,
  424. return_offsets_mapping: bool = False,
  425. return_length: bool = False,
  426. verbose: bool = True,
  427. **kwargs,
  428. ) -> BatchEncoding:
  429. """
  430. Tokenize and prepare for the model a list of sequences or a list of pairs of sequences.
  431. <Tip warning={true}>
  432. This method is deprecated, `__call__` should be used instead.
  433. </Tip>
  434. Args:
  435. batch_text_or_text_pairs (`list[str]`, `list[tuple[str, str]]`, `list[list[str]]`, `list[tuple[list[str], list[str]]]`, and for not-fast tokenizers, also `list[list[int]]`, `list[tuple[list[int], list[int]]]`):
  436. Batch of sequences or pair of sequences to be encoded. This can be a list of
  437. string/string-sequences/int-sequences or a list of pair of string/string-sequences/int-sequence (see
  438. details in `encode_plus`).
  439. """
  440. # Backward compatibility for 'truncation_strategy', 'pad_to_max_length'
  441. padding_strategy, truncation_strategy, max_length, kwargs = self._get_padding_truncation_strategies(
  442. padding=padding,
  443. truncation=truncation,
  444. max_length=max_length,
  445. pad_to_multiple_of=pad_to_multiple_of,
  446. verbose=verbose,
  447. **kwargs,
  448. )
  449. return self._batch_encode_plus_boxes(
  450. batch_text_or_text_pairs=batch_text_or_text_pairs,
  451. is_pair=is_pair,
  452. boxes=boxes,
  453. word_labels=word_labels,
  454. add_special_tokens=add_special_tokens,
  455. padding_strategy=padding_strategy,
  456. truncation_strategy=truncation_strategy,
  457. max_length=max_length,
  458. stride=stride,
  459. is_split_into_words=is_split_into_words,
  460. pad_to_multiple_of=pad_to_multiple_of,
  461. padding_side=padding_side,
  462. return_tensors=return_tensors,
  463. return_token_type_ids=return_token_type_ids,
  464. return_attention_mask=return_attention_mask,
  465. return_overflowing_tokens=return_overflowing_tokens,
  466. return_special_tokens_mask=return_special_tokens_mask,
  467. return_offsets_mapping=return_offsets_mapping,
  468. return_length=return_length,
  469. verbose=verbose,
  470. **kwargs,
  471. )
  472. def _batch_encode_plus_boxes(
  473. self,
  474. batch_text_or_text_pairs: list[TextInput] | list[TextInputPair] | list[PreTokenizedInput],
  475. is_pair: bool | None = None,
  476. boxes: list[list[list[int]]] | None = None,
  477. word_labels: list[list[int]] | None = None,
  478. add_special_tokens: bool = True,
  479. padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
  480. truncation_strategy: TruncationStrategy = TruncationStrategy.DO_NOT_TRUNCATE,
  481. max_length: int | None = None,
  482. stride: int = 0,
  483. pad_to_multiple_of: int | None = None,
  484. padding_side: str | None = None,
  485. return_tensors: str | None = None,
  486. return_token_type_ids: bool | None = None,
  487. return_attention_mask: bool | None = None,
  488. return_overflowing_tokens: bool = False,
  489. return_special_tokens_mask: bool = False,
  490. return_offsets_mapping: bool = False,
  491. return_length: bool = False,
  492. verbose: bool = True,
  493. **kwargs,
  494. ) -> BatchEncoding:
  495. if not isinstance(batch_text_or_text_pairs, list):
  496. raise TypeError(f"batch_text_or_text_pairs has to be a list (got {type(batch_text_or_text_pairs)})")
  497. # Set the truncation and padding strategy and restore the initial configuration
  498. self.set_truncation_and_padding(
  499. padding_strategy=padding_strategy,
  500. truncation_strategy=truncation_strategy,
  501. max_length=max_length,
  502. stride=stride,
  503. pad_to_multiple_of=pad_to_multiple_of,
  504. padding_side=padding_side,
  505. )
  506. if is_pair:
  507. batch_text_or_text_pairs = [(text.split(), text_pair) for text, text_pair in batch_text_or_text_pairs]
  508. encodings = self._tokenizer.encode_batch(
  509. batch_text_or_text_pairs,
  510. add_special_tokens=add_special_tokens,
  511. is_pretokenized=True, # we set this to True as LayoutLMv2 always expects pretokenized inputs
  512. )
  513. # Convert encoding to dict
  514. # `Tokens` has type: tuple[
  515. # list[dict[str, list[list[int]]]] or list[dict[str, 2D-Tensor]],
  516. # list[EncodingFast]
  517. # ]
  518. # with nested dimensions corresponding to batch, overflows, sequence length
  519. tokens_and_encodings = [
  520. self._convert_encoding(
  521. encoding=encoding,
  522. return_token_type_ids=return_token_type_ids,
  523. return_attention_mask=return_attention_mask,
  524. return_overflowing_tokens=return_overflowing_tokens,
  525. return_special_tokens_mask=return_special_tokens_mask,
  526. return_offsets_mapping=True
  527. if word_labels is not None
  528. else return_offsets_mapping, # we use offsets to create the labels
  529. return_length=return_length,
  530. verbose=verbose,
  531. )
  532. for encoding in encodings
  533. ]
  534. # Convert the output to have dict[list] from list[dict] and remove the additional overflows dimension
  535. # From (variable) shape (batch, overflows, sequence length) to ~ (batch * overflows, sequence length)
  536. # (we say ~ because the number of overflow varies with the example in the batch)
  537. #
  538. # To match each overflowing sample with the original sample in the batch
  539. # we add an overflow_to_sample_mapping array (see below)
  540. sanitized_tokens = {}
  541. for key in tokens_and_encodings[0][0]:
  542. stack = [e for item, _ in tokens_and_encodings for e in item[key]]
  543. sanitized_tokens[key] = stack
  544. sanitized_encodings = [e for _, item in tokens_and_encodings for e in item]
  545. # If returning overflowing tokens, we need to return a mapping
  546. # from the batch idx to the original sample
  547. if return_overflowing_tokens:
  548. overflow_to_sample_mapping = []
  549. for i, (toks, _) in enumerate(tokens_and_encodings):
  550. overflow_to_sample_mapping += [i] * len(toks["input_ids"])
  551. sanitized_tokens["overflow_to_sample_mapping"] = overflow_to_sample_mapping
  552. for input_ids in sanitized_tokens["input_ids"]:
  553. self._eventual_warn_about_too_long_sequence(input_ids, max_length, verbose)
  554. # create the token boxes
  555. token_boxes = []
  556. for batch_index in range(len(sanitized_tokens["input_ids"])):
  557. if return_overflowing_tokens:
  558. original_index = sanitized_tokens["overflow_to_sample_mapping"][batch_index]
  559. else:
  560. original_index = batch_index
  561. token_boxes_example = []
  562. for id, sequence_id, word_id in zip(
  563. sanitized_tokens["input_ids"][batch_index],
  564. sanitized_encodings[batch_index].sequence_ids,
  565. sanitized_encodings[batch_index].word_ids,
  566. ):
  567. if word_id is not None:
  568. if is_pair and sequence_id == 0:
  569. token_boxes_example.append(self.pad_token_box)
  570. else:
  571. token_boxes_example.append(boxes[original_index][word_id])
  572. else:
  573. if id == self.sep_token_id:
  574. token_boxes_example.append(self.sep_token_box)
  575. elif id == self.pad_token_id:
  576. token_boxes_example.append(self.pad_token_box)
  577. else:
  578. raise ValueError("Id not recognized")
  579. token_boxes.append(token_boxes_example)
  580. sanitized_tokens["bbox"] = token_boxes
  581. # optionally, create the labels
  582. if word_labels is not None:
  583. labels = []
  584. for batch_index in range(len(sanitized_tokens["input_ids"])):
  585. if return_overflowing_tokens:
  586. original_index = sanitized_tokens["overflow_to_sample_mapping"][batch_index]
  587. else:
  588. original_index = batch_index
  589. labels_example = []
  590. previous_token_empty = False
  591. for id, offset, word_id in zip(
  592. sanitized_tokens["input_ids"][batch_index],
  593. sanitized_tokens["offset_mapping"][batch_index],
  594. sanitized_encodings[batch_index].word_ids,
  595. ):
  596. if word_id is not None:
  597. if self.only_label_first_subword:
  598. if offset[0] == 0 and not previous_token_empty:
  599. # Use the real label id for the first token of the word, and padding ids for the remaining tokens
  600. labels_example.append(word_labels[original_index][word_id])
  601. else:
  602. labels_example.append(self.pad_token_label)
  603. else:
  604. labels_example.append(word_labels[original_index][word_id])
  605. if self.decode(id) == "":
  606. previous_token_empty = True
  607. else:
  608. previous_token_empty = False
  609. else:
  610. labels_example.append(self.pad_token_label)
  611. labels.append(labels_example)
  612. sanitized_tokens["labels"] = labels
  613. # finally, remove offsets if the user didn't want them
  614. if not return_offsets_mapping:
  615. del sanitized_tokens["offset_mapping"]
  616. return BatchEncoding(sanitized_tokens, sanitized_encodings, tensor_type=return_tensors)
  617. def _encode_plus_boxes(
  618. self,
  619. text: TextInput | PreTokenizedInput,
  620. text_pair: PreTokenizedInput | None = None,
  621. boxes: list[list[int]] | None = None,
  622. word_labels: list[int] | None = None,
  623. add_special_tokens: bool = True,
  624. padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
  625. truncation_strategy: TruncationStrategy = TruncationStrategy.DO_NOT_TRUNCATE,
  626. max_length: int | None = None,
  627. stride: int = 0,
  628. pad_to_multiple_of: int | None = None,
  629. padding_side: str | None = None,
  630. return_tensors: bool | None = None,
  631. return_token_type_ids: bool | None = None,
  632. return_attention_mask: bool | None = None,
  633. return_overflowing_tokens: bool = False,
  634. return_special_tokens_mask: bool = False,
  635. return_offsets_mapping: bool = False,
  636. return_length: bool = False,
  637. verbose: bool = True,
  638. **kwargs,
  639. ) -> BatchEncoding:
  640. # make it a batched input
  641. # 2 options:
  642. # 1) only text, in case text must be a list of str
  643. # 2) text + text_pair, in which case text = str and text_pair a list of str
  644. batched_input = [(text, text_pair)] if text_pair else [text]
  645. batched_boxes = [boxes]
  646. batched_word_labels = [word_labels] if word_labels is not None else None
  647. batched_output = self._batch_encode_plus_boxes(
  648. batched_input,
  649. is_pair=bool(text_pair is not None),
  650. boxes=batched_boxes,
  651. word_labels=batched_word_labels,
  652. add_special_tokens=add_special_tokens,
  653. padding_strategy=padding_strategy,
  654. truncation_strategy=truncation_strategy,
  655. max_length=max_length,
  656. stride=stride,
  657. pad_to_multiple_of=pad_to_multiple_of,
  658. padding_side=padding_side,
  659. return_tensors=return_tensors,
  660. return_token_type_ids=return_token_type_ids,
  661. return_attention_mask=return_attention_mask,
  662. return_overflowing_tokens=return_overflowing_tokens,
  663. return_special_tokens_mask=return_special_tokens_mask,
  664. return_offsets_mapping=return_offsets_mapping,
  665. return_length=return_length,
  666. verbose=verbose,
  667. **kwargs,
  668. )
  669. # Return tensor is None, then we can remove the leading batch axis
  670. # Overflowing tokens are returned as a batch of output so we keep them in this case
  671. if return_tensors is None and not return_overflowing_tokens:
  672. batched_output = BatchEncoding(
  673. {
  674. key: value[0] if len(value) > 0 and isinstance(value[0], list) else value
  675. for key, value in batched_output.items()
  676. },
  677. batched_output.encodings,
  678. )
  679. self._eventual_warn_about_too_long_sequence(batched_output["input_ids"], max_length, verbose)
  680. return batched_output
  681. def encode_boxes(
  682. self,
  683. text: TextInput | PreTokenizedInput | EncodedInput,
  684. text_pair: TextInput | PreTokenizedInput | EncodedInput | None = None,
  685. boxes: list[list[int]] | None = None,
  686. word_labels: list[list[int]] | None = None,
  687. add_special_tokens: bool = True,
  688. padding: bool | str | PaddingStrategy = False,
  689. truncation: bool | str | TruncationStrategy = None,
  690. max_length: int | None = None,
  691. stride: int = 0,
  692. return_tensors: str | TensorType | None = None,
  693. **kwargs,
  694. ) -> list[int]:
  695. """
  696. Args:
  697. Converts a string to a sequence of ids (integer), using the tokenizer and vocabulary. Same as doing
  698. `self.convert_tokens_to_ids(self.tokenize(text))`.
  699. text (`str`, `list[str]` or `list[int]`):
  700. The first sequence to be encoded. This can be a string, a list of strings (tokenized string using the
  701. `tokenize` method) or a list of integers (tokenized string ids using the `convert_tokens_to_ids`
  702. method).
  703. text_pair (`str`, `list[str]` or `list[int]`, *optional*):
  704. Optional second sequence to be encoded. This can be a string, a list of strings (tokenized string using
  705. the `tokenize` method) or a list of integers (tokenized string ids using the `convert_tokens_to_ids`
  706. method).
  707. """
  708. encoded_inputs = self.encode_plus_boxes(
  709. text,
  710. text_pair=text_pair,
  711. boxes=boxes,
  712. word_labels=word_labels,
  713. add_special_tokens=add_special_tokens,
  714. padding=padding,
  715. truncation=truncation,
  716. max_length=max_length,
  717. stride=stride,
  718. return_tensors=return_tensors,
  719. **kwargs,
  720. )
  721. return encoded_inputs["input_ids"]
  722. def encode_plus_boxes(
  723. self,
  724. text: TextInput | PreTokenizedInput,
  725. text_pair: PreTokenizedInput | None = None,
  726. boxes: list[list[int]] | None = None,
  727. word_labels: list[list[int]] | None = None,
  728. add_special_tokens: bool = True,
  729. padding: bool | str | PaddingStrategy = False,
  730. truncation: bool | str | TruncationStrategy = None,
  731. max_length: int | None = None,
  732. stride: int = 0,
  733. is_split_into_words: bool = False,
  734. pad_to_multiple_of: int | None = None,
  735. padding_side: str | None = None,
  736. return_tensors: str | TensorType | None = None,
  737. return_token_type_ids: bool | None = None,
  738. return_attention_mask: bool | None = None,
  739. return_overflowing_tokens: bool = False,
  740. return_special_tokens_mask: bool = False,
  741. return_offsets_mapping: bool = False,
  742. return_length: bool = False,
  743. verbose: bool = True,
  744. **kwargs,
  745. ) -> BatchEncoding:
  746. """
  747. Tokenize and prepare for the model a sequence or a pair of sequences.
  748. <Tip warning={true}>
  749. This method is deprecated, `__call__` should be used instead.
  750. </Tip>
  751. Args:
  752. text (`str`, `list[str]` or (for non-fast tokenizers) `list[int]`):
  753. The first sequence to be encoded. This can be a string, a list of strings (tokenized string using the
  754. `tokenize` method) or a list of integers (tokenized string ids using the `convert_tokens_to_ids`
  755. method).
  756. text_pair (`str`, `list[str]` or `list[int]`, *optional*):
  757. Optional second sequence to be encoded. This can be a string, a list of strings (tokenized string using
  758. the `tokenize` method) or a list of integers (tokenized string ids using the `convert_tokens_to_ids`
  759. method).
  760. """
  761. # Backward compatibility for 'truncation_strategy', 'pad_to_max_length'
  762. padding_strategy, truncation_strategy, max_length, kwargs = self._get_padding_truncation_strategies(
  763. padding=padding,
  764. truncation=truncation,
  765. max_length=max_length,
  766. pad_to_multiple_of=pad_to_multiple_of,
  767. verbose=verbose,
  768. **kwargs,
  769. )
  770. return self._encode_plus_boxes(
  771. text=text,
  772. text_pair=text_pair,
  773. boxes=boxes,
  774. word_labels=word_labels,
  775. add_special_tokens=add_special_tokens,
  776. padding_strategy=padding_strategy,
  777. truncation_strategy=truncation_strategy,
  778. max_length=max_length,
  779. stride=stride,
  780. is_split_into_words=is_split_into_words,
  781. pad_to_multiple_of=pad_to_multiple_of,
  782. padding_side=padding_side,
  783. return_tensors=return_tensors,
  784. return_token_type_ids=return_token_type_ids,
  785. return_attention_mask=return_attention_mask,
  786. return_overflowing_tokens=return_overflowing_tokens,
  787. return_special_tokens_mask=return_special_tokens_mask,
  788. return_offsets_mapping=return_offsets_mapping,
  789. return_length=return_length,
  790. verbose=verbose,
  791. **kwargs,
  792. )
  793. def _pad(
  794. self,
  795. encoded_inputs: dict[str, EncodedInput] | BatchEncoding,
  796. max_length: int | None = None,
  797. padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
  798. pad_to_multiple_of: int | None = None,
  799. padding_side: str | None = None,
  800. return_attention_mask: bool | None = None,
  801. ) -> dict:
  802. """
  803. Pad encoded inputs (on left/right and up to predefined length or max length in the batch)
  804. Args:
  805. encoded_inputs:
  806. Dictionary of tokenized inputs (`list[int]`) or batch of tokenized inputs (`list[list[int]]`).
  807. max_length: maximum length of the returned list and optionally padding length (see below).
  808. Will truncate by taking into account the special tokens.
  809. padding_strategy: PaddingStrategy to use for padding.
  810. - PaddingStrategy.LONGEST Pad to the longest sequence in the batch
  811. - PaddingStrategy.MAX_LENGTH: Pad to the max length (default)
  812. - PaddingStrategy.DO_NOT_PAD: Do not pad
  813. The tokenizer padding sides are defined in self.padding_side:
  814. - 'left': pads on the left of the sequences
  815. - 'right': pads on the right of the sequences
  816. pad_to_multiple_of: (optional) Integer if set will pad the sequence to a multiple of the provided value.
  817. This is especially useful to enable the use of Tensor Core on NVIDIA hardware with compute capability
  818. `>= 7.5` (Volta).
  819. padding_side (`str`, *optional*):
  820. The side on which the model should have padding applied. Should be selected between ['right', 'left'].
  821. Default value is picked from the class attribute of the same name.
  822. return_attention_mask:
  823. (optional) Set to False to avoid returning attention mask (default: set to model specifics)
  824. """
  825. # Load from model defaults
  826. if return_attention_mask is None:
  827. return_attention_mask = "attention_mask" in self.model_input_names
  828. required_input = encoded_inputs[self.model_input_names[0]]
  829. if padding_strategy == PaddingStrategy.LONGEST:
  830. max_length = len(required_input)
  831. if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0):
  832. max_length = ((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of
  833. needs_to_be_padded = padding_strategy != PaddingStrategy.DO_NOT_PAD and len(required_input) != max_length
  834. # Initialize attention mask if not present.
  835. if return_attention_mask and "attention_mask" not in encoded_inputs:
  836. encoded_inputs["attention_mask"] = [1] * len(required_input)
  837. if needs_to_be_padded:
  838. difference = max_length - len(required_input)
  839. padding_side = padding_side if padding_side is not None else self.padding_side
  840. if padding_side == "right":
  841. if return_attention_mask:
  842. encoded_inputs["attention_mask"] = encoded_inputs["attention_mask"] + [0] * difference
  843. if "token_type_ids" in encoded_inputs:
  844. encoded_inputs["token_type_ids"] = (
  845. encoded_inputs["token_type_ids"] + [self.pad_token_type_id] * difference
  846. )
  847. if "bbox" in encoded_inputs:
  848. encoded_inputs["bbox"] = encoded_inputs["bbox"] + [self.pad_token_box] * difference
  849. if "labels" in encoded_inputs:
  850. encoded_inputs["labels"] = encoded_inputs["labels"] + [self.pad_token_label] * difference
  851. if "special_tokens_mask" in encoded_inputs:
  852. encoded_inputs["special_tokens_mask"] = encoded_inputs["special_tokens_mask"] + [1] * difference
  853. encoded_inputs[self.model_input_names[0]] = required_input + [self.pad_token_id] * difference
  854. elif padding_side == "left":
  855. if return_attention_mask:
  856. encoded_inputs["attention_mask"] = [0] * difference + encoded_inputs["attention_mask"]
  857. if "token_type_ids" in encoded_inputs:
  858. encoded_inputs["token_type_ids"] = [self.pad_token_type_id] * difference + encoded_inputs[
  859. "token_type_ids"
  860. ]
  861. if "bbox" in encoded_inputs:
  862. encoded_inputs["bbox"] = [self.pad_token_box] * difference + encoded_inputs["bbox"]
  863. if "labels" in encoded_inputs:
  864. encoded_inputs["labels"] = [self.pad_token_label] * difference + encoded_inputs["labels"]
  865. if "special_tokens_mask" in encoded_inputs:
  866. encoded_inputs["special_tokens_mask"] = [1] * difference + encoded_inputs["special_tokens_mask"]
  867. encoded_inputs[self.model_input_names[0]] = [self.pad_token_id] * difference + required_input
  868. else:
  869. raise ValueError("Invalid padding strategy:" + str(padding_side))
  870. return encoded_inputs
  871. def build_inputs_with_special_tokens(
  872. self, token_ids_0: list[int], token_ids_1: list[int] | None = None
  873. ) -> list[int]:
  874. """
  875. Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
  876. adding special tokens. An XLM-RoBERTa sequence has the following format:
  877. - single sequence: `<s> X </s>`
  878. - pair of sequences: `<s> A </s></s> B </s>`
  879. Args:
  880. token_ids_0 (`list[int]`):
  881. List of IDs to which the special tokens will be added.
  882. token_ids_1 (`list[int]`, *optional*):
  883. Optional second list of IDs for sequence pairs.
  884. Returns:
  885. `list[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
  886. """
  887. if token_ids_1 is None:
  888. return token_ids_0 + [self.sep_token_id]
  889. sep = [self.sep_token_id]
  890. return token_ids_0 + sep + token_ids_1 + sep
  891. def create_token_type_ids_from_sequences(
  892. self, token_ids_0: list[int], token_ids_1: list[int] | None = None
  893. ) -> list[int]:
  894. """
  895. Create a mask from the two sequences passed to be used in a sequence-pair classification task. XLM-RoBERTa does
  896. not make use of token type ids, therefore a list of zeros is returned.
  897. Args:
  898. token_ids_0 (`list[int]`):
  899. List of IDs.
  900. token_ids_1 (`list[int]`, *optional*):
  901. Optional second list of IDs for sequence pairs.
  902. Returns:
  903. `list[int]`: List of zeros.
  904. """
  905. sep = [self.sep_token_id]
  906. if token_ids_1 is None:
  907. return len(token_ids_0 + sep) * [0]
  908. return len(token_ids_0 + sep + token_ids_1 + sep) * [0]
  909. def save_vocabulary(self, save_directory: str, filename_prefix: str | None = None) -> tuple[str]:
  910. """
  911. Save the tokenizer vocabulary files. For TokenizersBackend, the tokenizer.json file is saved
  912. by the base class. This method returns an empty tuple since we only use tokenizer.json.
  913. """
  914. # The base class handles saving tokenizer.json in _save_pretrained
  915. # We don't need to save vocab_file since we only use tokenizer.json
  916. return ()
  917. __all__ = ["UdopTokenizer"]