tokenization_layoutlmv2_fast.py 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809
  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. """
  16. Fast tokenization class for LayoutLMv2. It overwrites 2 methods of the slow tokenizer class, namely _batch_encode_plus
  17. and _encode_plus, in which the Rust tokenizer is used.
  18. """
  19. import json
  20. from typing import Dict, List, Optional, Tuple, Union
  21. from tokenizers import normalizers
  22. from ...tokenization_utils_base import (
  23. BatchEncoding,
  24. EncodedInput,
  25. PaddingStrategy,
  26. PreTokenizedInput,
  27. TensorType,
  28. TextInput,
  29. TextInputPair,
  30. TruncationStrategy,
  31. )
  32. from ...tokenization_utils_fast import PreTrainedTokenizerFast
  33. from ...utils import add_end_docstrings, logging
  34. from .tokenization_layoutlmv2 import (
  35. LAYOUTLMV2_ENCODE_KWARGS_DOCSTRING,
  36. LAYOUTLMV2_ENCODE_PLUS_ADDITIONAL_KWARGS_DOCSTRING,
  37. LayoutLMv2Tokenizer,
  38. )
  39. logger = logging.get_logger(__name__)
  40. VOCAB_FILES_NAMES = {"vocab_file": "vocab.txt", "tokenizer_file": "tokenizer.json"}
  41. class LayoutLMv2TokenizerFast(PreTrainedTokenizerFast):
  42. r"""
  43. Construct a "fast" LayoutLMv2 tokenizer (backed by HuggingFace's *tokenizers* library). Based on WordPiece.
  44. This tokenizer inherits from [`PreTrainedTokenizerFast`] which contains most of the main methods. Users should
  45. refer to this superclass for more information regarding those methods.
  46. Args:
  47. vocab_file (`str`):
  48. File containing the vocabulary.
  49. do_lower_case (`bool`, *optional*, defaults to `True`):
  50. Whether or not to lowercase the input when tokenizing.
  51. unk_token (`str`, *optional*, defaults to `"[UNK]"`):
  52. The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
  53. token instead.
  54. sep_token (`str`, *optional*, defaults to `"[SEP]"`):
  55. The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
  56. sequence classification or for a text and a question for question answering. It is also used as the last
  57. token of a sequence built with special tokens.
  58. pad_token (`str`, *optional*, defaults to `"[PAD]"`):
  59. The token used for padding, for example when batching sequences of different lengths.
  60. cls_token (`str`, *optional*, defaults to `"[CLS]"`):
  61. The classifier token which is used when doing sequence classification (classification of the whole sequence
  62. instead of per-token classification). It is the first token of the sequence when built with special tokens.
  63. mask_token (`str`, *optional*, defaults to `"[MASK]"`):
  64. The token used for masking values. This is the token used when training this model with masked language
  65. modeling. This is the token which the model will try to predict.
  66. cls_token_box (`List[int]`, *optional*, defaults to `[0, 0, 0, 0]`):
  67. The bounding box to use for the special [CLS] token.
  68. sep_token_box (`List[int]`, *optional*, defaults to `[1000, 1000, 1000, 1000]`):
  69. The bounding box to use for the special [SEP] token.
  70. pad_token_box (`List[int]`, *optional*, defaults to `[0, 0, 0, 0]`):
  71. The bounding box to use for the special [PAD] token.
  72. pad_token_label (`int`, *optional*, defaults to -100):
  73. The label to use for padding tokens. Defaults to -100, which is the `ignore_index` of PyTorch's
  74. CrossEntropyLoss.
  75. only_label_first_subword (`bool`, *optional*, defaults to `True`):
  76. Whether or not to only label the first subword, in case word labels are provided.
  77. tokenize_chinese_chars (`bool`, *optional*, defaults to `True`):
  78. Whether or not to tokenize Chinese characters. This should likely be deactivated for Japanese (see [this
  79. issue](https://github.com/huggingface/transformers/issues/328)).
  80. strip_accents (`bool`, *optional*):
  81. Whether or not to strip all accents. If this option is not specified, then it will be determined by the
  82. value for `lowercase` (as in the original LayoutLMv2).
  83. """
  84. vocab_files_names = VOCAB_FILES_NAMES
  85. slow_tokenizer_class = LayoutLMv2Tokenizer
  86. def __init__(
  87. self,
  88. vocab_file=None,
  89. tokenizer_file=None,
  90. do_lower_case=True,
  91. unk_token="[UNK]",
  92. sep_token="[SEP]",
  93. pad_token="[PAD]",
  94. cls_token="[CLS]",
  95. mask_token="[MASK]",
  96. cls_token_box=[0, 0, 0, 0],
  97. sep_token_box=[1000, 1000, 1000, 1000],
  98. pad_token_box=[0, 0, 0, 0],
  99. pad_token_label=-100,
  100. only_label_first_subword=True,
  101. tokenize_chinese_chars=True,
  102. strip_accents=None,
  103. **kwargs,
  104. ):
  105. super().__init__(
  106. vocab_file,
  107. tokenizer_file=tokenizer_file,
  108. do_lower_case=do_lower_case,
  109. unk_token=unk_token,
  110. sep_token=sep_token,
  111. pad_token=pad_token,
  112. cls_token=cls_token,
  113. mask_token=mask_token,
  114. cls_token_box=cls_token_box,
  115. sep_token_box=sep_token_box,
  116. pad_token_box=pad_token_box,
  117. pad_token_label=pad_token_label,
  118. only_label_first_subword=only_label_first_subword,
  119. tokenize_chinese_chars=tokenize_chinese_chars,
  120. strip_accents=strip_accents,
  121. **kwargs,
  122. )
  123. pre_tok_state = json.loads(self.backend_tokenizer.normalizer.__getstate__())
  124. if (
  125. pre_tok_state.get("lowercase", do_lower_case) != do_lower_case
  126. or pre_tok_state.get("strip_accents", strip_accents) != strip_accents
  127. ):
  128. pre_tok_class = getattr(normalizers, pre_tok_state.pop("type"))
  129. pre_tok_state["lowercase"] = do_lower_case
  130. pre_tok_state["strip_accents"] = strip_accents
  131. self.backend_tokenizer.normalizer = pre_tok_class(**pre_tok_state)
  132. self.do_lower_case = do_lower_case
  133. # additional properties
  134. self.cls_token_box = cls_token_box
  135. self.sep_token_box = sep_token_box
  136. self.pad_token_box = pad_token_box
  137. self.pad_token_label = pad_token_label
  138. self.only_label_first_subword = only_label_first_subword
  139. @add_end_docstrings(LAYOUTLMV2_ENCODE_KWARGS_DOCSTRING, LAYOUTLMV2_ENCODE_PLUS_ADDITIONAL_KWARGS_DOCSTRING)
  140. def __call__(
  141. self,
  142. text: Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]],
  143. text_pair: Optional[Union[PreTokenizedInput, List[PreTokenizedInput]]] = None,
  144. boxes: Union[List[List[int]], List[List[List[int]]]] = None,
  145. word_labels: Optional[Union[List[int], List[List[int]]]] = None,
  146. add_special_tokens: bool = True,
  147. padding: Union[bool, str, PaddingStrategy] = False,
  148. truncation: Union[bool, str, TruncationStrategy] = None,
  149. max_length: Optional[int] = None,
  150. stride: int = 0,
  151. pad_to_multiple_of: Optional[int] = None,
  152. padding_side: Optional[bool] = None,
  153. return_tensors: Optional[Union[str, TensorType]] = None,
  154. return_token_type_ids: Optional[bool] = None,
  155. return_attention_mask: Optional[bool] = None,
  156. return_overflowing_tokens: bool = False,
  157. return_special_tokens_mask: bool = False,
  158. return_offsets_mapping: bool = False,
  159. return_length: bool = False,
  160. verbose: bool = True,
  161. **kwargs,
  162. ) -> BatchEncoding:
  163. """
  164. Main method to tokenize and prepare for the model one or several sequence(s) or one or several pair(s) of
  165. sequences with word-level normalized bounding boxes and optional labels.
  166. Args:
  167. text (`str`, `List[str]`, `List[List[str]]`):
  168. The sequence or batch of sequences to be encoded. Each sequence can be a string, a list of strings
  169. (words of a single example or questions of a batch of examples) or a list of list of strings (batch of
  170. words).
  171. text_pair (`List[str]`, `List[List[str]]`):
  172. The sequence or batch of sequences to be encoded. Each sequence should be a list of strings
  173. (pretokenized string).
  174. boxes (`List[List[int]]`, `List[List[List[int]]]`):
  175. Word-level bounding boxes. Each bounding box should be normalized to be on a 0-1000 scale.
  176. word_labels (`List[int]`, `List[List[int]]`, *optional*):
  177. Word-level integer labels (for token classification tasks such as FUNSD, CORD).
  178. """
  179. # Input type checking for clearer error
  180. def _is_valid_text_input(t):
  181. if isinstance(t, str):
  182. # Strings are fine
  183. return True
  184. elif isinstance(t, (list, tuple)):
  185. # List are fine as long as they are...
  186. if len(t) == 0:
  187. # ... empty
  188. return True
  189. elif isinstance(t[0], str):
  190. # ... list of strings
  191. return True
  192. elif isinstance(t[0], (list, tuple)):
  193. # ... list with an empty list or with a list of strings
  194. return len(t[0]) == 0 or isinstance(t[0][0], str)
  195. else:
  196. return False
  197. else:
  198. return False
  199. if text_pair is not None:
  200. # in case text + text_pair are provided, text = questions, text_pair = words
  201. if not _is_valid_text_input(text):
  202. raise ValueError("text input must of type `str` (single example) or `List[str]` (batch of examples). ")
  203. if not isinstance(text_pair, (list, tuple)):
  204. raise ValueError(
  205. "Words must be of type `List[str]` (single pretokenized example), "
  206. "or `List[List[str]]` (batch of pretokenized examples)."
  207. )
  208. else:
  209. # in case only text is provided => must be words
  210. if not isinstance(text, (list, tuple)):
  211. raise ValueError(
  212. "Words must be of type `List[str]` (single pretokenized example), "
  213. "or `List[List[str]]` (batch of pretokenized examples)."
  214. )
  215. if text_pair is not None:
  216. is_batched = isinstance(text, (list, tuple))
  217. else:
  218. is_batched = isinstance(text, (list, tuple)) and text and isinstance(text[0], (list, tuple))
  219. words = text if text_pair is None else text_pair
  220. if boxes is None:
  221. raise ValueError("You must provide corresponding bounding boxes")
  222. if is_batched:
  223. if len(words) != len(boxes):
  224. raise ValueError("You must provide words and boxes for an equal amount of examples")
  225. for words_example, boxes_example in zip(words, boxes):
  226. if len(words_example) != len(boxes_example):
  227. raise ValueError("You must provide as many words as there are bounding boxes")
  228. else:
  229. if len(words) != len(boxes):
  230. raise ValueError("You must provide as many words as there are bounding boxes")
  231. if is_batched:
  232. if text_pair is not None and len(text) != len(text_pair):
  233. raise ValueError(
  234. f"batch length of `text`: {len(text)} does not match batch length of `text_pair`:"
  235. f" {len(text_pair)}."
  236. )
  237. batch_text_or_text_pairs = list(zip(text, text_pair)) if text_pair is not None else text
  238. is_pair = bool(text_pair is not None)
  239. return self.batch_encode_plus(
  240. batch_text_or_text_pairs=batch_text_or_text_pairs,
  241. is_pair=is_pair,
  242. boxes=boxes,
  243. word_labels=word_labels,
  244. add_special_tokens=add_special_tokens,
  245. padding=padding,
  246. truncation=truncation,
  247. max_length=max_length,
  248. stride=stride,
  249. pad_to_multiple_of=pad_to_multiple_of,
  250. padding_side=padding_side,
  251. return_tensors=return_tensors,
  252. return_token_type_ids=return_token_type_ids,
  253. return_attention_mask=return_attention_mask,
  254. return_overflowing_tokens=return_overflowing_tokens,
  255. return_special_tokens_mask=return_special_tokens_mask,
  256. return_offsets_mapping=return_offsets_mapping,
  257. return_length=return_length,
  258. verbose=verbose,
  259. **kwargs,
  260. )
  261. else:
  262. return self.encode_plus(
  263. text=text,
  264. text_pair=text_pair,
  265. boxes=boxes,
  266. word_labels=word_labels,
  267. add_special_tokens=add_special_tokens,
  268. padding=padding,
  269. truncation=truncation,
  270. max_length=max_length,
  271. stride=stride,
  272. pad_to_multiple_of=pad_to_multiple_of,
  273. padding_side=padding_side,
  274. return_tensors=return_tensors,
  275. return_token_type_ids=return_token_type_ids,
  276. return_attention_mask=return_attention_mask,
  277. return_overflowing_tokens=return_overflowing_tokens,
  278. return_special_tokens_mask=return_special_tokens_mask,
  279. return_offsets_mapping=return_offsets_mapping,
  280. return_length=return_length,
  281. verbose=verbose,
  282. **kwargs,
  283. )
  284. @add_end_docstrings(LAYOUTLMV2_ENCODE_KWARGS_DOCSTRING, LAYOUTLMV2_ENCODE_PLUS_ADDITIONAL_KWARGS_DOCSTRING)
  285. def batch_encode_plus(
  286. self,
  287. batch_text_or_text_pairs: Union[
  288. List[TextInput],
  289. List[TextInputPair],
  290. List[PreTokenizedInput],
  291. ],
  292. is_pair: bool = None,
  293. boxes: Optional[List[List[List[int]]]] = None,
  294. word_labels: Optional[Union[List[int], List[List[int]]]] = None,
  295. add_special_tokens: bool = True,
  296. padding: Union[bool, str, PaddingStrategy] = False,
  297. truncation: Union[bool, str, TruncationStrategy] = None,
  298. max_length: Optional[int] = None,
  299. stride: int = 0,
  300. pad_to_multiple_of: Optional[int] = None,
  301. padding_side: Optional[bool] = None,
  302. return_tensors: Optional[Union[str, TensorType]] = None,
  303. return_token_type_ids: Optional[bool] = None,
  304. return_attention_mask: Optional[bool] = None,
  305. return_overflowing_tokens: bool = False,
  306. return_special_tokens_mask: bool = False,
  307. return_offsets_mapping: bool = False,
  308. return_length: bool = False,
  309. verbose: bool = True,
  310. **kwargs,
  311. ) -> BatchEncoding:
  312. # Backward compatibility for 'truncation_strategy', 'pad_to_max_length'
  313. padding_strategy, truncation_strategy, max_length, kwargs = self._get_padding_truncation_strategies(
  314. padding=padding,
  315. truncation=truncation,
  316. max_length=max_length,
  317. pad_to_multiple_of=pad_to_multiple_of,
  318. verbose=verbose,
  319. **kwargs,
  320. )
  321. return self._batch_encode_plus(
  322. batch_text_or_text_pairs=batch_text_or_text_pairs,
  323. is_pair=is_pair,
  324. boxes=boxes,
  325. word_labels=word_labels,
  326. add_special_tokens=add_special_tokens,
  327. padding_strategy=padding_strategy,
  328. truncation_strategy=truncation_strategy,
  329. max_length=max_length,
  330. stride=stride,
  331. pad_to_multiple_of=pad_to_multiple_of,
  332. padding_side=padding_side,
  333. return_tensors=return_tensors,
  334. return_token_type_ids=return_token_type_ids,
  335. return_attention_mask=return_attention_mask,
  336. return_overflowing_tokens=return_overflowing_tokens,
  337. return_special_tokens_mask=return_special_tokens_mask,
  338. return_offsets_mapping=return_offsets_mapping,
  339. return_length=return_length,
  340. verbose=verbose,
  341. **kwargs,
  342. )
  343. def tokenize(self, text: str, pair: Optional[str] = None, add_special_tokens: bool = False, **kwargs) -> List[str]:
  344. batched_input = [(text, pair)] if pair else [text]
  345. encodings = self._tokenizer.encode_batch(
  346. batched_input, add_special_tokens=add_special_tokens, is_pretokenized=False, **kwargs
  347. )
  348. return encodings[0].tokens
  349. @add_end_docstrings(LAYOUTLMV2_ENCODE_KWARGS_DOCSTRING, LAYOUTLMV2_ENCODE_PLUS_ADDITIONAL_KWARGS_DOCSTRING)
  350. def encode_plus(
  351. self,
  352. text: Union[TextInput, PreTokenizedInput],
  353. text_pair: Optional[PreTokenizedInput] = None,
  354. boxes: Optional[List[List[int]]] = None,
  355. word_labels: Optional[List[int]] = None,
  356. add_special_tokens: bool = True,
  357. padding: Union[bool, str, PaddingStrategy] = False,
  358. truncation: Union[bool, str, TruncationStrategy] = None,
  359. max_length: Optional[int] = None,
  360. stride: int = 0,
  361. pad_to_multiple_of: Optional[int] = None,
  362. padding_side: Optional[bool] = None,
  363. return_tensors: Optional[Union[str, TensorType]] = None,
  364. return_token_type_ids: Optional[bool] = None,
  365. return_attention_mask: Optional[bool] = None,
  366. return_overflowing_tokens: bool = False,
  367. return_special_tokens_mask: bool = False,
  368. return_offsets_mapping: bool = False,
  369. return_length: bool = False,
  370. verbose: bool = True,
  371. **kwargs,
  372. ) -> BatchEncoding:
  373. """
  374. Tokenize and prepare for the model a sequence or a pair of sequences. .. warning:: This method is deprecated,
  375. `__call__` should be used instead.
  376. Args:
  377. text (`str`, `List[str]`, `List[List[str]]`):
  378. The first sequence to be encoded. This can be a string, a list of strings or a list of list of strings.
  379. text_pair (`List[str]` or `List[int]`, *optional*):
  380. Optional second sequence to be encoded. This can be a list of strings (words of a single example) or a
  381. list of list of strings (words of a batch of examples).
  382. """
  383. # Backward compatibility for 'truncation_strategy', 'pad_to_max_length'
  384. padding_strategy, truncation_strategy, max_length, kwargs = self._get_padding_truncation_strategies(
  385. padding=padding,
  386. truncation=truncation,
  387. max_length=max_length,
  388. pad_to_multiple_of=pad_to_multiple_of,
  389. verbose=verbose,
  390. **kwargs,
  391. )
  392. return self._encode_plus(
  393. text=text,
  394. boxes=boxes,
  395. text_pair=text_pair,
  396. word_labels=word_labels,
  397. add_special_tokens=add_special_tokens,
  398. padding_strategy=padding_strategy,
  399. truncation_strategy=truncation_strategy,
  400. max_length=max_length,
  401. stride=stride,
  402. pad_to_multiple_of=pad_to_multiple_of,
  403. padding_side=padding_side,
  404. return_tensors=return_tensors,
  405. return_token_type_ids=return_token_type_ids,
  406. return_attention_mask=return_attention_mask,
  407. return_overflowing_tokens=return_overflowing_tokens,
  408. return_special_tokens_mask=return_special_tokens_mask,
  409. return_offsets_mapping=return_offsets_mapping,
  410. return_length=return_length,
  411. verbose=verbose,
  412. **kwargs,
  413. )
  414. def _batch_encode_plus(
  415. self,
  416. batch_text_or_text_pairs: Union[
  417. List[TextInput],
  418. List[TextInputPair],
  419. List[PreTokenizedInput],
  420. ],
  421. is_pair: bool = None,
  422. boxes: Optional[List[List[List[int]]]] = None,
  423. word_labels: Optional[List[List[int]]] = None,
  424. add_special_tokens: bool = True,
  425. padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
  426. truncation_strategy: TruncationStrategy = TruncationStrategy.DO_NOT_TRUNCATE,
  427. max_length: Optional[int] = None,
  428. stride: int = 0,
  429. pad_to_multiple_of: Optional[int] = None,
  430. padding_side: Optional[bool] = None,
  431. return_tensors: Optional[str] = None,
  432. return_token_type_ids: Optional[bool] = None,
  433. return_attention_mask: Optional[bool] = None,
  434. return_overflowing_tokens: bool = False,
  435. return_special_tokens_mask: bool = False,
  436. return_offsets_mapping: bool = False,
  437. return_length: bool = False,
  438. verbose: bool = True,
  439. ) -> BatchEncoding:
  440. if not isinstance(batch_text_or_text_pairs, list):
  441. raise TypeError(f"batch_text_or_text_pairs has to be a list (got {type(batch_text_or_text_pairs)})")
  442. # Set the truncation and padding strategy and restore the initial configuration
  443. self.set_truncation_and_padding(
  444. padding_strategy=padding_strategy,
  445. truncation_strategy=truncation_strategy,
  446. max_length=max_length,
  447. stride=stride,
  448. pad_to_multiple_of=pad_to_multiple_of,
  449. padding_side=padding_side,
  450. )
  451. if is_pair:
  452. batch_text_or_text_pairs = [(text.split(), text_pair) for text, text_pair in batch_text_or_text_pairs]
  453. encodings = self._tokenizer.encode_batch(
  454. batch_text_or_text_pairs,
  455. add_special_tokens=add_special_tokens,
  456. is_pretokenized=True, # we set this to True as LayoutLMv2 always expects pretokenized inputs
  457. )
  458. # Convert encoding to dict
  459. # `Tokens` has type: Tuple[
  460. # List[Dict[str, List[List[int]]]] or List[Dict[str, 2D-Tensor]],
  461. # List[EncodingFast]
  462. # ]
  463. # with nested dimensions corresponding to batch, overflows, sequence length
  464. tokens_and_encodings = [
  465. self._convert_encoding(
  466. encoding=encoding,
  467. return_token_type_ids=return_token_type_ids,
  468. return_attention_mask=return_attention_mask,
  469. return_overflowing_tokens=return_overflowing_tokens,
  470. return_special_tokens_mask=return_special_tokens_mask,
  471. return_offsets_mapping=True
  472. if word_labels is not None
  473. else return_offsets_mapping, # we use offsets to create the labels
  474. return_length=return_length,
  475. verbose=verbose,
  476. )
  477. for encoding in encodings
  478. ]
  479. # Convert the output to have dict[list] from list[dict] and remove the additional overflows dimension
  480. # From (variable) shape (batch, overflows, sequence length) to ~ (batch * overflows, sequence length)
  481. # (we say ~ because the number of overflow varies with the example in the batch)
  482. #
  483. # To match each overflowing sample with the original sample in the batch
  484. # we add an overflow_to_sample_mapping array (see below)
  485. sanitized_tokens = {}
  486. for key in tokens_and_encodings[0][0].keys():
  487. stack = [e for item, _ in tokens_and_encodings for e in item[key]]
  488. sanitized_tokens[key] = stack
  489. sanitized_encodings = [e for _, item in tokens_and_encodings for e in item]
  490. # If returning overflowing tokens, we need to return a mapping
  491. # from the batch idx to the original sample
  492. if return_overflowing_tokens:
  493. overflow_to_sample_mapping = []
  494. for i, (toks, _) in enumerate(tokens_and_encodings):
  495. overflow_to_sample_mapping += [i] * len(toks["input_ids"])
  496. sanitized_tokens["overflow_to_sample_mapping"] = overflow_to_sample_mapping
  497. for input_ids in sanitized_tokens["input_ids"]:
  498. self._eventual_warn_about_too_long_sequence(input_ids, max_length, verbose)
  499. # create the token boxes
  500. token_boxes = []
  501. for batch_index in range(len(sanitized_tokens["input_ids"])):
  502. if return_overflowing_tokens:
  503. original_index = sanitized_tokens["overflow_to_sample_mapping"][batch_index]
  504. else:
  505. original_index = batch_index
  506. token_boxes_example = []
  507. for id, sequence_id, word_id in zip(
  508. sanitized_tokens["input_ids"][batch_index],
  509. sanitized_encodings[batch_index].sequence_ids,
  510. sanitized_encodings[batch_index].word_ids,
  511. ):
  512. if word_id is not None:
  513. if is_pair and sequence_id == 0:
  514. token_boxes_example.append(self.pad_token_box)
  515. else:
  516. token_boxes_example.append(boxes[original_index][word_id])
  517. else:
  518. if id == self.cls_token_id:
  519. token_boxes_example.append(self.cls_token_box)
  520. elif id == self.sep_token_id:
  521. token_boxes_example.append(self.sep_token_box)
  522. elif id == self.pad_token_id:
  523. token_boxes_example.append(self.pad_token_box)
  524. else:
  525. raise ValueError("Id not recognized")
  526. token_boxes.append(token_boxes_example)
  527. sanitized_tokens["bbox"] = token_boxes
  528. # optionally, create the labels
  529. if word_labels is not None:
  530. labels = []
  531. for batch_index in range(len(sanitized_tokens["input_ids"])):
  532. if return_overflowing_tokens:
  533. original_index = sanitized_tokens["overflow_to_sample_mapping"][batch_index]
  534. else:
  535. original_index = batch_index
  536. labels_example = []
  537. for id, offset, word_id in zip(
  538. sanitized_tokens["input_ids"][batch_index],
  539. sanitized_tokens["offset_mapping"][batch_index],
  540. sanitized_encodings[batch_index].word_ids,
  541. ):
  542. if word_id is not None:
  543. if self.only_label_first_subword:
  544. if offset[0] == 0:
  545. # Use the real label id for the first token of the word, and padding ids for the remaining tokens
  546. labels_example.append(word_labels[original_index][word_id])
  547. else:
  548. labels_example.append(self.pad_token_label)
  549. else:
  550. labels_example.append(word_labels[original_index][word_id])
  551. else:
  552. labels_example.append(self.pad_token_label)
  553. labels.append(labels_example)
  554. sanitized_tokens["labels"] = labels
  555. # finally, remove offsets if the user didn't want them
  556. if not return_offsets_mapping:
  557. del sanitized_tokens["offset_mapping"]
  558. return BatchEncoding(sanitized_tokens, sanitized_encodings, tensor_type=return_tensors)
  559. def _encode_plus(
  560. self,
  561. text: Union[TextInput, PreTokenizedInput],
  562. text_pair: Optional[PreTokenizedInput] = None,
  563. boxes: Optional[List[List[int]]] = None,
  564. word_labels: Optional[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[bool] = None,
  572. return_tensors: Optional[bool] = 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_offsets_mapping: bool = False,
  578. return_length: bool = False,
  579. verbose: bool = True,
  580. **kwargs,
  581. ) -> BatchEncoding:
  582. # make it a batched input
  583. # 2 options:
  584. # 1) only text, in case text must be a list of str
  585. # 2) text + text_pair, in which case text = str and text_pair a list of str
  586. batched_input = [(text, text_pair)] if text_pair else [text]
  587. batched_boxes = [boxes]
  588. batched_word_labels = [word_labels] if word_labels is not None else None
  589. batched_output = self._batch_encode_plus(
  590. batched_input,
  591. is_pair=bool(text_pair is not None),
  592. boxes=batched_boxes,
  593. word_labels=batched_word_labels,
  594. add_special_tokens=add_special_tokens,
  595. padding_strategy=padding_strategy,
  596. truncation_strategy=truncation_strategy,
  597. max_length=max_length,
  598. stride=stride,
  599. pad_to_multiple_of=pad_to_multiple_of,
  600. padding_side=padding_side,
  601. return_tensors=return_tensors,
  602. return_token_type_ids=return_token_type_ids,
  603. return_attention_mask=return_attention_mask,
  604. return_overflowing_tokens=return_overflowing_tokens,
  605. return_special_tokens_mask=return_special_tokens_mask,
  606. return_offsets_mapping=return_offsets_mapping,
  607. return_length=return_length,
  608. verbose=verbose,
  609. **kwargs,
  610. )
  611. # Return tensor is None, then we can remove the leading batch axis
  612. # Overflowing tokens are returned as a batch of output so we keep them in this case
  613. if return_tensors is None and not return_overflowing_tokens:
  614. batched_output = BatchEncoding(
  615. {
  616. key: value[0] if len(value) > 0 and isinstance(value[0], list) else value
  617. for key, value in batched_output.items()
  618. },
  619. batched_output.encodings,
  620. )
  621. self._eventual_warn_about_too_long_sequence(batched_output["input_ids"], max_length, verbose)
  622. return batched_output
  623. def _pad(
  624. self,
  625. encoded_inputs: Union[Dict[str, EncodedInput], BatchEncoding],
  626. max_length: Optional[int] = None,
  627. padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
  628. pad_to_multiple_of: Optional[int] = None,
  629. padding_side: Optional[bool] = None,
  630. return_attention_mask: Optional[bool] = None,
  631. ) -> dict:
  632. """
  633. Pad encoded inputs (on left/right and up to predefined length or max length in the batch)
  634. Args:
  635. encoded_inputs:
  636. Dictionary of tokenized inputs (`List[int]`) or batch of tokenized inputs (`List[List[int]]`).
  637. max_length: maximum length of the returned list and optionally padding length (see below).
  638. Will truncate by taking into account the special tokens.
  639. padding_strategy: PaddingStrategy to use for padding.
  640. - PaddingStrategy.LONGEST Pad to the longest sequence in the batch
  641. - PaddingStrategy.MAX_LENGTH: Pad to the max length (default)
  642. - PaddingStrategy.DO_NOT_PAD: Do not pad
  643. The tokenizer padding sides are defined in self.padding_side:
  644. - 'left': pads on the left of the sequences
  645. - 'right': pads on the right of the sequences
  646. pad_to_multiple_of: (optional) Integer if set will pad the sequence to a multiple of the provided value.
  647. This is especially useful to enable the use of Tensor Core on NVIDIA hardware with compute capability
  648. `>= 7.5` (Volta).
  649. padding_side:
  650. The side on which the model should have padding applied. Should be selected between ['right', 'left'].
  651. Default value is picked from the class attribute of the same name.
  652. return_attention_mask:
  653. (optional) Set to False to avoid returning attention mask (default: set to model specifics)
  654. """
  655. # Load from model defaults
  656. if return_attention_mask is None:
  657. return_attention_mask = "attention_mask" in self.model_input_names
  658. required_input = encoded_inputs[self.model_input_names[0]]
  659. if padding_strategy == PaddingStrategy.LONGEST:
  660. max_length = len(required_input)
  661. if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0):
  662. max_length = ((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of
  663. needs_to_be_padded = padding_strategy != PaddingStrategy.DO_NOT_PAD and len(required_input) != max_length
  664. # Initialize attention mask if not present.
  665. if return_attention_mask and "attention_mask" not in encoded_inputs:
  666. encoded_inputs["attention_mask"] = [1] * len(required_input)
  667. if needs_to_be_padded:
  668. difference = max_length - len(required_input)
  669. padding_side = padding_side if padding_side is not None else self.padding_side
  670. if padding_side == "right":
  671. if return_attention_mask:
  672. encoded_inputs["attention_mask"] = encoded_inputs["attention_mask"] + [0] * difference
  673. if "token_type_ids" in encoded_inputs:
  674. encoded_inputs["token_type_ids"] = (
  675. encoded_inputs["token_type_ids"] + [self.pad_token_type_id] * difference
  676. )
  677. if "bbox" in encoded_inputs:
  678. encoded_inputs["bbox"] = encoded_inputs["bbox"] + [self.pad_token_box] * difference
  679. if "labels" in encoded_inputs:
  680. encoded_inputs["labels"] = encoded_inputs["labels"] + [self.pad_token_label] * difference
  681. if "special_tokens_mask" in encoded_inputs:
  682. encoded_inputs["special_tokens_mask"] = encoded_inputs["special_tokens_mask"] + [1] * difference
  683. encoded_inputs[self.model_input_names[0]] = required_input + [self.pad_token_id] * difference
  684. elif padding_side == "left":
  685. if return_attention_mask:
  686. encoded_inputs["attention_mask"] = [0] * difference + encoded_inputs["attention_mask"]
  687. if "token_type_ids" in encoded_inputs:
  688. encoded_inputs["token_type_ids"] = [self.pad_token_type_id] * difference + encoded_inputs[
  689. "token_type_ids"
  690. ]
  691. if "bbox" in encoded_inputs:
  692. encoded_inputs["bbox"] = [self.pad_token_box] * difference + encoded_inputs["bbox"]
  693. if "labels" in encoded_inputs:
  694. encoded_inputs["labels"] = [self.pad_token_label] * difference + encoded_inputs["labels"]
  695. if "special_tokens_mask" in encoded_inputs:
  696. encoded_inputs["special_tokens_mask"] = [1] * difference + encoded_inputs["special_tokens_mask"]
  697. encoded_inputs[self.model_input_names[0]] = [self.pad_token_id] * difference + required_input
  698. else:
  699. raise ValueError("Invalid padding strategy:" + str(padding_side))
  700. return encoded_inputs
  701. def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
  702. """
  703. Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
  704. adding special tokens. A BERT sequence has the following format:
  705. - single sequence: `[CLS] X [SEP]`
  706. - pair of sequences: `[CLS] A [SEP] B [SEP]`
  707. Args:
  708. token_ids_0 (`List[int]`):
  709. List of IDs to which the special tokens will be added.
  710. token_ids_1 (`List[int]`, *optional*):
  711. Optional second list of IDs for sequence pairs.
  712. Returns:
  713. `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
  714. """
  715. output = [self.cls_token_id] + token_ids_0 + [self.sep_token_id]
  716. if token_ids_1:
  717. output += token_ids_1 + [self.sep_token_id]
  718. return output
  719. def create_token_type_ids_from_sequences(
  720. self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
  721. ) -> List[int]:
  722. """
  723. Create a mask from the two sequences passed to be used in a sequence-pair classification task. A BERT sequence
  724. pair mask has the following format: :: 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 | first sequence | second
  725. sequence | If `token_ids_1` is `None`, this method only returns the first portion of the mask (0s).
  726. Args:
  727. token_ids_0 (`List[int]`):
  728. List of IDs.
  729. token_ids_1 (`List[int]`, *optional*):
  730. Optional second list of IDs for sequence pairs.
  731. Returns:
  732. `List[int]`: List of [token type IDs](../glossary#token-type-ids) according to the given sequence(s).
  733. """
  734. sep = [self.sep_token_id]
  735. cls = [self.cls_token_id]
  736. if token_ids_1 is None:
  737. return len(cls + token_ids_0 + sep) * [0]
  738. return len(cls + token_ids_0 + sep) * [0] + len(token_ids_1 + sep) * [1]
  739. def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
  740. files = self._tokenizer.model.save(save_directory, name=filename_prefix)
  741. return tuple(files)