tokenization_layoutxlm.py 45 KB

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