tokenization_layoutxlm.py 57 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191
  1. # coding=utf-8
  2. # Copyright 2021 The HuggingFace Inc. team.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License
  15. """Tokenization classes for LayoutXLM model."""
  16. import os
  17. from shutil import copyfile
  18. from typing import Any, Optional, Union
  19. import sentencepiece as spm
  20. from ...tokenization_utils import AddedToken, PreTrainedTokenizer
  21. from ...tokenization_utils_base import (
  22. BatchEncoding,
  23. EncodedInput,
  24. PreTokenizedInput,
  25. TextInput,
  26. TextInputPair,
  27. TruncationStrategy,
  28. )
  29. from ...utils import PaddingStrategy, TensorType, add_end_docstrings, logging
  30. from ...utils.import_utils import requires
  31. from ..xlm_roberta.tokenization_xlm_roberta import (
  32. SPIECE_UNDERLINE,
  33. VOCAB_FILES_NAMES,
  34. )
  35. logger = logging.get_logger(__name__)
  36. LAYOUTXLM_ENCODE_KWARGS_DOCSTRING = r"""
  37. add_special_tokens (`bool`, *optional*, defaults to `True`):
  38. Whether or not to encode the sequences with the special tokens relative to their model.
  39. padding (`bool`, `str` or [`~file_utils.PaddingStrategy`], *optional*, defaults to `False`):
  40. Activates and controls padding. Accepts the following values:
  41. - `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single
  42. sequence if provided).
  43. - `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum
  44. acceptable input length for the model if that argument is not provided.
  45. - `False` or `'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of different
  46. lengths).
  47. truncation (`bool`, `str` or [`~tokenization_utils_base.TruncationStrategy`], *optional*, defaults to `False`):
  48. Activates and controls truncation. Accepts the following values:
  49. - `True` or `'longest_first'`: Truncate to a maximum length specified with the argument `max_length` or
  50. to the maximum acceptable input length for the model if that argument is not provided. This will
  51. truncate token by token, removing a token from the longest sequence in the pair if a pair of
  52. sequences (or a batch of pairs) is provided.
  53. - `'only_first'`: Truncate to a maximum length specified with the argument `max_length` or to the
  54. maximum acceptable input length for the model if that argument is not provided. This will only
  55. truncate the first sequence of a pair if a pair of sequences (or a batch of pairs) is provided.
  56. - `'only_second'`: Truncate to a maximum length specified with the argument `max_length` or to the
  57. maximum acceptable input length for the model if that argument is not provided. This will only
  58. truncate the second sequence of a pair if a pair of sequences (or a batch of pairs) is provided.
  59. - `False` or `'do_not_truncate'` (default): No truncation (i.e., can output batch with sequence lengths
  60. greater than the model maximum admissible input size).
  61. max_length (`int`, *optional*):
  62. Controls the maximum length to use by one of the truncation/padding parameters.
  63. If left unset or set to `None`, this will use the predefined model maximum length if a maximum length
  64. is required by one of the truncation/padding parameters. If the model has no specific maximum input
  65. length (like XLNet) truncation/padding to a maximum length will be deactivated.
  66. stride (`int`, *optional*, defaults to 0):
  67. If set to a number along with `max_length`, the overflowing tokens returned when
  68. `return_overflowing_tokens=True` will contain some tokens from the end of the truncated sequence
  69. returned to provide some overlap between truncated and overflowing sequences. The value of this
  70. argument defines the number of overlapping tokens.
  71. pad_to_multiple_of (`int`, *optional*):
  72. If set will pad the sequence to a multiple of the provided value. This is especially useful to enable
  73. the use of Tensor Cores on NVIDIA hardware with compute capability `>= 7.5` (Volta).
  74. return_tensors (`str` or [`~file_utils.TensorType`], *optional*):
  75. If set, will return tensors instead of list of python integers. Acceptable values are:
  76. - `'tf'`: Return TensorFlow `tf.constant` objects.
  77. - `'pt'`: Return PyTorch `torch.Tensor` objects.
  78. - `'np'`: Return Numpy `np.ndarray` objects.
  79. return_token_type_ids (`bool`, *optional*):
  80. Whether to return token type IDs. If left to the default, will return the token type IDs according to
  81. the specific tokenizer's default, defined by the `return_outputs` attribute.
  82. [What are token type IDs?](../glossary#token-type-ids)
  83. return_attention_mask (`bool`, *optional*):
  84. Whether to return the attention mask. If left to the default, will return the attention mask according
  85. to the specific tokenizer's default, defined by the `return_outputs` attribute.
  86. [What are attention masks?](../glossary#attention-mask)
  87. return_overflowing_tokens (`bool`, *optional*, defaults to `False`):
  88. Whether or not to return overflowing token sequences. If a pair of sequences of input ids (or a batch
  89. of pairs) is provided with `truncation_strategy = longest_first` or `True`, an error is raised instead
  90. of returning overflowing tokens.
  91. return_special_tokens_mask (`bool`, *optional*, defaults to `False`):
  92. Whether or not to return special tokens mask information.
  93. return_offsets_mapping (`bool`, *optional*, defaults to `False`):
  94. Whether or not to return `(char_start, char_end)` for each token.
  95. This is only available on fast tokenizers inheriting from [`PreTrainedTokenizerFast`], if using
  96. Python's tokenizer, this method will raise `NotImplementedError`.
  97. return_length (`bool`, *optional*, defaults to `False`):
  98. Whether or not to return the lengths of the encoded inputs.
  99. verbose (`bool`, *optional*, defaults to `True`):
  100. Whether or not to print more information and warnings.
  101. **kwargs: passed to the `self.tokenize()` method
  102. Return:
  103. [`BatchEncoding`]: A [`BatchEncoding`] with the following fields:
  104. - **input_ids** -- List of token ids to be fed to a model.
  105. [What are input IDs?](../glossary#input-ids)
  106. - **bbox** -- List of bounding boxes to be fed to a model.
  107. - **token_type_ids** -- List of token type ids to be fed to a model (when `return_token_type_ids=True` or
  108. if *"token_type_ids"* is in `self.model_input_names`).
  109. [What are token type IDs?](../glossary#token-type-ids)
  110. - **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
  111. `return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names`).
  112. [What are attention masks?](../glossary#attention-mask)
  113. - **labels** -- List of labels to be fed to a model. (when `word_labels` is specified).
  114. - **overflowing_tokens** -- List of overflowing tokens sequences (when a `max_length` is specified and
  115. `return_overflowing_tokens=True`).
  116. - **num_truncated_tokens** -- Number of tokens truncated (when a `max_length` is specified and
  117. `return_overflowing_tokens=True`).
  118. - **special_tokens_mask** -- List of 0s and 1s, with 1 specifying added special tokens and 0 specifying
  119. regular sequence tokens (when `add_special_tokens=True` and `return_special_tokens_mask=True`).
  120. - **length** -- The length of the inputs (when `return_length=True`).
  121. """
  122. @requires(backends=("sentencepiece",))
  123. class LayoutXLMTokenizer(PreTrainedTokenizer):
  124. """
  125. Adapted from [`RobertaTokenizer`] and [`XLNetTokenizer`]. Based on
  126. [SentencePiece](https://github.com/google/sentencepiece).
  127. This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
  128. this superclass for more information regarding those methods.
  129. Args:
  130. vocab_file (`str`):
  131. Path to the vocabulary file.
  132. bos_token (`str`, *optional*, defaults to `"<s>"`):
  133. The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.
  134. <Tip>
  135. When building a sequence using special tokens, this is not the token that is used for the beginning of
  136. sequence. The token used is the `cls_token`.
  137. </Tip>
  138. eos_token (`str`, *optional*, defaults to `"</s>"`):
  139. The end of sequence token.
  140. <Tip>
  141. When building a sequence using special tokens, this is not the token that is used for the end of sequence.
  142. The token used is the `sep_token`.
  143. </Tip>
  144. sep_token (`str`, *optional*, defaults to `"</s>"`):
  145. The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
  146. sequence classification or for a text and a question for question answering. It is also used as the last
  147. token of a sequence built with special tokens.
  148. cls_token (`str`, *optional*, defaults to `"<s>"`):
  149. The classifier token which is used when doing sequence classification (classification of the whole sequence
  150. instead of per-token classification). It is the first token of the sequence when built with special tokens.
  151. unk_token (`str`, *optional*, defaults to `"<unk>"`):
  152. The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
  153. token instead.
  154. pad_token (`str`, *optional*, defaults to `"<pad>"`):
  155. The token used for padding, for example when batching sequences of different lengths.
  156. mask_token (`str`, *optional*, defaults to `"<mask>"`):
  157. The token used for masking values. This is the token used when training this model with masked language
  158. modeling. This is the token which the model will try to predict.
  159. cls_token_box (`list[int]`, *optional*, defaults to `[0, 0, 0, 0]`):
  160. The bounding box to use for the special [CLS] token.
  161. sep_token_box (`list[int]`, *optional*, defaults to `[1000, 1000, 1000, 1000]`):
  162. The bounding box to use for the special [SEP] token.
  163. pad_token_box (`list[int]`, *optional*, defaults to `[0, 0, 0, 0]`):
  164. The bounding box to use for the special [PAD] token.
  165. pad_token_label (`int`, *optional*, defaults to -100):
  166. The label to use for padding tokens. Defaults to -100, which is the `ignore_index` of PyTorch's
  167. CrossEntropyLoss.
  168. only_label_first_subword (`bool`, *optional*, defaults to `True`):
  169. Whether or not to only label the first subword, in case word labels are provided.
  170. sp_model_kwargs (`dict`, *optional*):
  171. Will be passed to the `SentencePieceProcessor.__init__()` method. The [Python wrapper for
  172. SentencePiece](https://github.com/google/sentencepiece/tree/master/python) can be used, among other things,
  173. to set:
  174. - `enable_sampling`: Enable subword regularization.
  175. - `nbest_size`: Sampling parameters for unigram. Invalid for BPE-Dropout.
  176. - `nbest_size = {0,1}`: No sampling is performed.
  177. - `nbest_size > 1`: samples from the nbest_size results.
  178. - `nbest_size < 0`: assuming that nbest_size is infinite and samples from the all hypothesis (lattice)
  179. using forward-filtering-and-backward-sampling algorithm.
  180. - `alpha`: Smoothing parameter for unigram sampling, and dropout probability of merge operations for
  181. BPE-dropout.
  182. Attributes:
  183. sp_model (`SentencePieceProcessor`):
  184. The *SentencePiece* processor that is used for every conversion (string, tokens and IDs).
  185. """
  186. vocab_files_names = VOCAB_FILES_NAMES
  187. model_input_names = ["input_ids", "attention_mask"]
  188. def __init__(
  189. self,
  190. vocab_file,
  191. bos_token="<s>",
  192. eos_token="</s>",
  193. sep_token="</s>",
  194. cls_token="<s>",
  195. unk_token="<unk>",
  196. pad_token="<pad>",
  197. mask_token="<mask>",
  198. cls_token_box=[0, 0, 0, 0],
  199. sep_token_box=[1000, 1000, 1000, 1000],
  200. pad_token_box=[0, 0, 0, 0],
  201. pad_token_label=-100,
  202. only_label_first_subword=True,
  203. sp_model_kwargs: Optional[dict[str, Any]] = None,
  204. **kwargs,
  205. ) -> None:
  206. # Mask token behave like a normal word, i.e. include the space before it
  207. mask_token = AddedToken(mask_token, lstrip=True, special=True) if isinstance(mask_token, str) else mask_token
  208. self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs
  209. self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
  210. self.sp_model.Load(str(vocab_file))
  211. self.vocab_file = vocab_file
  212. # Original fairseq vocab and spm vocab must be "aligned":
  213. # Vocab | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9
  214. # -------- | ------- | ------- | ------ | ------- | --- | --- | --- | ----- | ----- | ----
  215. # fairseq | '<s>' | '<pad>' | '</s>' | '<unk>' | ',' | '.' | '▁' | 's' | '▁de' | '-'
  216. # spm | '<unk>' | '<s>' | '</s>' | ',' | '.' | '▁' | 's' | '▁de' | '-' | '▁a'
  217. # Mimic fairseq token-to-id alignment for the first 4 token
  218. self.fairseq_tokens_to_ids = {"<s>": 0, "<pad>": 1, "</s>": 2, "<unk>": 3}
  219. # The first "real" token "," has position 4 in the original fairseq vocab and position 3 in the spm vocab
  220. self.fairseq_offset = 1
  221. self.fairseq_tokens_to_ids["<mask>"] = len(self.sp_model) + self.fairseq_offset
  222. self.fairseq_ids_to_tokens = {v: k for k, v in self.fairseq_tokens_to_ids.items()}
  223. # additional properties
  224. self.cls_token_box = cls_token_box
  225. self.sep_token_box = sep_token_box
  226. self.pad_token_box = pad_token_box
  227. self.pad_token_label = pad_token_label
  228. self.only_label_first_subword = only_label_first_subword
  229. super().__init__(
  230. bos_token=bos_token,
  231. eos_token=eos_token,
  232. unk_token=unk_token,
  233. sep_token=sep_token,
  234. cls_token=cls_token,
  235. pad_token=pad_token,
  236. mask_token=mask_token,
  237. cls_token_box=cls_token_box,
  238. sep_token_box=sep_token_box,
  239. pad_token_box=pad_token_box,
  240. pad_token_label=pad_token_label,
  241. only_label_first_subword=only_label_first_subword,
  242. sp_model_kwargs=self.sp_model_kwargs,
  243. **kwargs,
  244. )
  245. def __getstate__(self):
  246. state = self.__dict__.copy()
  247. state["sp_model"] = None
  248. state["sp_model_proto"] = self.sp_model.serialized_model_proto()
  249. return state
  250. def __setstate__(self, d):
  251. self.__dict__.update(d)
  252. # for backward compatibility
  253. if not hasattr(self, "sp_model_kwargs"):
  254. self.sp_model_kwargs = {}
  255. self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
  256. self.sp_model.LoadFromSerializedProto(self.sp_model_proto)
  257. def build_inputs_with_special_tokens(
  258. self, token_ids_0: list[int], token_ids_1: Optional[list[int]] = None
  259. ) -> list[int]:
  260. """
  261. Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
  262. adding special tokens. An XLM-RoBERTa sequence has the following format:
  263. - single sequence: `<s> X </s>`
  264. - pair of sequences: `<s> A </s></s> B </s>`
  265. Args:
  266. token_ids_0 (`list[int]`):
  267. List of IDs to which the special tokens will be added.
  268. token_ids_1 (`list[int]`, *optional*):
  269. Optional second list of IDs for sequence pairs.
  270. Returns:
  271. `list[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
  272. """
  273. if token_ids_1 is None:
  274. return [self.cls_token_id] + token_ids_0 + [self.sep_token_id]
  275. cls = [self.cls_token_id]
  276. sep = [self.sep_token_id]
  277. return cls + token_ids_0 + sep + sep + token_ids_1 + sep
  278. def get_special_tokens_mask(
  279. self, token_ids_0: list[int], token_ids_1: Optional[list[int]] = None, already_has_special_tokens: bool = False
  280. ) -> list[int]:
  281. """
  282. Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
  283. special tokens using the tokenizer `prepare_for_model` method.
  284. Args:
  285. token_ids_0 (`list[int]`):
  286. List of IDs.
  287. token_ids_1 (`list[int]`, *optional*):
  288. Optional second list of IDs for sequence pairs.
  289. already_has_special_tokens (`bool`, *optional*, defaults to `False`):
  290. Whether or not the token list is already formatted with special tokens for the model.
  291. Returns:
  292. `list[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
  293. """
  294. if already_has_special_tokens:
  295. return super().get_special_tokens_mask(
  296. token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
  297. )
  298. if token_ids_1 is None:
  299. return [1] + ([0] * len(token_ids_0)) + [1]
  300. return [1] + ([0] * len(token_ids_0)) + [1, 1] + ([0] * len(token_ids_1)) + [1]
  301. def create_token_type_ids_from_sequences(
  302. self, token_ids_0: list[int], token_ids_1: Optional[list[int]] = None
  303. ) -> list[int]:
  304. """
  305. Create a mask from the two sequences passed to be used in a sequence-pair classification task. XLM-RoBERTa does
  306. not make use of token type ids, therefore a list of zeros is returned.
  307. Args:
  308. token_ids_0 (`list[int]`):
  309. List of IDs.
  310. token_ids_1 (`list[int]`, *optional*):
  311. Optional second list of IDs for sequence pairs.
  312. Returns:
  313. `list[int]`: List of zeros.
  314. """
  315. sep = [self.sep_token_id]
  316. cls = [self.cls_token_id]
  317. if token_ids_1 is None:
  318. return len(cls + token_ids_0 + sep) * [0]
  319. return len(cls + token_ids_0 + sep + sep + token_ids_1 + sep) * [0]
  320. @property
  321. def vocab_size(self):
  322. return len(self.sp_model) + self.fairseq_offset + 1 # Add the <mask> token
  323. def get_vocab(self):
  324. vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size)}
  325. vocab.update(self.added_tokens_encoder)
  326. return vocab
  327. def _tokenize(self, text: str) -> list[str]:
  328. return self.sp_model.encode(text, out_type=str)
  329. def _convert_token_to_id(self, token):
  330. """Converts a token (str) in an id using the vocab."""
  331. if token in self.fairseq_tokens_to_ids:
  332. return self.fairseq_tokens_to_ids[token]
  333. spm_id = self.sp_model.PieceToId(token)
  334. # Need to return unknown token if the SP model returned 0
  335. return spm_id + self.fairseq_offset if spm_id else self.unk_token_id
  336. def _convert_id_to_token(self, index):
  337. """Converts an index (integer) in a token (str) using the vocab."""
  338. if index in self.fairseq_ids_to_tokens:
  339. return self.fairseq_ids_to_tokens[index]
  340. return self.sp_model.IdToPiece(index - self.fairseq_offset)
  341. def convert_tokens_to_string(self, tokens):
  342. """Converts a sequence of tokens (strings for sub-words) in a single string."""
  343. out_string = "".join(tokens).replace(SPIECE_UNDERLINE, " ").strip()
  344. return out_string
  345. def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> tuple[str]:
  346. if not os.path.isdir(save_directory):
  347. logger.error(f"Vocabulary path ({save_directory}) should be a directory")
  348. return
  349. out_vocab_file = os.path.join(
  350. save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
  351. )
  352. if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file) and os.path.isfile(self.vocab_file):
  353. copyfile(self.vocab_file, out_vocab_file)
  354. elif not os.path.isfile(self.vocab_file):
  355. with open(out_vocab_file, "wb") as fi:
  356. content_spiece_model = self.sp_model.serialized_model_proto()
  357. fi.write(content_spiece_model)
  358. return (out_vocab_file,)
  359. @add_end_docstrings(LAYOUTXLM_ENCODE_KWARGS_DOCSTRING)
  360. def __call__(
  361. self,
  362. text: Union[TextInput, PreTokenizedInput, list[TextInput], list[PreTokenizedInput]],
  363. text_pair: Optional[Union[PreTokenizedInput, list[PreTokenizedInput]]] = None,
  364. boxes: Optional[Union[list[list[int]], list[list[list[int]]]]] = None,
  365. word_labels: Optional[Union[list[int], list[list[int]]]] = None,
  366. add_special_tokens: bool = True,
  367. padding: Union[bool, str, PaddingStrategy] = False,
  368. truncation: Union[bool, str, TruncationStrategy] = None,
  369. max_length: Optional[int] = None,
  370. stride: int = 0,
  371. pad_to_multiple_of: Optional[int] = None,
  372. padding_side: Optional[str] = None,
  373. return_tensors: Optional[Union[str, TensorType]] = None,
  374. return_token_type_ids: Optional[bool] = None,
  375. return_attention_mask: Optional[bool] = None,
  376. return_overflowing_tokens: bool = False,
  377. return_special_tokens_mask: bool = False,
  378. return_offsets_mapping: bool = False,
  379. return_length: bool = False,
  380. verbose: bool = True,
  381. **kwargs,
  382. ) -> BatchEncoding:
  383. """
  384. Main method to tokenize and prepare for the model one or several sequence(s) or one or several pair(s) of
  385. sequences with word-level normalized bounding boxes and optional labels.
  386. Args:
  387. text (`str`, `list[str]`, `list[list[str]]`):
  388. The sequence or batch of sequences to be encoded. Each sequence can be a string, a list of strings
  389. (words of a single example or questions of a batch of examples) or a list of list of strings (batch of
  390. words).
  391. text_pair (`list[str]`, `list[list[str]]`):
  392. The sequence or batch of sequences to be encoded. Each sequence should be a list of strings
  393. (pretokenized string).
  394. boxes (`list[list[int]]`, `list[list[list[int]]]`):
  395. Word-level bounding boxes. Each bounding box should be normalized to be on a 0-1000 scale.
  396. word_labels (`list[int]`, `list[list[int]]`, *optional*):
  397. Word-level integer labels (for token classification tasks such as FUNSD, CORD).
  398. """
  399. # Input type checking for clearer error
  400. def _is_valid_text_input(t):
  401. if isinstance(t, str):
  402. # Strings are fine
  403. return True
  404. elif isinstance(t, (list, tuple)):
  405. # List are fine as long as they are...
  406. if len(t) == 0:
  407. # ... empty
  408. return True
  409. elif isinstance(t[0], str):
  410. # ... list of strings
  411. return True
  412. elif isinstance(t[0], (list, tuple)):
  413. # ... list with an empty list or with a list of strings
  414. return len(t[0]) == 0 or isinstance(t[0][0], str)
  415. else:
  416. return False
  417. else:
  418. return False
  419. if text_pair is not None:
  420. # in case text + text_pair are provided, text = questions, text_pair = words
  421. if not _is_valid_text_input(text):
  422. raise ValueError("text input must of type `str` (single example) or `list[str]` (batch of examples). ")
  423. if not isinstance(text_pair, (list, tuple)):
  424. raise ValueError(
  425. "words must of type `list[str]` (single pretokenized example), "
  426. "or `list[list[str]]` (batch of pretokenized examples)."
  427. )
  428. else:
  429. # in case only text is provided => must be words
  430. if not isinstance(text, (list, tuple)):
  431. raise ValueError(
  432. "Words must of type `list[str]` (single pretokenized example), "
  433. "or `list[list[str]]` (batch of pretokenized examples)."
  434. )
  435. if text_pair is not None:
  436. is_batched = isinstance(text, (list, tuple))
  437. else:
  438. is_batched = isinstance(text, (list, tuple)) and text and isinstance(text[0], (list, tuple))
  439. words = text if text_pair is None else text_pair
  440. if boxes is None:
  441. raise ValueError("You must provide corresponding bounding boxes")
  442. if is_batched:
  443. if len(words) != len(boxes):
  444. raise ValueError("You must provide words and boxes for an equal amount of examples")
  445. for words_example, boxes_example in zip(words, boxes):
  446. if len(words_example) != len(boxes_example):
  447. raise ValueError("You must provide as many words as there are bounding boxes")
  448. else:
  449. if len(words) != len(boxes):
  450. raise ValueError("You must provide as many words as there are bounding boxes")
  451. if is_batched:
  452. if text_pair is not None and len(text) != len(text_pair):
  453. raise ValueError(
  454. f"batch length of `text`: {len(text)} does not match batch length of `text_pair`:"
  455. f" {len(text_pair)}."
  456. )
  457. batch_text_or_text_pairs = list(zip(text, text_pair)) if text_pair is not None else text
  458. is_pair = bool(text_pair is not None)
  459. return self.batch_encode_plus(
  460. batch_text_or_text_pairs=batch_text_or_text_pairs,
  461. is_pair=is_pair,
  462. boxes=boxes,
  463. word_labels=word_labels,
  464. add_special_tokens=add_special_tokens,
  465. padding=padding,
  466. truncation=truncation,
  467. max_length=max_length,
  468. stride=stride,
  469. pad_to_multiple_of=pad_to_multiple_of,
  470. padding_side=padding_side,
  471. return_tensors=return_tensors,
  472. return_token_type_ids=return_token_type_ids,
  473. return_attention_mask=return_attention_mask,
  474. return_overflowing_tokens=return_overflowing_tokens,
  475. return_special_tokens_mask=return_special_tokens_mask,
  476. return_offsets_mapping=return_offsets_mapping,
  477. return_length=return_length,
  478. verbose=verbose,
  479. **kwargs,
  480. )
  481. else:
  482. return self.encode_plus(
  483. text=text,
  484. text_pair=text_pair,
  485. boxes=boxes,
  486. word_labels=word_labels,
  487. add_special_tokens=add_special_tokens,
  488. padding=padding,
  489. truncation=truncation,
  490. max_length=max_length,
  491. stride=stride,
  492. pad_to_multiple_of=pad_to_multiple_of,
  493. padding_side=padding_side,
  494. return_tensors=return_tensors,
  495. return_token_type_ids=return_token_type_ids,
  496. return_attention_mask=return_attention_mask,
  497. return_overflowing_tokens=return_overflowing_tokens,
  498. return_special_tokens_mask=return_special_tokens_mask,
  499. return_offsets_mapping=return_offsets_mapping,
  500. return_length=return_length,
  501. verbose=verbose,
  502. **kwargs,
  503. )
  504. def _batch_encode_plus(
  505. self,
  506. batch_text_or_text_pairs: Union[
  507. list[TextInput],
  508. list[TextInputPair],
  509. list[PreTokenizedInput],
  510. ],
  511. is_pair: Optional[bool] = None,
  512. boxes: Optional[list[list[list[int]]]] = None,
  513. word_labels: Optional[list[list[int]]] = None,
  514. add_special_tokens: bool = True,
  515. padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
  516. truncation_strategy: TruncationStrategy = TruncationStrategy.DO_NOT_TRUNCATE,
  517. max_length: Optional[int] = None,
  518. stride: int = 0,
  519. pad_to_multiple_of: Optional[int] = None,
  520. padding_side: Optional[str] = None,
  521. return_tensors: Optional[Union[str, TensorType]] = None,
  522. return_token_type_ids: Optional[bool] = None,
  523. return_attention_mask: Optional[bool] = None,
  524. return_overflowing_tokens: bool = False,
  525. return_special_tokens_mask: bool = False,
  526. return_offsets_mapping: bool = False,
  527. return_length: bool = False,
  528. verbose: bool = True,
  529. **kwargs,
  530. ) -> BatchEncoding:
  531. if return_offsets_mapping:
  532. raise NotImplementedError(
  533. "return_offset_mapping is not available when using Python tokenizers. "
  534. "To use this feature, change your tokenizer to one deriving from "
  535. "transformers.PreTrainedTokenizerFast."
  536. )
  537. batch_outputs = self._batch_prepare_for_model(
  538. batch_text_or_text_pairs=batch_text_or_text_pairs,
  539. is_pair=is_pair,
  540. boxes=boxes,
  541. word_labels=word_labels,
  542. add_special_tokens=add_special_tokens,
  543. padding_strategy=padding_strategy,
  544. truncation_strategy=truncation_strategy,
  545. max_length=max_length,
  546. stride=stride,
  547. pad_to_multiple_of=pad_to_multiple_of,
  548. padding_side=padding_side,
  549. return_attention_mask=return_attention_mask,
  550. return_token_type_ids=return_token_type_ids,
  551. return_overflowing_tokens=return_overflowing_tokens,
  552. return_special_tokens_mask=return_special_tokens_mask,
  553. return_length=return_length,
  554. return_tensors=return_tensors,
  555. verbose=verbose,
  556. )
  557. return BatchEncoding(batch_outputs)
  558. @add_end_docstrings(LAYOUTXLM_ENCODE_KWARGS_DOCSTRING)
  559. def _batch_prepare_for_model(
  560. self,
  561. batch_text_or_text_pairs,
  562. is_pair: Optional[bool] = None,
  563. boxes: Optional[list[list[int]]] = None,
  564. word_labels: Optional[list[list[int]]] = None,
  565. add_special_tokens: bool = True,
  566. padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
  567. truncation_strategy: TruncationStrategy = TruncationStrategy.DO_NOT_TRUNCATE,
  568. max_length: Optional[int] = None,
  569. stride: int = 0,
  570. pad_to_multiple_of: Optional[int] = None,
  571. padding_side: Optional[str] = None,
  572. return_tensors: Optional[str] = None,
  573. return_token_type_ids: Optional[bool] = None,
  574. return_attention_mask: Optional[bool] = None,
  575. return_overflowing_tokens: bool = False,
  576. return_special_tokens_mask: bool = False,
  577. return_length: bool = False,
  578. verbose: bool = True,
  579. ) -> BatchEncoding:
  580. """
  581. Prepares a sequence of input id, or a pair of sequences of inputs ids so that it can be used by the model. It
  582. adds special tokens, truncates sequences if overflowing while taking into account the special tokens and
  583. manages a moving window (with user defined stride) for overflowing tokens
  584. Args:
  585. batch_ids_pairs: list of tokenized input ids or input ids pairs
  586. """
  587. batch_outputs = {}
  588. for idx, example in enumerate(zip(batch_text_or_text_pairs, boxes)):
  589. batch_text_or_text_pair, boxes_example = example
  590. outputs = self.prepare_for_model(
  591. batch_text_or_text_pair[0] if is_pair else batch_text_or_text_pair,
  592. batch_text_or_text_pair[1] if is_pair else None,
  593. boxes_example,
  594. word_labels=word_labels[idx] if word_labels is not None else None,
  595. add_special_tokens=add_special_tokens,
  596. padding=PaddingStrategy.DO_NOT_PAD.value, # we pad in batch afterward
  597. truncation=truncation_strategy.value,
  598. max_length=max_length,
  599. stride=stride,
  600. pad_to_multiple_of=None, # we pad in batch afterward
  601. padding_side=None, # we pad in batch afterward
  602. return_attention_mask=False, # we pad in batch afterward
  603. return_token_type_ids=return_token_type_ids,
  604. return_overflowing_tokens=return_overflowing_tokens,
  605. return_special_tokens_mask=return_special_tokens_mask,
  606. return_length=return_length,
  607. return_tensors=None, # We convert the whole batch to tensors at the end
  608. prepend_batch_axis=False,
  609. verbose=verbose,
  610. )
  611. for key, value in outputs.items():
  612. if key not in batch_outputs:
  613. batch_outputs[key] = []
  614. batch_outputs[key].append(value)
  615. batch_outputs = self.pad(
  616. batch_outputs,
  617. padding=padding_strategy.value,
  618. max_length=max_length,
  619. pad_to_multiple_of=pad_to_multiple_of,
  620. padding_side=padding_side,
  621. return_attention_mask=return_attention_mask,
  622. )
  623. batch_outputs = BatchEncoding(batch_outputs, tensor_type=return_tensors)
  624. return batch_outputs
  625. def _encode_plus(
  626. self,
  627. text: Union[TextInput, PreTokenizedInput],
  628. text_pair: Optional[PreTokenizedInput] = None,
  629. boxes: Optional[list[list[int]]] = None,
  630. word_labels: Optional[list[int]] = None,
  631. add_special_tokens: bool = True,
  632. padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
  633. truncation_strategy: TruncationStrategy = TruncationStrategy.DO_NOT_TRUNCATE,
  634. max_length: Optional[int] = None,
  635. stride: int = 0,
  636. pad_to_multiple_of: Optional[int] = None,
  637. padding_side: Optional[str] = None,
  638. return_tensors: Optional[Union[str, TensorType]] = None,
  639. return_token_type_ids: Optional[bool] = None,
  640. return_attention_mask: Optional[bool] = None,
  641. return_overflowing_tokens: bool = False,
  642. return_special_tokens_mask: bool = False,
  643. return_offsets_mapping: bool = False,
  644. return_length: bool = False,
  645. verbose: bool = True,
  646. **kwargs,
  647. ) -> BatchEncoding:
  648. if return_offsets_mapping:
  649. raise NotImplementedError(
  650. "return_offset_mapping is not available when using Python tokenizers. "
  651. "To use this feature, change your tokenizer to one deriving from "
  652. "transformers.PreTrainedTokenizerFast. "
  653. "More information on available tokenizers at "
  654. "https://github.com/huggingface/transformers/pull/2674"
  655. )
  656. return self.prepare_for_model(
  657. text=text,
  658. text_pair=text_pair,
  659. boxes=boxes,
  660. word_labels=word_labels,
  661. add_special_tokens=add_special_tokens,
  662. padding=padding_strategy.value,
  663. truncation=truncation_strategy.value,
  664. max_length=max_length,
  665. stride=stride,
  666. pad_to_multiple_of=pad_to_multiple_of,
  667. padding_side=padding_side,
  668. return_tensors=return_tensors,
  669. prepend_batch_axis=True,
  670. return_attention_mask=return_attention_mask,
  671. return_token_type_ids=return_token_type_ids,
  672. return_overflowing_tokens=return_overflowing_tokens,
  673. return_special_tokens_mask=return_special_tokens_mask,
  674. return_length=return_length,
  675. verbose=verbose,
  676. )
  677. @add_end_docstrings(LAYOUTXLM_ENCODE_KWARGS_DOCSTRING)
  678. def prepare_for_model(
  679. self,
  680. text: Union[TextInput, PreTokenizedInput],
  681. text_pair: Optional[PreTokenizedInput] = None,
  682. boxes: Optional[list[list[int]]] = None,
  683. word_labels: Optional[list[int]] = None,
  684. add_special_tokens: bool = True,
  685. padding: Union[bool, str, PaddingStrategy] = False,
  686. truncation: Union[bool, str, TruncationStrategy] = None,
  687. max_length: Optional[int] = None,
  688. stride: int = 0,
  689. pad_to_multiple_of: Optional[int] = None,
  690. padding_side: Optional[str] = None,
  691. return_tensors: Optional[Union[str, TensorType]] = None,
  692. return_token_type_ids: Optional[bool] = None,
  693. return_attention_mask: Optional[bool] = None,
  694. return_overflowing_tokens: bool = False,
  695. return_special_tokens_mask: bool = False,
  696. return_offsets_mapping: bool = False,
  697. return_length: bool = False,
  698. verbose: bool = True,
  699. prepend_batch_axis: bool = False,
  700. **kwargs,
  701. ) -> BatchEncoding:
  702. """
  703. Prepares a sequence or a pair of sequences so that it can be used by the model. It adds special tokens,
  704. truncates sequences if overflowing while taking into account the special tokens and manages a moving window
  705. (with user defined stride) for overflowing tokens.
  706. Word-level `boxes` are turned into token-level `bbox`. If provided, word-level `word_labels` are turned into
  707. token-level `labels`. The word label is used for the first token of the word, while remaining tokens are
  708. labeled with -100, such that they will be ignored by the loss function.
  709. Args:
  710. text (`str`, `list[str]`, `list[list[str]]`):
  711. The first sequence to be encoded. This can be a string, a list of strings or a list of list of strings.
  712. text_pair (`list[str]` or `list[int]`, *optional*):
  713. Optional second sequence to be encoded. This can be a list of strings (words of a single example) or a
  714. list of list of strings (words of a batch of examples).
  715. """
  716. # Backward compatibility for 'truncation_strategy', 'pad_to_max_length'
  717. padding_strategy, truncation_strategy, max_length, kwargs = self._get_padding_truncation_strategies(
  718. padding=padding,
  719. truncation=truncation,
  720. max_length=max_length,
  721. pad_to_multiple_of=pad_to_multiple_of,
  722. verbose=verbose,
  723. **kwargs,
  724. )
  725. tokens = []
  726. pair_tokens = []
  727. token_boxes = []
  728. pair_token_boxes = []
  729. labels = []
  730. if text_pair is None:
  731. if word_labels is None:
  732. # CASE 1: document image classification (training + inference) + CASE 2: token classification (inference)
  733. for word, box in zip(text, boxes):
  734. if len(word) < 1: # skip empty words
  735. continue
  736. word_tokens = self.tokenize(word)
  737. tokens.extend(word_tokens)
  738. token_boxes.extend([box] * len(word_tokens))
  739. else:
  740. # CASE 2: token classification (training)
  741. for word, box, label in zip(text, boxes, word_labels):
  742. if len(word) < 1: # skip empty words
  743. continue
  744. word_tokens = self.tokenize(word)
  745. tokens.extend(word_tokens)
  746. token_boxes.extend([box] * len(word_tokens))
  747. if self.only_label_first_subword:
  748. # Use the real label id for the first token of the word, and padding ids for the remaining tokens
  749. labels.extend([label] + [self.pad_token_label] * (len(word_tokens) - 1))
  750. else:
  751. labels.extend([label] * len(word_tokens))
  752. else:
  753. # CASE 3: document visual question answering (inference)
  754. # text = question
  755. # text_pair = words
  756. tokens = self.tokenize(text)
  757. token_boxes = [self.pad_token_box for _ in range(len(tokens))] + [self.sep_token_box]
  758. for word, box in zip(text_pair, boxes):
  759. if len(word) < 1: # skip empty words
  760. continue
  761. word_tokens = self.tokenize(word)
  762. pair_tokens.extend(word_tokens)
  763. pair_token_boxes.extend([box] * len(word_tokens))
  764. # Create ids + pair_ids
  765. ids = self.convert_tokens_to_ids(tokens)
  766. pair_ids = self.convert_tokens_to_ids(pair_tokens) if pair_tokens else None
  767. # Compute the total size of the returned encodings
  768. pair = bool(pair_ids is not None)
  769. len_ids = len(ids)
  770. len_pair_ids = len(pair_ids) if pair else 0
  771. total_len = len_ids + len_pair_ids + (self.num_special_tokens_to_add(pair=pair) if add_special_tokens else 0)
  772. # Truncation: Handle max sequence length
  773. overflowing_tokens = []
  774. overflowing_token_boxes = []
  775. overflowing_labels = []
  776. if truncation_strategy != TruncationStrategy.DO_NOT_TRUNCATE and max_length and total_len > max_length:
  777. (
  778. ids,
  779. token_boxes,
  780. pair_ids,
  781. pair_token_boxes,
  782. labels,
  783. overflowing_tokens,
  784. overflowing_token_boxes,
  785. overflowing_labels,
  786. ) = self.truncate_sequences(
  787. ids,
  788. token_boxes,
  789. pair_ids=pair_ids,
  790. pair_token_boxes=pair_token_boxes,
  791. labels=labels,
  792. num_tokens_to_remove=total_len - max_length,
  793. truncation_strategy=truncation_strategy,
  794. stride=stride,
  795. )
  796. if return_token_type_ids and not add_special_tokens:
  797. raise ValueError(
  798. "Asking to return token_type_ids while setting add_special_tokens to False "
  799. "results in an undefined behavior. Please set add_special_tokens to True or "
  800. "set return_token_type_ids to None."
  801. )
  802. # Load from model defaults
  803. if return_token_type_ids is None:
  804. return_token_type_ids = "token_type_ids" in self.model_input_names
  805. if return_attention_mask is None:
  806. return_attention_mask = "attention_mask" in self.model_input_names
  807. encoded_inputs = {}
  808. if return_overflowing_tokens:
  809. encoded_inputs["overflowing_tokens"] = overflowing_tokens
  810. encoded_inputs["overflowing_token_boxes"] = overflowing_token_boxes
  811. encoded_inputs["overflowing_labels"] = overflowing_labels
  812. encoded_inputs["num_truncated_tokens"] = total_len - max_length
  813. # Add special tokens
  814. if add_special_tokens:
  815. sequence = self.build_inputs_with_special_tokens(ids, pair_ids)
  816. token_type_ids = self.create_token_type_ids_from_sequences(ids, pair_ids)
  817. token_boxes = [self.cls_token_box] + token_boxes + [self.sep_token_box]
  818. if pair_token_boxes:
  819. pair_token_boxes = pair_token_boxes + [self.sep_token_box]
  820. if labels:
  821. labels = [self.pad_token_label] + labels + [self.pad_token_label]
  822. else:
  823. sequence = ids + pair_ids if pair else ids
  824. token_type_ids = [0] * len(ids) + ([0] * len(pair_ids) if pair else [])
  825. # Build output dictionary
  826. encoded_inputs["input_ids"] = sequence
  827. encoded_inputs["bbox"] = token_boxes + pair_token_boxes
  828. if return_token_type_ids:
  829. encoded_inputs["token_type_ids"] = token_type_ids
  830. if return_special_tokens_mask:
  831. if add_special_tokens:
  832. encoded_inputs["special_tokens_mask"] = self.get_special_tokens_mask(ids, pair_ids)
  833. else:
  834. encoded_inputs["special_tokens_mask"] = [0] * len(sequence)
  835. if labels:
  836. encoded_inputs["labels"] = labels
  837. # Check lengths
  838. self._eventual_warn_about_too_long_sequence(encoded_inputs["input_ids"], max_length, verbose)
  839. # Padding
  840. if padding_strategy != PaddingStrategy.DO_NOT_PAD or return_attention_mask:
  841. encoded_inputs = self.pad(
  842. encoded_inputs,
  843. max_length=max_length,
  844. padding=padding_strategy.value,
  845. pad_to_multiple_of=pad_to_multiple_of,
  846. padding_side=padding_side,
  847. return_attention_mask=return_attention_mask,
  848. )
  849. if return_length:
  850. encoded_inputs["length"] = len(encoded_inputs["input_ids"])
  851. batch_outputs = BatchEncoding(
  852. encoded_inputs, tensor_type=return_tensors, prepend_batch_axis=prepend_batch_axis
  853. )
  854. return batch_outputs
  855. def truncate_sequences(
  856. self,
  857. ids: list[int],
  858. token_boxes: list[list[int]],
  859. pair_ids: Optional[list[int]] = None,
  860. pair_token_boxes: Optional[list[list[int]]] = None,
  861. labels: Optional[list[int]] = None,
  862. num_tokens_to_remove: int = 0,
  863. truncation_strategy: Union[str, TruncationStrategy] = "longest_first",
  864. stride: int = 0,
  865. ) -> tuple[list[int], list[int], list[int]]:
  866. """
  867. Truncates a sequence pair in-place following the strategy.
  868. Args:
  869. ids (`list[int]`):
  870. Tokenized input ids of the first sequence. Can be obtained from a string by chaining the `tokenize` and
  871. `convert_tokens_to_ids` methods.
  872. token_boxes (`list[list[int]]`):
  873. Bounding boxes of the first sequence.
  874. pair_ids (`list[int]`, *optional*):
  875. Tokenized input ids of the second sequence. Can be obtained from a string by chaining the `tokenize`
  876. and `convert_tokens_to_ids` methods.
  877. pair_token_boxes (`list[list[int]]`, *optional*):
  878. Bounding boxes of the second sequence.
  879. labels (`list[int]`, *optional*):
  880. Labels of the first sequence (for token classification tasks).
  881. num_tokens_to_remove (`int`, *optional*, defaults to 0):
  882. Number of tokens to remove using the truncation strategy.
  883. truncation_strategy (`str` or [`~tokenization_utils_base.TruncationStrategy`], *optional*, defaults to `False`):
  884. The strategy to follow for truncation. Can be:
  885. - `'longest_first'`: Truncate to a maximum length specified with the argument `max_length` or to the
  886. maximum acceptable input length for the model if that argument is not provided. This will truncate
  887. token by token, removing a token from the longest sequence in the pair if a pair of sequences (or a
  888. batch of pairs) is provided.
  889. - `'only_first'`: Truncate to a maximum length specified with the argument `max_length` or to the
  890. maximum acceptable input length for the model if that argument is not provided. This will only
  891. truncate the first sequence of a pair if a pair of sequences (or a batch of pairs) is provided.
  892. - `'only_second'`: Truncate to a maximum length specified with the argument `max_length` or to the
  893. maximum acceptable input length for the model if that argument is not provided. This will only
  894. truncate the second sequence of a pair if a pair of sequences (or a batch of pairs) is provided.
  895. - `'do_not_truncate'` (default): No truncation (i.e., can output batch with sequence lengths greater
  896. than the model maximum admissible input size).
  897. stride (`int`, *optional*, defaults to 0):
  898. If set to a positive number, the overflowing tokens returned will contain some tokens from the main
  899. sequence returned. The value of this argument defines the number of additional tokens.
  900. Returns:
  901. `tuple[list[int], list[int], list[int]]`: The truncated `ids`, the truncated `pair_ids` and the list of
  902. overflowing tokens.
  903. """
  904. if num_tokens_to_remove <= 0:
  905. return ids, token_boxes, pair_ids, pair_token_boxes, labels, [], [], []
  906. if not isinstance(truncation_strategy, TruncationStrategy):
  907. truncation_strategy = TruncationStrategy(truncation_strategy)
  908. overflowing_tokens = []
  909. overflowing_token_boxes = []
  910. overflowing_labels = []
  911. if truncation_strategy == TruncationStrategy.LONGEST_FIRST:
  912. for _ in range(num_tokens_to_remove):
  913. if pair_ids is None or len(ids) > len(pair_ids):
  914. if not overflowing_tokens:
  915. window_len = min(len(ids), stride + 1)
  916. else:
  917. window_len = 1
  918. overflowing_tokens.extend(ids[-window_len:])
  919. overflowing_token_boxes.extend(token_boxes[-window_len:])
  920. overflowing_labels.extend(labels[-window_len:])
  921. ids = ids[:-1]
  922. token_boxes = token_boxes[:-1]
  923. labels = labels[:-1]
  924. else:
  925. if not overflowing_tokens:
  926. window_len = min(len(pair_ids), stride + 1)
  927. else:
  928. window_len = 1
  929. overflowing_tokens.extend(pair_ids[-window_len:])
  930. overflowing_token_boxes.extend(pair_token_boxes[-window_len:])
  931. pair_ids = pair_ids[:-1]
  932. pair_token_boxes = pair_token_boxes[:-1]
  933. elif truncation_strategy == TruncationStrategy.ONLY_FIRST:
  934. if len(ids) > num_tokens_to_remove:
  935. window_len = min(len(ids), stride + num_tokens_to_remove)
  936. overflowing_tokens = ids[-window_len:]
  937. overflowing_token_boxes = token_boxes[-window_len:]
  938. overflowing_labels = labels[-window_len:]
  939. ids = ids[:-num_tokens_to_remove]
  940. token_boxes = token_boxes[:-num_tokens_to_remove]
  941. labels = labels[:-num_tokens_to_remove]
  942. else:
  943. logger.error(
  944. f"We need to remove {num_tokens_to_remove} to truncate the input "
  945. f"but the first sequence has a length {len(ids)}. "
  946. f"Please select another truncation strategy than {truncation_strategy}, "
  947. "for instance 'longest_first' or 'only_second'."
  948. )
  949. elif truncation_strategy == TruncationStrategy.ONLY_SECOND and pair_ids is not None:
  950. if len(pair_ids) > num_tokens_to_remove:
  951. window_len = min(len(pair_ids), stride + num_tokens_to_remove)
  952. overflowing_tokens = pair_ids[-window_len:]
  953. overflowing_token_boxes = pair_token_boxes[-window_len:]
  954. pair_ids = pair_ids[:-num_tokens_to_remove]
  955. pair_token_boxes = pair_token_boxes[:-num_tokens_to_remove]
  956. else:
  957. logger.error(
  958. f"We need to remove {num_tokens_to_remove} to truncate the input "
  959. f"but the second sequence has a length {len(pair_ids)}. "
  960. f"Please select another truncation strategy than {truncation_strategy}, "
  961. "for instance 'longest_first' or 'only_first'."
  962. )
  963. return (
  964. ids,
  965. token_boxes,
  966. pair_ids,
  967. pair_token_boxes,
  968. labels,
  969. overflowing_tokens,
  970. overflowing_token_boxes,
  971. overflowing_labels,
  972. )
  973. def _pad(
  974. self,
  975. encoded_inputs: Union[dict[str, EncodedInput], BatchEncoding],
  976. max_length: Optional[int] = None,
  977. padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
  978. pad_to_multiple_of: Optional[int] = None,
  979. padding_side: Optional[str] = None,
  980. return_attention_mask: Optional[bool] = None,
  981. ) -> dict:
  982. """
  983. Pad encoded inputs (on left/right and up to predefined length or max length in the batch)
  984. Args:
  985. encoded_inputs:
  986. Dictionary of tokenized inputs (`list[int]`) or batch of tokenized inputs (`list[list[int]]`).
  987. max_length: maximum length of the returned list and optionally padding length (see below).
  988. Will truncate by taking into account the special tokens.
  989. padding_strategy: PaddingStrategy to use for padding.
  990. - PaddingStrategy.LONGEST Pad to the longest sequence in the batch
  991. - PaddingStrategy.MAX_LENGTH: Pad to the max length (default)
  992. - PaddingStrategy.DO_NOT_PAD: Do not pad
  993. The tokenizer padding sides are defined in self.padding_side:
  994. - 'left': pads on the left of the sequences
  995. - 'right': pads on the right of the sequences
  996. pad_to_multiple_of: (optional) Integer if set will pad the sequence to a multiple of the provided value.
  997. This is especially useful to enable the use of Tensor Core on NVIDIA hardware with compute capability
  998. `>= 7.5` (Volta).
  999. padding_side (`str`, *optional*):
  1000. The side on which the model should have padding applied. Should be selected between ['right', 'left'].
  1001. Default value is picked from the class attribute of the same name.
  1002. return_attention_mask:
  1003. (optional) Set to False to avoid returning attention mask (default: set to model specifics)
  1004. """
  1005. # Load from model defaults
  1006. if return_attention_mask is None:
  1007. return_attention_mask = "attention_mask" in self.model_input_names
  1008. required_input = encoded_inputs[self.model_input_names[0]]
  1009. if padding_strategy == PaddingStrategy.LONGEST:
  1010. max_length = len(required_input)
  1011. if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0):
  1012. max_length = ((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of
  1013. needs_to_be_padded = padding_strategy != PaddingStrategy.DO_NOT_PAD and len(required_input) != max_length
  1014. # Initialize attention mask if not present.
  1015. if return_attention_mask and "attention_mask" not in encoded_inputs:
  1016. encoded_inputs["attention_mask"] = [1] * len(required_input)
  1017. if needs_to_be_padded:
  1018. difference = max_length - len(required_input)
  1019. padding_side = padding_side if padding_side is not None else self.padding_side
  1020. if padding_side == "right":
  1021. if return_attention_mask:
  1022. encoded_inputs["attention_mask"] = encoded_inputs["attention_mask"] + [0] * difference
  1023. if "token_type_ids" in encoded_inputs:
  1024. encoded_inputs["token_type_ids"] = (
  1025. encoded_inputs["token_type_ids"] + [self.pad_token_type_id] * difference
  1026. )
  1027. if "bbox" in encoded_inputs:
  1028. encoded_inputs["bbox"] = encoded_inputs["bbox"] + [self.pad_token_box] * difference
  1029. if "labels" in encoded_inputs:
  1030. encoded_inputs["labels"] = encoded_inputs["labels"] + [self.pad_token_label] * difference
  1031. if "special_tokens_mask" in encoded_inputs:
  1032. encoded_inputs["special_tokens_mask"] = encoded_inputs["special_tokens_mask"] + [1] * difference
  1033. encoded_inputs[self.model_input_names[0]] = required_input + [self.pad_token_id] * difference
  1034. elif padding_side == "left":
  1035. if return_attention_mask:
  1036. encoded_inputs["attention_mask"] = [0] * difference + encoded_inputs["attention_mask"]
  1037. if "token_type_ids" in encoded_inputs:
  1038. encoded_inputs["token_type_ids"] = [self.pad_token_type_id] * difference + encoded_inputs[
  1039. "token_type_ids"
  1040. ]
  1041. if "bbox" in encoded_inputs:
  1042. encoded_inputs["bbox"] = [self.pad_token_box] * difference + encoded_inputs["bbox"]
  1043. if "labels" in encoded_inputs:
  1044. encoded_inputs["labels"] = [self.pad_token_label] * difference + encoded_inputs["labels"]
  1045. if "special_tokens_mask" in encoded_inputs:
  1046. encoded_inputs["special_tokens_mask"] = [1] * difference + encoded_inputs["special_tokens_mask"]
  1047. encoded_inputs[self.model_input_names[0]] = [self.pad_token_id] * difference + required_input
  1048. else:
  1049. raise ValueError("Invalid padding strategy:" + str(padding_side))
  1050. return encoded_inputs
  1051. __all__ = ["LayoutXLMTokenizer"]