tokenization_layoutlmv2.py 70 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545
  1. # coding=utf-8
  2. # Copyright Microsoft Research and The HuggingFace Inc. team. All rights reserved.
  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 class for LayoutLMv2."""
  16. import collections
  17. import os
  18. import sys
  19. import unicodedata
  20. from typing import Optional, Union
  21. from ...tokenization_utils import AddedToken, PreTrainedTokenizer, _is_control, _is_punctuation, _is_whitespace
  22. from ...tokenization_utils_base import (
  23. BatchEncoding,
  24. EncodedInput,
  25. PreTokenizedInput,
  26. TextInput,
  27. TextInputPair,
  28. TruncationStrategy,
  29. )
  30. from ...utils import PaddingStrategy, TensorType, add_end_docstrings, logging
  31. logger = logging.get_logger(__name__)
  32. VOCAB_FILES_NAMES = {"vocab_file": "vocab.txt"}
  33. LAYOUTLMV2_ENCODE_KWARGS_DOCSTRING = r"""
  34. add_special_tokens (`bool`, *optional*, defaults to `True`):
  35. Whether or not to encode the sequences with the special tokens relative to their model.
  36. padding (`bool`, `str` or [`~file_utils.PaddingStrategy`], *optional*, defaults to `False`):
  37. Activates and controls padding. Accepts the following values:
  38. - `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single
  39. sequence if provided).
  40. - `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum
  41. acceptable input length for the model if that argument is not provided.
  42. - `False` or `'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of different
  43. lengths).
  44. truncation (`bool`, `str` or [`~tokenization_utils_base.TruncationStrategy`], *optional*, defaults to `False`):
  45. Activates and controls truncation. Accepts the following values:
  46. - `True` or `'longest_first'`: Truncate to a maximum length specified with the argument `max_length` or
  47. to the maximum acceptable input length for the model if that argument is not provided. This will
  48. truncate token by token, removing a token from the longest sequence in the pair if a pair of
  49. sequences (or a batch of pairs) is provided.
  50. - `'only_first'`: Truncate to a maximum length specified with the argument `max_length` or to the
  51. maximum acceptable input length for the model if that argument is not provided. This will only
  52. truncate the first sequence of a pair if a pair of sequences (or a batch of pairs) is provided.
  53. - `'only_second'`: 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 second sequence of a pair if a pair of sequences (or a batch of pairs) is provided.
  56. - `False` or `'do_not_truncate'` (default): No truncation (i.e., can output batch with sequence lengths
  57. greater than the model maximum admissible input size).
  58. max_length (`int`, *optional*):
  59. Controls the maximum length to use by one of the truncation/padding parameters.
  60. If left unset or set to `None`, this will use the predefined model maximum length if a maximum length
  61. is required by one of the truncation/padding parameters. If the model has no specific maximum input
  62. length (like XLNet) truncation/padding to a maximum length will be deactivated.
  63. stride (`int`, *optional*, defaults to 0):
  64. If set to a number along with `max_length`, the overflowing tokens returned when
  65. `return_overflowing_tokens=True` will contain some tokens from the end of the truncated sequence
  66. returned to provide some overlap between truncated and overflowing sequences. The value of this
  67. argument defines the number of overlapping tokens.
  68. pad_to_multiple_of (`int`, *optional*):
  69. If set will pad the sequence to a multiple of the provided value. This is especially useful to enable
  70. the use of Tensor Cores on NVIDIA hardware with compute capability `>= 7.5` (Volta).
  71. return_tensors (`str` or [`~file_utils.TensorType`], *optional*):
  72. If set, will return tensors instead of list of python integers. Acceptable values are:
  73. - `'tf'`: Return TensorFlow `tf.constant` objects.
  74. - `'pt'`: Return PyTorch `torch.Tensor` objects.
  75. - `'np'`: Return Numpy `np.ndarray` objects.
  76. """
  77. LAYOUTLMV2_ENCODE_PLUS_ADDITIONAL_KWARGS_DOCSTRING = r"""
  78. return_token_type_ids (`bool`, *optional*):
  79. Whether to return token type IDs. If left to the default, will return the token type IDs according to
  80. the specific tokenizer's default, defined by the `return_outputs` attribute.
  81. [What are token type IDs?](../glossary#token-type-ids)
  82. return_attention_mask (`bool`, *optional*):
  83. Whether to return the attention mask. If left to the default, will return the attention mask according
  84. to the specific tokenizer's default, defined by the `return_outputs` attribute.
  85. [What are attention masks?](../glossary#attention-mask)
  86. return_overflowing_tokens (`bool`, *optional*, defaults to `False`):
  87. Whether or not to return overflowing token sequences. If a pair of sequences of input ids (or a batch
  88. of pairs) is provided with `truncation_strategy = longest_first` or `True`, an error is raised instead
  89. of returning overflowing tokens.
  90. return_special_tokens_mask (`bool`, *optional*, defaults to `False`):
  91. Whether or not to return special tokens mask information.
  92. return_offsets_mapping (`bool`, *optional*, defaults to `False`):
  93. Whether or not to return `(char_start, char_end)` for each token.
  94. This is only available on fast tokenizers inheriting from [`PreTrainedTokenizerFast`], if using
  95. Python's tokenizer, this method will raise `NotImplementedError`.
  96. return_length (`bool`, *optional*, defaults to `False`):
  97. Whether or not to return the lengths of the encoded inputs.
  98. verbose (`bool`, *optional*, defaults to `True`):
  99. Whether or not to print more information and warnings.
  100. **kwargs: passed to the `self.tokenize()` method
  101. Return:
  102. [`BatchEncoding`]: A [`BatchEncoding`] with the following fields:
  103. - **input_ids** -- List of token ids to be fed to a model.
  104. [What are input IDs?](../glossary#input-ids)
  105. - **bbox** -- List of bounding boxes to be fed to a model.
  106. - **token_type_ids** -- List of token type ids to be fed to a model (when `return_token_type_ids=True` or
  107. if *"token_type_ids"* is in `self.model_input_names`).
  108. [What are token type IDs?](../glossary#token-type-ids)
  109. - **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
  110. `return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names`).
  111. [What are attention masks?](../glossary#attention-mask)
  112. - **labels** -- List of labels to be fed to a model. (when `word_labels` is specified).
  113. - **overflowing_tokens** -- List of overflowing tokens sequences (when a `max_length` is specified and
  114. `return_overflowing_tokens=True`).
  115. - **num_truncated_tokens** -- Number of tokens truncated (when a `max_length` is specified and
  116. `return_overflowing_tokens=True`).
  117. - **special_tokens_mask** -- List of 0s and 1s, with 1 specifying added special tokens and 0 specifying
  118. regular sequence tokens (when `add_special_tokens=True` and `return_special_tokens_mask=True`).
  119. - **length** -- The length of the inputs (when `return_length=True`).
  120. """
  121. def load_vocab(vocab_file):
  122. """Loads a vocabulary file into a dictionary."""
  123. vocab = collections.OrderedDict()
  124. with open(vocab_file, "r", encoding="utf-8") as reader:
  125. tokens = reader.readlines()
  126. for index, token in enumerate(tokens):
  127. token = token.rstrip("\n")
  128. vocab[token] = index
  129. return vocab
  130. def whitespace_tokenize(text):
  131. """Runs basic whitespace cleaning and splitting on a piece of text."""
  132. text = text.strip()
  133. if not text:
  134. return []
  135. tokens = text.split()
  136. return tokens
  137. table = dict.fromkeys(i for i in range(sys.maxunicode) if unicodedata.category(chr(i)).startswith("P"))
  138. def subfinder(mylist, pattern):
  139. matches = []
  140. indices = []
  141. for idx, i in enumerate(range(len(mylist))):
  142. if mylist[i] == pattern[0] and mylist[i : i + len(pattern)] == pattern:
  143. matches.append(pattern)
  144. indices.append(idx)
  145. if matches:
  146. return matches[0], indices[0]
  147. else:
  148. return None, 0
  149. class LayoutLMv2Tokenizer(PreTrainedTokenizer):
  150. r"""
  151. Construct a LayoutLMv2 tokenizer. Based on WordPiece. [`LayoutLMv2Tokenizer`] can be used to turn words, word-level
  152. bounding boxes and optional word labels to token-level `input_ids`, `attention_mask`, `token_type_ids`, `bbox`, and
  153. optional `labels` (for token classification).
  154. This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
  155. this superclass for more information regarding those methods.
  156. [`LayoutLMv2Tokenizer`] runs end-to-end tokenization: punctuation splitting and wordpiece. It also turns the
  157. word-level bounding boxes into token-level bounding boxes.
  158. """
  159. vocab_files_names = VOCAB_FILES_NAMES
  160. def __init__(
  161. self,
  162. vocab_file,
  163. do_lower_case=True,
  164. do_basic_tokenize=True,
  165. never_split=None,
  166. unk_token="[UNK]",
  167. sep_token="[SEP]",
  168. pad_token="[PAD]",
  169. cls_token="[CLS]",
  170. mask_token="[MASK]",
  171. cls_token_box=[0, 0, 0, 0],
  172. sep_token_box=[1000, 1000, 1000, 1000],
  173. pad_token_box=[0, 0, 0, 0],
  174. pad_token_label=-100,
  175. only_label_first_subword=True,
  176. tokenize_chinese_chars=True,
  177. strip_accents=None,
  178. model_max_length: int = 512,
  179. additional_special_tokens: Optional[list[str]] = None,
  180. **kwargs,
  181. ):
  182. sep_token = AddedToken(sep_token, special=True) if isinstance(sep_token, str) else sep_token
  183. unk_token = AddedToken(unk_token, special=True) if isinstance(unk_token, str) else unk_token
  184. pad_token = AddedToken(pad_token, special=True) if isinstance(pad_token, str) else pad_token
  185. cls_token = AddedToken(cls_token, special=True) if isinstance(cls_token, str) else cls_token
  186. mask_token = AddedToken(mask_token, special=True) if isinstance(mask_token, str) else mask_token
  187. if not os.path.isfile(vocab_file):
  188. raise ValueError(
  189. f"Can't find a vocabulary file at path '{vocab_file}'. To load the vocabulary from a Google pretrained"
  190. " model use `tokenizer = BertTokenizer.from_pretrained(PRETRAINED_MODEL_NAME)`"
  191. )
  192. self.vocab = load_vocab(vocab_file)
  193. self.ids_to_tokens = collections.OrderedDict([(ids, tok) for tok, ids in self.vocab.items()])
  194. self.do_basic_tokenize = do_basic_tokenize
  195. if do_basic_tokenize:
  196. self.basic_tokenizer = BasicTokenizer(
  197. do_lower_case=do_lower_case,
  198. never_split=never_split,
  199. tokenize_chinese_chars=tokenize_chinese_chars,
  200. strip_accents=strip_accents,
  201. )
  202. self.wordpiece_tokenizer = WordpieceTokenizer(vocab=self.vocab, unk_token=str(unk_token))
  203. # additional properties
  204. self.cls_token_box = cls_token_box
  205. self.sep_token_box = sep_token_box
  206. self.pad_token_box = pad_token_box
  207. self.pad_token_label = pad_token_label
  208. self.only_label_first_subword = only_label_first_subword
  209. super().__init__(
  210. do_lower_case=do_lower_case,
  211. do_basic_tokenize=do_basic_tokenize,
  212. never_split=never_split,
  213. unk_token=unk_token,
  214. sep_token=sep_token,
  215. pad_token=pad_token,
  216. cls_token=cls_token,
  217. mask_token=mask_token,
  218. cls_token_box=cls_token_box,
  219. sep_token_box=sep_token_box,
  220. pad_token_box=pad_token_box,
  221. pad_token_label=pad_token_label,
  222. only_label_first_subword=only_label_first_subword,
  223. tokenize_chinese_chars=tokenize_chinese_chars,
  224. strip_accents=strip_accents,
  225. model_max_length=model_max_length,
  226. additional_special_tokens=additional_special_tokens,
  227. **kwargs,
  228. )
  229. @property
  230. def do_lower_case(self):
  231. return self.basic_tokenizer.do_lower_case
  232. @property
  233. def vocab_size(self):
  234. return len(self.vocab)
  235. def get_vocab(self):
  236. return dict(self.vocab, **self.added_tokens_encoder)
  237. def _tokenize(self, text):
  238. split_tokens = []
  239. if self.do_basic_tokenize:
  240. for token in self.basic_tokenizer.tokenize(text, never_split=self.all_special_tokens):
  241. # If the token is part of the never_split set
  242. if token in self.basic_tokenizer.never_split:
  243. split_tokens.append(token)
  244. else:
  245. split_tokens += self.wordpiece_tokenizer.tokenize(token)
  246. else:
  247. split_tokens = self.wordpiece_tokenizer.tokenize(text)
  248. return split_tokens
  249. def _convert_token_to_id(self, token):
  250. """Converts a token (str) in an id using the vocab."""
  251. return self.vocab.get(token, self.vocab.get(self.unk_token))
  252. def _convert_id_to_token(self, index):
  253. """Converts an index (integer) in a token (str) using the vocab."""
  254. return self.ids_to_tokens.get(index, self.unk_token)
  255. def convert_tokens_to_string(self, tokens):
  256. """Converts a sequence of tokens (string) in a single string."""
  257. out_string = " ".join(tokens).replace(" ##", "").strip()
  258. return out_string
  259. def build_inputs_with_special_tokens(
  260. self, token_ids_0: list[int], token_ids_1: Optional[list[int]] = None
  261. ) -> list[int]:
  262. """
  263. Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
  264. adding special tokens. A BERT sequence has the following format:
  265. - single sequence: `[CLS] X [SEP]`
  266. - pair of sequences: `[CLS] A [SEP] B [SEP]`
  267. Args:
  268. token_ids_0 (`List[int]`):
  269. List of IDs to which the special tokens will be added.
  270. token_ids_1 (`List[int]`, *optional*):
  271. Optional second list of IDs for sequence pairs.
  272. Returns:
  273. `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
  274. """
  275. if token_ids_1 is None:
  276. return [self.cls_token_id] + token_ids_0 + [self.sep_token_id]
  277. cls = [self.cls_token_id]
  278. sep = [self.sep_token_id]
  279. return cls + token_ids_0 + sep + token_ids_1 + sep
  280. def get_special_tokens_mask(
  281. self, token_ids_0: list[int], token_ids_1: Optional[list[int]] = None, already_has_special_tokens: bool = False
  282. ) -> list[int]:
  283. """
  284. Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
  285. special tokens using the tokenizer `prepare_for_model` method.
  286. Args:
  287. token_ids_0 (`List[int]`):
  288. List of IDs.
  289. token_ids_1 (`List[int]`, *optional*):
  290. Optional second list of IDs for sequence pairs.
  291. already_has_special_tokens (`bool`, *optional*, defaults to `False`):
  292. Whether or not the token list is already formatted with special tokens for the model.
  293. Returns:
  294. `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
  295. """
  296. if already_has_special_tokens:
  297. return super().get_special_tokens_mask(
  298. token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
  299. )
  300. if token_ids_1 is not None:
  301. return [1] + ([0] * len(token_ids_0)) + [1] + ([0] * len(token_ids_1)) + [1]
  302. return [1] + ([0] * len(token_ids_0)) + [1]
  303. def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> tuple[str]:
  304. index = 0
  305. if os.path.isdir(save_directory):
  306. vocab_file = os.path.join(
  307. save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
  308. )
  309. else:
  310. vocab_file = (filename_prefix + "-" if filename_prefix else "") + save_directory
  311. with open(vocab_file, "w", encoding="utf-8") as writer:
  312. for token, token_index in sorted(self.vocab.items(), key=lambda kv: kv[1]):
  313. if index != token_index:
  314. logger.warning(
  315. f"Saving vocabulary to {vocab_file}: vocabulary indices are not consecutive."
  316. " Please check that the vocabulary is not corrupted!"
  317. )
  318. index = token_index
  319. writer.write(token + "\n")
  320. index += 1
  321. return (vocab_file,)
  322. @add_end_docstrings(LAYOUTLMV2_ENCODE_KWARGS_DOCSTRING, LAYOUTLMV2_ENCODE_PLUS_ADDITIONAL_KWARGS_DOCSTRING)
  323. def __call__(
  324. self,
  325. text: Union[TextInput, PreTokenizedInput, list[TextInput], list[PreTokenizedInput]],
  326. text_pair: Optional[Union[PreTokenizedInput, list[PreTokenizedInput]]] = None,
  327. boxes: Optional[Union[list[list[int]], list[list[list[int]]]]] = None,
  328. word_labels: Optional[Union[list[int], list[list[int]]]] = None,
  329. add_special_tokens: bool = True,
  330. padding: Union[bool, str, PaddingStrategy] = False,
  331. truncation: Union[bool, str, TruncationStrategy] = None,
  332. max_length: Optional[int] = None,
  333. stride: int = 0,
  334. pad_to_multiple_of: Optional[int] = None,
  335. padding_side: Optional[str] = None,
  336. return_tensors: Optional[Union[str, TensorType]] = None,
  337. return_token_type_ids: Optional[bool] = None,
  338. return_attention_mask: Optional[bool] = None,
  339. return_overflowing_tokens: bool = False,
  340. return_special_tokens_mask: bool = False,
  341. return_offsets_mapping: bool = False,
  342. return_length: bool = False,
  343. verbose: bool = True,
  344. **kwargs,
  345. ) -> BatchEncoding:
  346. """
  347. Main method to tokenize and prepare for the model one or several sequence(s) or one or several pair(s) of
  348. sequences with word-level normalized bounding boxes and optional labels.
  349. Args:
  350. text (`str`, `List[str]`, `List[List[str]]`):
  351. The sequence or batch of sequences to be encoded. Each sequence can be a string, a list of strings
  352. (words of a single example or questions of a batch of examples) or a list of list of strings (batch of
  353. words).
  354. text_pair (`List[str]`, `List[List[str]]`):
  355. The sequence or batch of sequences to be encoded. Each sequence should be a list of strings
  356. (pretokenized string).
  357. boxes (`List[List[int]]`, `List[List[List[int]]]`):
  358. Word-level bounding boxes. Each bounding box should be normalized to be on a 0-1000 scale.
  359. word_labels (`List[int]`, `List[List[int]]`, *optional*):
  360. Word-level integer labels (for token classification tasks such as FUNSD, CORD).
  361. """
  362. # Input type checking for clearer error
  363. def _is_valid_text_input(t):
  364. if isinstance(t, str):
  365. # Strings are fine
  366. return True
  367. elif isinstance(t, (list, tuple)):
  368. # List are fine as long as they are...
  369. if len(t) == 0:
  370. # ... empty
  371. return True
  372. elif isinstance(t[0], str):
  373. # ... list of strings
  374. return True
  375. elif isinstance(t[0], (list, tuple)):
  376. # ... list with an empty list or with a list of strings
  377. return len(t[0]) == 0 or isinstance(t[0][0], str)
  378. else:
  379. return False
  380. else:
  381. return False
  382. if text_pair is not None:
  383. # in case text + text_pair are provided, text = questions, text_pair = words
  384. if not _is_valid_text_input(text):
  385. raise ValueError("text input must of type `str` (single example) or `List[str]` (batch of examples). ")
  386. if not isinstance(text_pair, (list, tuple)):
  387. raise ValueError(
  388. "Words must be of type `List[str]` (single pretokenized example), "
  389. "or `List[List[str]]` (batch of pretokenized examples)."
  390. )
  391. else:
  392. # in case only text is provided => must be words
  393. if not isinstance(text, (list, tuple)):
  394. raise ValueError(
  395. "Words must be of type `List[str]` (single pretokenized example), "
  396. "or `List[List[str]]` (batch of pretokenized examples)."
  397. )
  398. if text_pair is not None:
  399. is_batched = isinstance(text, (list, tuple))
  400. else:
  401. is_batched = isinstance(text, (list, tuple)) and text and isinstance(text[0], (list, tuple))
  402. words = text if text_pair is None else text_pair
  403. if boxes is None:
  404. raise ValueError("You must provide corresponding bounding boxes")
  405. if is_batched:
  406. if len(words) != len(boxes):
  407. raise ValueError("You must provide words and boxes for an equal amount of examples")
  408. for words_example, boxes_example in zip(words, boxes):
  409. if len(words_example) != len(boxes_example):
  410. raise ValueError("You must provide as many words as there are bounding boxes")
  411. else:
  412. if len(words) != len(boxes):
  413. raise ValueError("You must provide as many words as there are bounding boxes")
  414. if is_batched:
  415. if text_pair is not None and len(text) != len(text_pair):
  416. raise ValueError(
  417. f"batch length of `text`: {len(text)} does not match batch length of `text_pair`:"
  418. f" {len(text_pair)}."
  419. )
  420. batch_text_or_text_pairs = list(zip(text, text_pair)) if text_pair is not None else text
  421. is_pair = bool(text_pair is not None)
  422. return self.batch_encode_plus(
  423. batch_text_or_text_pairs=batch_text_or_text_pairs,
  424. is_pair=is_pair,
  425. boxes=boxes,
  426. word_labels=word_labels,
  427. add_special_tokens=add_special_tokens,
  428. padding=padding,
  429. truncation=truncation,
  430. max_length=max_length,
  431. stride=stride,
  432. pad_to_multiple_of=pad_to_multiple_of,
  433. padding_side=padding_side,
  434. return_tensors=return_tensors,
  435. return_token_type_ids=return_token_type_ids,
  436. return_attention_mask=return_attention_mask,
  437. return_overflowing_tokens=return_overflowing_tokens,
  438. return_special_tokens_mask=return_special_tokens_mask,
  439. return_offsets_mapping=return_offsets_mapping,
  440. return_length=return_length,
  441. verbose=verbose,
  442. **kwargs,
  443. )
  444. else:
  445. return self.encode_plus(
  446. text=text,
  447. text_pair=text_pair,
  448. boxes=boxes,
  449. word_labels=word_labels,
  450. add_special_tokens=add_special_tokens,
  451. padding=padding,
  452. truncation=truncation,
  453. max_length=max_length,
  454. stride=stride,
  455. pad_to_multiple_of=pad_to_multiple_of,
  456. padding_side=padding_side,
  457. return_tensors=return_tensors,
  458. return_token_type_ids=return_token_type_ids,
  459. return_attention_mask=return_attention_mask,
  460. return_overflowing_tokens=return_overflowing_tokens,
  461. return_special_tokens_mask=return_special_tokens_mask,
  462. return_offsets_mapping=return_offsets_mapping,
  463. return_length=return_length,
  464. verbose=verbose,
  465. **kwargs,
  466. )
  467. @add_end_docstrings(LAYOUTLMV2_ENCODE_KWARGS_DOCSTRING, LAYOUTLMV2_ENCODE_PLUS_ADDITIONAL_KWARGS_DOCSTRING)
  468. def batch_encode_plus(
  469. self,
  470. batch_text_or_text_pairs: Union[
  471. list[TextInput],
  472. list[TextInputPair],
  473. list[PreTokenizedInput],
  474. ],
  475. is_pair: Optional[bool] = None,
  476. boxes: Optional[list[list[list[int]]]] = None,
  477. word_labels: Optional[Union[list[int], list[list[int]]]] = None,
  478. add_special_tokens: bool = True,
  479. padding: Union[bool, str, PaddingStrategy] = False,
  480. truncation: Union[bool, str, TruncationStrategy] = None,
  481. max_length: Optional[int] = None,
  482. stride: int = 0,
  483. pad_to_multiple_of: Optional[int] = None,
  484. padding_side: Optional[str] = None,
  485. return_tensors: Optional[Union[str, TensorType]] = None,
  486. return_token_type_ids: Optional[bool] = None,
  487. return_attention_mask: Optional[bool] = None,
  488. return_overflowing_tokens: bool = False,
  489. return_special_tokens_mask: bool = False,
  490. return_offsets_mapping: bool = False,
  491. return_length: bool = False,
  492. verbose: bool = True,
  493. **kwargs,
  494. ) -> BatchEncoding:
  495. # Backward compatibility for 'truncation_strategy', 'pad_to_max_length'
  496. padding_strategy, truncation_strategy, max_length, kwargs = self._get_padding_truncation_strategies(
  497. padding=padding,
  498. truncation=truncation,
  499. max_length=max_length,
  500. pad_to_multiple_of=pad_to_multiple_of,
  501. verbose=verbose,
  502. **kwargs,
  503. )
  504. return self._batch_encode_plus(
  505. batch_text_or_text_pairs=batch_text_or_text_pairs,
  506. is_pair=is_pair,
  507. boxes=boxes,
  508. word_labels=word_labels,
  509. add_special_tokens=add_special_tokens,
  510. padding_strategy=padding_strategy,
  511. truncation_strategy=truncation_strategy,
  512. max_length=max_length,
  513. stride=stride,
  514. pad_to_multiple_of=pad_to_multiple_of,
  515. padding_side=padding_side,
  516. return_tensors=return_tensors,
  517. return_token_type_ids=return_token_type_ids,
  518. return_attention_mask=return_attention_mask,
  519. return_overflowing_tokens=return_overflowing_tokens,
  520. return_special_tokens_mask=return_special_tokens_mask,
  521. return_offsets_mapping=return_offsets_mapping,
  522. return_length=return_length,
  523. verbose=verbose,
  524. **kwargs,
  525. )
  526. def _batch_encode_plus(
  527. self,
  528. batch_text_or_text_pairs: Union[
  529. list[TextInput],
  530. list[TextInputPair],
  531. list[PreTokenizedInput],
  532. ],
  533. is_pair: Optional[bool] = None,
  534. boxes: Optional[list[list[list[int]]]] = None,
  535. word_labels: Optional[list[list[int]]] = None,
  536. add_special_tokens: bool = True,
  537. padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
  538. truncation_strategy: TruncationStrategy = TruncationStrategy.DO_NOT_TRUNCATE,
  539. max_length: Optional[int] = None,
  540. stride: int = 0,
  541. pad_to_multiple_of: Optional[int] = None,
  542. padding_side: Optional[str] = None,
  543. return_tensors: Optional[Union[str, TensorType]] = None,
  544. return_token_type_ids: Optional[bool] = None,
  545. return_attention_mask: Optional[bool] = None,
  546. return_overflowing_tokens: bool = False,
  547. return_special_tokens_mask: bool = False,
  548. return_offsets_mapping: bool = False,
  549. return_length: bool = False,
  550. verbose: bool = True,
  551. **kwargs,
  552. ) -> BatchEncoding:
  553. if return_offsets_mapping:
  554. raise NotImplementedError(
  555. "return_offset_mapping is not available when using Python tokenizers. "
  556. "To use this feature, change your tokenizer to one deriving from "
  557. "transformers.PreTrainedTokenizerFast."
  558. )
  559. batch_outputs = self._batch_prepare_for_model(
  560. batch_text_or_text_pairs=batch_text_or_text_pairs,
  561. is_pair=is_pair,
  562. boxes=boxes,
  563. word_labels=word_labels,
  564. add_special_tokens=add_special_tokens,
  565. padding_strategy=padding_strategy,
  566. truncation_strategy=truncation_strategy,
  567. max_length=max_length,
  568. stride=stride,
  569. pad_to_multiple_of=pad_to_multiple_of,
  570. padding_side=padding_side,
  571. return_attention_mask=return_attention_mask,
  572. return_token_type_ids=return_token_type_ids,
  573. return_overflowing_tokens=return_overflowing_tokens,
  574. return_special_tokens_mask=return_special_tokens_mask,
  575. return_length=return_length,
  576. return_tensors=return_tensors,
  577. verbose=verbose,
  578. )
  579. return BatchEncoding(batch_outputs)
  580. @add_end_docstrings(LAYOUTLMV2_ENCODE_KWARGS_DOCSTRING, LAYOUTLMV2_ENCODE_PLUS_ADDITIONAL_KWARGS_DOCSTRING)
  581. def _batch_prepare_for_model(
  582. self,
  583. batch_text_or_text_pairs,
  584. is_pair: Optional[bool] = None,
  585. boxes: Optional[list[list[int]]] = None,
  586. word_labels: Optional[list[list[int]]] = None,
  587. add_special_tokens: bool = True,
  588. padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
  589. truncation_strategy: TruncationStrategy = TruncationStrategy.DO_NOT_TRUNCATE,
  590. max_length: Optional[int] = None,
  591. stride: int = 0,
  592. pad_to_multiple_of: Optional[int] = None,
  593. padding_side: Optional[str] = None,
  594. return_tensors: Optional[str] = None,
  595. return_token_type_ids: Optional[bool] = None,
  596. return_attention_mask: Optional[bool] = None,
  597. return_overflowing_tokens: bool = False,
  598. return_special_tokens_mask: bool = False,
  599. return_length: bool = False,
  600. verbose: bool = True,
  601. ) -> BatchEncoding:
  602. """
  603. Prepares a sequence of input id, or a pair of sequences of inputs ids so that it can be used by the model. It
  604. adds special tokens, truncates sequences if overflowing while taking into account the special tokens and
  605. manages a moving window (with user defined stride) for overflowing tokens.
  606. Args:
  607. batch_ids_pairs: list of tokenized input ids or input ids pairs
  608. """
  609. batch_outputs = {}
  610. for idx, example in enumerate(zip(batch_text_or_text_pairs, boxes)):
  611. batch_text_or_text_pair, boxes_example = example
  612. outputs = self.prepare_for_model(
  613. batch_text_or_text_pair[0] if is_pair else batch_text_or_text_pair,
  614. batch_text_or_text_pair[1] if is_pair else None,
  615. boxes_example,
  616. word_labels=word_labels[idx] if word_labels is not None else None,
  617. add_special_tokens=add_special_tokens,
  618. padding=PaddingStrategy.DO_NOT_PAD.value, # we pad in batch afterward
  619. truncation=truncation_strategy.value,
  620. max_length=max_length,
  621. stride=stride,
  622. pad_to_multiple_of=None, # we pad in batch afterward
  623. padding_side=None, # we pad in batch afterward
  624. return_attention_mask=False, # we pad in batch afterward
  625. return_token_type_ids=return_token_type_ids,
  626. return_overflowing_tokens=return_overflowing_tokens,
  627. return_special_tokens_mask=return_special_tokens_mask,
  628. return_length=return_length,
  629. return_tensors=None, # We convert the whole batch to tensors at the end
  630. prepend_batch_axis=False,
  631. verbose=verbose,
  632. )
  633. for key, value in outputs.items():
  634. if key not in batch_outputs:
  635. batch_outputs[key] = []
  636. batch_outputs[key].append(value)
  637. batch_outputs = self.pad(
  638. batch_outputs,
  639. padding=padding_strategy.value,
  640. max_length=max_length,
  641. pad_to_multiple_of=pad_to_multiple_of,
  642. padding_side=padding_side,
  643. return_attention_mask=return_attention_mask,
  644. )
  645. batch_outputs = BatchEncoding(batch_outputs, tensor_type=return_tensors)
  646. return batch_outputs
  647. @add_end_docstrings(LAYOUTLMV2_ENCODE_KWARGS_DOCSTRING)
  648. def encode(
  649. self,
  650. text: Union[TextInput, PreTokenizedInput],
  651. text_pair: Optional[PreTokenizedInput] = None,
  652. boxes: Optional[list[list[int]]] = None,
  653. word_labels: Optional[list[int]] = None,
  654. add_special_tokens: bool = True,
  655. padding: Union[bool, str, PaddingStrategy] = False,
  656. truncation: Union[bool, str, TruncationStrategy] = None,
  657. max_length: Optional[int] = None,
  658. stride: int = 0,
  659. pad_to_multiple_of: Optional[int] = None,
  660. padding_side: Optional[str] = None,
  661. return_tensors: Optional[Union[str, TensorType]] = None,
  662. return_token_type_ids: Optional[bool] = None,
  663. return_attention_mask: Optional[bool] = None,
  664. return_overflowing_tokens: bool = False,
  665. return_special_tokens_mask: bool = False,
  666. return_offsets_mapping: bool = False,
  667. return_length: bool = False,
  668. verbose: bool = True,
  669. **kwargs,
  670. ) -> list[int]:
  671. encoded_inputs = self.encode_plus(
  672. text=text,
  673. text_pair=text_pair,
  674. boxes=boxes,
  675. word_labels=word_labels,
  676. add_special_tokens=add_special_tokens,
  677. padding=padding,
  678. truncation=truncation,
  679. max_length=max_length,
  680. stride=stride,
  681. pad_to_multiple_of=pad_to_multiple_of,
  682. padding_side=padding_side,
  683. return_tensors=return_tensors,
  684. return_token_type_ids=return_token_type_ids,
  685. return_attention_mask=return_attention_mask,
  686. return_overflowing_tokens=return_overflowing_tokens,
  687. return_special_tokens_mask=return_special_tokens_mask,
  688. return_offsets_mapping=return_offsets_mapping,
  689. return_length=return_length,
  690. verbose=verbose,
  691. **kwargs,
  692. )
  693. return encoded_inputs["input_ids"]
  694. @add_end_docstrings(LAYOUTLMV2_ENCODE_KWARGS_DOCSTRING, LAYOUTLMV2_ENCODE_PLUS_ADDITIONAL_KWARGS_DOCSTRING)
  695. def encode_plus(
  696. self,
  697. text: Union[TextInput, PreTokenizedInput],
  698. text_pair: Optional[PreTokenizedInput] = None,
  699. boxes: Optional[list[list[int]]] = None,
  700. word_labels: Optional[list[int]] = None,
  701. add_special_tokens: bool = True,
  702. padding: Union[bool, str, PaddingStrategy] = False,
  703. truncation: Union[bool, str, TruncationStrategy] = None,
  704. max_length: Optional[int] = None,
  705. stride: int = 0,
  706. pad_to_multiple_of: Optional[int] = None,
  707. padding_side: Optional[str] = None,
  708. return_tensors: Optional[Union[str, TensorType]] = None,
  709. return_token_type_ids: Optional[bool] = None,
  710. return_attention_mask: Optional[bool] = None,
  711. return_overflowing_tokens: bool = False,
  712. return_special_tokens_mask: bool = False,
  713. return_offsets_mapping: bool = False,
  714. return_length: bool = False,
  715. verbose: bool = True,
  716. **kwargs,
  717. ) -> BatchEncoding:
  718. """
  719. Tokenize and prepare for the model a sequence or a pair of sequences. .. warning:: This method is deprecated,
  720. `__call__` should be used instead.
  721. Args:
  722. text (`str`, `List[str]`, `List[List[str]]`):
  723. The first sequence to be encoded. This can be a string, a list of strings or a list of list of strings.
  724. text_pair (`List[str]` or `List[int]`, *optional*):
  725. Optional second sequence to be encoded. This can be a list of strings (words of a single example) or a
  726. list of list of strings (words of a batch of examples).
  727. """
  728. # Backward compatibility for 'truncation_strategy', 'pad_to_max_length'
  729. padding_strategy, truncation_strategy, max_length, kwargs = self._get_padding_truncation_strategies(
  730. padding=padding,
  731. truncation=truncation,
  732. max_length=max_length,
  733. pad_to_multiple_of=pad_to_multiple_of,
  734. verbose=verbose,
  735. **kwargs,
  736. )
  737. return self._encode_plus(
  738. text=text,
  739. boxes=boxes,
  740. text_pair=text_pair,
  741. word_labels=word_labels,
  742. add_special_tokens=add_special_tokens,
  743. padding_strategy=padding_strategy,
  744. truncation_strategy=truncation_strategy,
  745. max_length=max_length,
  746. stride=stride,
  747. pad_to_multiple_of=pad_to_multiple_of,
  748. padding_side=padding_side,
  749. return_tensors=return_tensors,
  750. return_token_type_ids=return_token_type_ids,
  751. return_attention_mask=return_attention_mask,
  752. return_overflowing_tokens=return_overflowing_tokens,
  753. return_special_tokens_mask=return_special_tokens_mask,
  754. return_offsets_mapping=return_offsets_mapping,
  755. return_length=return_length,
  756. verbose=verbose,
  757. **kwargs,
  758. )
  759. def _encode_plus(
  760. self,
  761. text: Union[TextInput, PreTokenizedInput],
  762. text_pair: Optional[PreTokenizedInput] = None,
  763. boxes: Optional[list[list[int]]] = None,
  764. word_labels: Optional[list[int]] = None,
  765. add_special_tokens: bool = True,
  766. padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
  767. truncation_strategy: TruncationStrategy = TruncationStrategy.DO_NOT_TRUNCATE,
  768. max_length: Optional[int] = None,
  769. stride: int = 0,
  770. pad_to_multiple_of: Optional[int] = None,
  771. padding_side: Optional[str] = None,
  772. return_tensors: Optional[Union[str, TensorType]] = None,
  773. return_token_type_ids: Optional[bool] = None,
  774. return_attention_mask: Optional[bool] = None,
  775. return_overflowing_tokens: bool = False,
  776. return_special_tokens_mask: bool = False,
  777. return_offsets_mapping: bool = False,
  778. return_length: bool = False,
  779. verbose: bool = True,
  780. **kwargs,
  781. ) -> BatchEncoding:
  782. if return_offsets_mapping:
  783. raise NotImplementedError(
  784. "return_offset_mapping is not available when using Python tokenizers. "
  785. "To use this feature, change your tokenizer to one deriving from "
  786. "transformers.PreTrainedTokenizerFast. "
  787. "More information on available tokenizers at "
  788. "https://github.com/huggingface/transformers/pull/2674"
  789. )
  790. return self.prepare_for_model(
  791. text=text,
  792. text_pair=text_pair,
  793. boxes=boxes,
  794. word_labels=word_labels,
  795. add_special_tokens=add_special_tokens,
  796. padding=padding_strategy.value,
  797. truncation=truncation_strategy.value,
  798. max_length=max_length,
  799. stride=stride,
  800. pad_to_multiple_of=pad_to_multiple_of,
  801. padding_side=padding_side,
  802. return_tensors=return_tensors,
  803. prepend_batch_axis=True,
  804. return_attention_mask=return_attention_mask,
  805. return_token_type_ids=return_token_type_ids,
  806. return_overflowing_tokens=return_overflowing_tokens,
  807. return_special_tokens_mask=return_special_tokens_mask,
  808. return_length=return_length,
  809. verbose=verbose,
  810. )
  811. @add_end_docstrings(LAYOUTLMV2_ENCODE_KWARGS_DOCSTRING, LAYOUTLMV2_ENCODE_PLUS_ADDITIONAL_KWARGS_DOCSTRING)
  812. def prepare_for_model(
  813. self,
  814. text: Union[TextInput, PreTokenizedInput],
  815. text_pair: Optional[PreTokenizedInput] = None,
  816. boxes: Optional[list[list[int]]] = None,
  817. word_labels: Optional[list[int]] = None,
  818. add_special_tokens: bool = True,
  819. padding: Union[bool, str, PaddingStrategy] = False,
  820. truncation: Union[bool, str, TruncationStrategy] = None,
  821. max_length: Optional[int] = None,
  822. stride: int = 0,
  823. pad_to_multiple_of: Optional[int] = None,
  824. padding_side: Optional[str] = None,
  825. return_tensors: Optional[Union[str, TensorType]] = None,
  826. return_token_type_ids: Optional[bool] = None,
  827. return_attention_mask: Optional[bool] = None,
  828. return_overflowing_tokens: bool = False,
  829. return_special_tokens_mask: bool = False,
  830. return_offsets_mapping: bool = False,
  831. return_length: bool = False,
  832. verbose: bool = True,
  833. prepend_batch_axis: bool = False,
  834. **kwargs,
  835. ) -> BatchEncoding:
  836. """
  837. Prepares a sequence or a pair of sequences so that it can be used by the model. It adds special tokens,
  838. truncates sequences if overflowing while taking into account the special tokens and manages a moving window
  839. (with user defined stride) for overflowing tokens. Please Note, for *text_pair* different than `None` and
  840. *truncation_strategy = longest_first* or `True`, it is not possible to return overflowing tokens. Such a
  841. combination of arguments will raise an error.
  842. Word-level `boxes` are turned into token-level `bbox`. If provided, word-level `word_labels` are turned into
  843. token-level `labels`. The word label is used for the first token of the word, while remaining tokens are
  844. labeled with -100, such that they will be ignored by the loss function.
  845. Args:
  846. text (`str`, `List[str]`, `List[List[str]]`):
  847. The first sequence to be encoded. This can be a string, a list of strings or a list of list of strings.
  848. text_pair (`List[str]` or `List[int]`, *optional*):
  849. Optional second sequence to be encoded. This can be a list of strings (words of a single example) or a
  850. list of list of strings (words of a batch of examples).
  851. """
  852. # Backward compatibility for 'truncation_strategy', 'pad_to_max_length'
  853. padding_strategy, truncation_strategy, max_length, kwargs = self._get_padding_truncation_strategies(
  854. padding=padding,
  855. truncation=truncation,
  856. max_length=max_length,
  857. pad_to_multiple_of=pad_to_multiple_of,
  858. verbose=verbose,
  859. **kwargs,
  860. )
  861. tokens = []
  862. pair_tokens = []
  863. token_boxes = []
  864. pair_token_boxes = []
  865. labels = []
  866. if text_pair is None:
  867. if word_labels is None:
  868. # CASE 1: document image classification (training + inference) + CASE 2: token classification (inference)
  869. for word, box in zip(text, boxes):
  870. if len(word) < 1: # skip empty words
  871. continue
  872. word_tokens = self.tokenize(word)
  873. tokens.extend(word_tokens)
  874. token_boxes.extend([box] * len(word_tokens))
  875. else:
  876. # CASE 2: token classification (training)
  877. for word, box, label in zip(text, boxes, word_labels):
  878. if len(word) < 1: # skip empty words
  879. continue
  880. word_tokens = self.tokenize(word)
  881. tokens.extend(word_tokens)
  882. token_boxes.extend([box] * len(word_tokens))
  883. if self.only_label_first_subword:
  884. # Use the real label id for the first token of the word, and padding ids for the remaining tokens
  885. labels.extend([label] + [self.pad_token_label] * (len(word_tokens) - 1))
  886. else:
  887. labels.extend([label] * len(word_tokens))
  888. else:
  889. # CASE 3: document visual question answering (inference)
  890. # text = question
  891. # text_pair = words
  892. tokens = self.tokenize(text)
  893. token_boxes = [self.pad_token_box for _ in range(len(tokens))]
  894. for word, box in zip(text_pair, boxes):
  895. if len(word) < 1: # skip empty words
  896. continue
  897. word_tokens = self.tokenize(word)
  898. pair_tokens.extend(word_tokens)
  899. pair_token_boxes.extend([box] * len(word_tokens))
  900. # Create ids + pair_ids
  901. ids = self.convert_tokens_to_ids(tokens)
  902. pair_ids = self.convert_tokens_to_ids(pair_tokens) if pair_tokens else None
  903. if (
  904. return_overflowing_tokens
  905. and truncation_strategy == TruncationStrategy.LONGEST_FIRST
  906. and pair_ids is not None
  907. ):
  908. raise ValueError(
  909. "Not possible to return overflowing tokens for pair of sequences with the "
  910. "`longest_first`. Please select another truncation strategy than `longest_first`, "
  911. "for instance `only_second` or `only_first`."
  912. )
  913. # Compute the total size of the returned encodings
  914. pair = bool(pair_ids is not None)
  915. len_ids = len(ids)
  916. len_pair_ids = len(pair_ids) if pair else 0
  917. total_len = len_ids + len_pair_ids + (self.num_special_tokens_to_add(pair=pair) if add_special_tokens else 0)
  918. # Truncation: Handle max sequence length
  919. overflowing_tokens = []
  920. overflowing_token_boxes = []
  921. overflowing_labels = []
  922. if truncation_strategy != TruncationStrategy.DO_NOT_TRUNCATE and max_length and total_len > max_length:
  923. (
  924. ids,
  925. token_boxes,
  926. pair_ids,
  927. pair_token_boxes,
  928. labels,
  929. overflowing_tokens,
  930. overflowing_token_boxes,
  931. overflowing_labels,
  932. ) = self.truncate_sequences(
  933. ids,
  934. token_boxes,
  935. pair_ids=pair_ids,
  936. pair_token_boxes=pair_token_boxes,
  937. labels=labels,
  938. num_tokens_to_remove=total_len - max_length,
  939. truncation_strategy=truncation_strategy,
  940. stride=stride,
  941. )
  942. if return_token_type_ids and not add_special_tokens:
  943. raise ValueError(
  944. "Asking to return token_type_ids while setting add_special_tokens to False "
  945. "results in an undefined behavior. Please set add_special_tokens to True or "
  946. "set return_token_type_ids to None."
  947. )
  948. # Load from model defaults
  949. if return_token_type_ids is None:
  950. return_token_type_ids = "token_type_ids" in self.model_input_names
  951. if return_attention_mask is None:
  952. return_attention_mask = "attention_mask" in self.model_input_names
  953. encoded_inputs = {}
  954. if return_overflowing_tokens:
  955. encoded_inputs["overflowing_tokens"] = overflowing_tokens
  956. encoded_inputs["overflowing_token_boxes"] = overflowing_token_boxes
  957. encoded_inputs["overflowing_labels"] = overflowing_labels
  958. encoded_inputs["num_truncated_tokens"] = total_len - max_length
  959. # Add special tokens
  960. if add_special_tokens:
  961. sequence = self.build_inputs_with_special_tokens(ids, pair_ids)
  962. token_type_ids = self.create_token_type_ids_from_sequences(ids, pair_ids)
  963. token_boxes = [self.cls_token_box] + token_boxes + [self.sep_token_box]
  964. if pair_token_boxes:
  965. pair_token_boxes = pair_token_boxes + [self.sep_token_box]
  966. if labels:
  967. labels = [self.pad_token_label] + labels + [self.pad_token_label]
  968. else:
  969. sequence = ids + pair_ids if pair else ids
  970. token_type_ids = [0] * len(ids) + ([0] * len(pair_ids) if pair else [])
  971. # Build output dictionary
  972. encoded_inputs["input_ids"] = sequence
  973. encoded_inputs["bbox"] = token_boxes + pair_token_boxes
  974. if return_token_type_ids:
  975. encoded_inputs["token_type_ids"] = token_type_ids
  976. if return_special_tokens_mask:
  977. if add_special_tokens:
  978. encoded_inputs["special_tokens_mask"] = self.get_special_tokens_mask(ids, pair_ids)
  979. else:
  980. encoded_inputs["special_tokens_mask"] = [0] * len(sequence)
  981. if labels:
  982. encoded_inputs["labels"] = labels
  983. # Check lengths
  984. self._eventual_warn_about_too_long_sequence(encoded_inputs["input_ids"], max_length, verbose)
  985. # Padding
  986. if padding_strategy != PaddingStrategy.DO_NOT_PAD or return_attention_mask:
  987. encoded_inputs = self.pad(
  988. encoded_inputs,
  989. max_length=max_length,
  990. padding=padding_strategy.value,
  991. pad_to_multiple_of=pad_to_multiple_of,
  992. padding_side=padding_side,
  993. return_attention_mask=return_attention_mask,
  994. )
  995. if return_length:
  996. encoded_inputs["length"] = len(encoded_inputs["input_ids"])
  997. batch_outputs = BatchEncoding(
  998. encoded_inputs, tensor_type=return_tensors, prepend_batch_axis=prepend_batch_axis
  999. )
  1000. return batch_outputs
  1001. def truncate_sequences(
  1002. self,
  1003. ids: list[int],
  1004. token_boxes: list[list[int]],
  1005. pair_ids: Optional[list[int]] = None,
  1006. pair_token_boxes: Optional[list[list[int]]] = None,
  1007. labels: Optional[list[int]] = None,
  1008. num_tokens_to_remove: int = 0,
  1009. truncation_strategy: Union[str, TruncationStrategy] = "longest_first",
  1010. stride: int = 0,
  1011. ) -> tuple[list[int], list[int], list[int]]:
  1012. """
  1013. Truncates a sequence pair in-place following the strategy.
  1014. Args:
  1015. ids (`List[int]`):
  1016. Tokenized input ids of the first sequence. Can be obtained from a string by chaining the `tokenize` and
  1017. `convert_tokens_to_ids` methods.
  1018. token_boxes (`List[List[int]]`):
  1019. Bounding boxes of the first sequence.
  1020. pair_ids (`List[int]`, *optional*):
  1021. Tokenized input ids of the second sequence. Can be obtained from a string by chaining the `tokenize`
  1022. and `convert_tokens_to_ids` methods.
  1023. pair_token_boxes (`List[List[int]]`, *optional*):
  1024. Bounding boxes of the second sequence.
  1025. labels (`List[int]`, *optional*):
  1026. Labels of the first sequence (for token classification tasks).
  1027. num_tokens_to_remove (`int`, *optional*, defaults to 0):
  1028. Number of tokens to remove using the truncation strategy.
  1029. truncation_strategy (`str` or [`~tokenization_utils_base.TruncationStrategy`], *optional*, defaults to `False`):
  1030. The strategy to follow for truncation. Can be:
  1031. - `'longest_first'`: Truncate to a maximum length specified with the argument `max_length` or to the
  1032. maximum acceptable input length for the model if that argument is not provided. This will truncate
  1033. token by token, removing a token from the longest sequence in the pair if a pair of sequences (or a
  1034. batch of pairs) is provided.
  1035. - `'only_first'`: Truncate to a maximum length specified with the argument `max_length` or to the
  1036. maximum acceptable input length for the model if that argument is not provided. This will only
  1037. truncate the first sequence of a pair if a pair of sequences (or a batch of pairs) is provided.
  1038. - `'only_second'`: Truncate to a maximum length specified with the argument `max_length` or to the
  1039. maximum acceptable input length for the model if that argument is not provided. This will only
  1040. truncate the second sequence of a pair if a pair of sequences (or a batch of pairs) is provided.
  1041. - `'do_not_truncate'` (default): No truncation (i.e., can output batch with sequence lengths greater
  1042. than the model maximum admissible input size).
  1043. stride (`int`, *optional*, defaults to 0):
  1044. If set to a positive number, the overflowing tokens returned will contain some tokens from the main
  1045. sequence returned. The value of this argument defines the number of additional tokens.
  1046. Returns:
  1047. `Tuple[List[int], List[int], List[int]]`: The truncated `ids`, the truncated `pair_ids` and the list of
  1048. overflowing tokens. Note: The *longest_first* strategy returns empty list of overflowing tokens if a pair
  1049. of sequences (or a batch of pairs) is provided.
  1050. """
  1051. if num_tokens_to_remove <= 0:
  1052. return ids, token_boxes, pair_ids, pair_token_boxes, labels, [], [], []
  1053. if not isinstance(truncation_strategy, TruncationStrategy):
  1054. truncation_strategy = TruncationStrategy(truncation_strategy)
  1055. overflowing_tokens = []
  1056. overflowing_token_boxes = []
  1057. overflowing_labels = []
  1058. if truncation_strategy == TruncationStrategy.ONLY_FIRST or (
  1059. truncation_strategy == TruncationStrategy.LONGEST_FIRST and pair_ids is None
  1060. ):
  1061. if len(ids) > num_tokens_to_remove:
  1062. window_len = min(len(ids), stride + num_tokens_to_remove)
  1063. overflowing_tokens = ids[-window_len:]
  1064. overflowing_token_boxes = token_boxes[-window_len:]
  1065. overflowing_labels = labels[-window_len:]
  1066. ids = ids[:-num_tokens_to_remove]
  1067. token_boxes = token_boxes[:-num_tokens_to_remove]
  1068. labels = labels[:-num_tokens_to_remove]
  1069. else:
  1070. error_msg = (
  1071. f"We need to remove {num_tokens_to_remove} to truncate the input "
  1072. f"but the first sequence has a length {len(ids)}. "
  1073. )
  1074. if truncation_strategy == TruncationStrategy.ONLY_FIRST:
  1075. error_msg = (
  1076. error_msg + "Please select another truncation strategy than "
  1077. f"{truncation_strategy}, for instance 'longest_first' or 'only_second'."
  1078. )
  1079. logger.error(error_msg)
  1080. elif truncation_strategy == TruncationStrategy.LONGEST_FIRST:
  1081. logger.warning(
  1082. "Be aware, overflowing tokens are not returned for the setting you have chosen,"
  1083. f" i.e. sequence pairs with the '{TruncationStrategy.LONGEST_FIRST.value}' "
  1084. "truncation strategy. So the returned list will always be empty even if some "
  1085. "tokens have been removed."
  1086. )
  1087. for _ in range(num_tokens_to_remove):
  1088. if pair_ids is None or len(ids) > len(pair_ids):
  1089. ids = ids[:-1]
  1090. token_boxes = token_boxes[:-1]
  1091. labels = labels[:-1]
  1092. else:
  1093. pair_ids = pair_ids[:-1]
  1094. pair_token_boxes = pair_token_boxes[:-1]
  1095. elif truncation_strategy == TruncationStrategy.ONLY_SECOND and pair_ids is not None:
  1096. if len(pair_ids) > num_tokens_to_remove:
  1097. window_len = min(len(pair_ids), stride + num_tokens_to_remove)
  1098. overflowing_tokens = pair_ids[-window_len:]
  1099. overflowing_token_boxes = pair_token_boxes[-window_len:]
  1100. pair_ids = pair_ids[:-num_tokens_to_remove]
  1101. pair_token_boxes = pair_token_boxes[:-num_tokens_to_remove]
  1102. else:
  1103. logger.error(
  1104. f"We need to remove {num_tokens_to_remove} to truncate the input "
  1105. f"but the second sequence has a length {len(pair_ids)}. "
  1106. f"Please select another truncation strategy than {truncation_strategy}, "
  1107. "for instance 'longest_first' or 'only_first'."
  1108. )
  1109. return (
  1110. ids,
  1111. token_boxes,
  1112. pair_ids,
  1113. pair_token_boxes,
  1114. labels,
  1115. overflowing_tokens,
  1116. overflowing_token_boxes,
  1117. overflowing_labels,
  1118. )
  1119. def _pad(
  1120. self,
  1121. encoded_inputs: Union[dict[str, EncodedInput], BatchEncoding],
  1122. max_length: Optional[int] = None,
  1123. padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
  1124. pad_to_multiple_of: Optional[int] = None,
  1125. padding_side: Optional[str] = None,
  1126. return_attention_mask: Optional[bool] = None,
  1127. ) -> dict:
  1128. """
  1129. Pad encoded inputs (on left/right and up to predefined length or max length in the batch)
  1130. Args:
  1131. encoded_inputs:
  1132. Dictionary of tokenized inputs (`List[int]`) or batch of tokenized inputs (`List[List[int]]`).
  1133. max_length: maximum length of the returned list and optionally padding length (see below).
  1134. Will truncate by taking into account the special tokens.
  1135. padding_strategy: PaddingStrategy to use for padding.
  1136. - PaddingStrategy.LONGEST Pad to the longest sequence in the batch
  1137. - PaddingStrategy.MAX_LENGTH: Pad to the max length (default)
  1138. - PaddingStrategy.DO_NOT_PAD: Do not pad
  1139. The tokenizer padding sides are defined in self.padding_side:
  1140. - 'left': pads on the left of the sequences
  1141. - 'right': pads on the right of the sequences
  1142. pad_to_multiple_of: (optional) Integer if set will pad the sequence to a multiple of the provided value.
  1143. This is especially useful to enable the use of Tensor Core on NVIDIA hardware with compute capability
  1144. `>= 7.5` (Volta).
  1145. padding_side:
  1146. The side on which the model should have padding applied. Should be selected between ['right', 'left'].
  1147. Default value is picked from the class attribute of the same name.
  1148. return_attention_mask:
  1149. (optional) Set to False to avoid returning attention mask (default: set to model specifics)
  1150. """
  1151. # Load from model defaults
  1152. if return_attention_mask is None:
  1153. return_attention_mask = "attention_mask" in self.model_input_names
  1154. required_input = encoded_inputs[self.model_input_names[0]]
  1155. if padding_strategy == PaddingStrategy.LONGEST:
  1156. max_length = len(required_input)
  1157. if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0):
  1158. max_length = ((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of
  1159. needs_to_be_padded = padding_strategy != PaddingStrategy.DO_NOT_PAD and len(required_input) != max_length
  1160. # Initialize attention mask if not present.
  1161. if return_attention_mask and "attention_mask" not in encoded_inputs:
  1162. encoded_inputs["attention_mask"] = [1] * len(required_input)
  1163. if needs_to_be_padded:
  1164. difference = max_length - len(required_input)
  1165. padding_side = padding_side if padding_side is not None else self.padding_side
  1166. if padding_side == "right":
  1167. if return_attention_mask:
  1168. encoded_inputs["attention_mask"] = encoded_inputs["attention_mask"] + [0] * difference
  1169. if "token_type_ids" in encoded_inputs:
  1170. encoded_inputs["token_type_ids"] = (
  1171. encoded_inputs["token_type_ids"] + [self.pad_token_type_id] * difference
  1172. )
  1173. if "bbox" in encoded_inputs:
  1174. encoded_inputs["bbox"] = encoded_inputs["bbox"] + [self.pad_token_box] * difference
  1175. if "labels" in encoded_inputs:
  1176. encoded_inputs["labels"] = encoded_inputs["labels"] + [self.pad_token_label] * difference
  1177. if "special_tokens_mask" in encoded_inputs:
  1178. encoded_inputs["special_tokens_mask"] = encoded_inputs["special_tokens_mask"] + [1] * difference
  1179. encoded_inputs[self.model_input_names[0]] = required_input + [self.pad_token_id] * difference
  1180. elif padding_side == "left":
  1181. if return_attention_mask:
  1182. encoded_inputs["attention_mask"] = [0] * difference + encoded_inputs["attention_mask"]
  1183. if "token_type_ids" in encoded_inputs:
  1184. encoded_inputs["token_type_ids"] = [self.pad_token_type_id] * difference + encoded_inputs[
  1185. "token_type_ids"
  1186. ]
  1187. if "bbox" in encoded_inputs:
  1188. encoded_inputs["bbox"] = [self.pad_token_box] * difference + encoded_inputs["bbox"]
  1189. if "labels" in encoded_inputs:
  1190. encoded_inputs["labels"] = [self.pad_token_label] * difference + encoded_inputs["labels"]
  1191. if "special_tokens_mask" in encoded_inputs:
  1192. encoded_inputs["special_tokens_mask"] = [1] * difference + encoded_inputs["special_tokens_mask"]
  1193. encoded_inputs[self.model_input_names[0]] = [self.pad_token_id] * difference + required_input
  1194. else:
  1195. raise ValueError("Invalid padding strategy:" + str(padding_side))
  1196. return encoded_inputs
  1197. # Copied from transformers.models.bert.tokenization_bert.BasicTokenizer
  1198. class BasicTokenizer:
  1199. """
  1200. Constructs a BasicTokenizer that will run basic tokenization (punctuation splitting, lower casing, etc.).
  1201. Args:
  1202. do_lower_case (`bool`, *optional*, defaults to `True`):
  1203. Whether or not to lowercase the input when tokenizing.
  1204. never_split (`Iterable`, *optional*):
  1205. Collection of tokens which will never be split during tokenization. Only has an effect when
  1206. `do_basic_tokenize=True`
  1207. tokenize_chinese_chars (`bool`, *optional*, defaults to `True`):
  1208. Whether or not to tokenize Chinese characters.
  1209. This should likely be deactivated for Japanese (see this
  1210. [issue](https://github.com/huggingface/transformers/issues/328)).
  1211. strip_accents (`bool`, *optional*):
  1212. Whether or not to strip all accents. If this option is not specified, then it will be determined by the
  1213. value for `lowercase` (as in the original BERT).
  1214. do_split_on_punc (`bool`, *optional*, defaults to `True`):
  1215. In some instances we want to skip the basic punctuation splitting so that later tokenization can capture
  1216. the full context of the words, such as contractions.
  1217. """
  1218. def __init__(
  1219. self,
  1220. do_lower_case=True,
  1221. never_split=None,
  1222. tokenize_chinese_chars=True,
  1223. strip_accents=None,
  1224. do_split_on_punc=True,
  1225. ):
  1226. if never_split is None:
  1227. never_split = []
  1228. self.do_lower_case = do_lower_case
  1229. self.never_split = set(never_split)
  1230. self.tokenize_chinese_chars = tokenize_chinese_chars
  1231. self.strip_accents = strip_accents
  1232. self.do_split_on_punc = do_split_on_punc
  1233. def tokenize(self, text, never_split=None):
  1234. """
  1235. Basic Tokenization of a piece of text. For sub-word tokenization, see WordPieceTokenizer.
  1236. Args:
  1237. never_split (`List[str]`, *optional*)
  1238. Kept for backward compatibility purposes. Now implemented directly at the base class level (see
  1239. [`PreTrainedTokenizer.tokenize`]) List of token not to split.
  1240. """
  1241. # union() returns a new set by concatenating the two sets.
  1242. never_split = self.never_split.union(set(never_split)) if never_split else self.never_split
  1243. text = self._clean_text(text)
  1244. # This was added on November 1st, 2018 for the multilingual and Chinese
  1245. # models. This is also applied to the English models now, but it doesn't
  1246. # matter since the English models were not trained on any Chinese data
  1247. # and generally don't have any Chinese data in them (there are Chinese
  1248. # characters in the vocabulary because Wikipedia does have some Chinese
  1249. # words in the English Wikipedia.).
  1250. if self.tokenize_chinese_chars:
  1251. text = self._tokenize_chinese_chars(text)
  1252. # prevents treating the same character with different unicode codepoints as different characters
  1253. unicode_normalized_text = unicodedata.normalize("NFC", text)
  1254. orig_tokens = whitespace_tokenize(unicode_normalized_text)
  1255. split_tokens = []
  1256. for token in orig_tokens:
  1257. if token not in never_split:
  1258. if self.do_lower_case:
  1259. token = token.lower()
  1260. if self.strip_accents is not False:
  1261. token = self._run_strip_accents(token)
  1262. elif self.strip_accents:
  1263. token = self._run_strip_accents(token)
  1264. split_tokens.extend(self._run_split_on_punc(token, never_split))
  1265. output_tokens = whitespace_tokenize(" ".join(split_tokens))
  1266. return output_tokens
  1267. def _run_strip_accents(self, text):
  1268. """Strips accents from a piece of text."""
  1269. text = unicodedata.normalize("NFD", text)
  1270. output = []
  1271. for char in text:
  1272. cat = unicodedata.category(char)
  1273. if cat == "Mn":
  1274. continue
  1275. output.append(char)
  1276. return "".join(output)
  1277. def _run_split_on_punc(self, text, never_split=None):
  1278. """Splits punctuation on a piece of text."""
  1279. if not self.do_split_on_punc or (never_split is not None and text in never_split):
  1280. return [text]
  1281. chars = list(text)
  1282. i = 0
  1283. start_new_word = True
  1284. output = []
  1285. while i < len(chars):
  1286. char = chars[i]
  1287. if _is_punctuation(char):
  1288. output.append([char])
  1289. start_new_word = True
  1290. else:
  1291. if start_new_word:
  1292. output.append([])
  1293. start_new_word = False
  1294. output[-1].append(char)
  1295. i += 1
  1296. return ["".join(x) for x in output]
  1297. def _tokenize_chinese_chars(self, text):
  1298. """Adds whitespace around any CJK character."""
  1299. output = []
  1300. for char in text:
  1301. cp = ord(char)
  1302. if self._is_chinese_char(cp):
  1303. output.append(" ")
  1304. output.append(char)
  1305. output.append(" ")
  1306. else:
  1307. output.append(char)
  1308. return "".join(output)
  1309. def _is_chinese_char(self, cp):
  1310. """Checks whether CP is the codepoint of a CJK character."""
  1311. # This defines a "chinese character" as anything in the CJK Unicode block:
  1312. # https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block)
  1313. #
  1314. # Note that the CJK Unicode block is NOT all Japanese and Korean characters,
  1315. # despite its name. The modern Korean Hangul alphabet is a different block,
  1316. # as is Japanese Hiragana and Katakana. Those alphabets are used to write
  1317. # space-separated words, so they are not treated specially and handled
  1318. # like the all of the other languages.
  1319. if (
  1320. (cp >= 0x4E00 and cp <= 0x9FFF)
  1321. or (cp >= 0x3400 and cp <= 0x4DBF)
  1322. or (cp >= 0x20000 and cp <= 0x2A6DF)
  1323. or (cp >= 0x2A700 and cp <= 0x2B73F)
  1324. or (cp >= 0x2B740 and cp <= 0x2B81F)
  1325. or (cp >= 0x2B820 and cp <= 0x2CEAF)
  1326. or (cp >= 0xF900 and cp <= 0xFAFF)
  1327. or (cp >= 0x2F800 and cp <= 0x2FA1F)
  1328. ):
  1329. return True
  1330. return False
  1331. def _clean_text(self, text):
  1332. """Performs invalid character removal and whitespace cleanup on text."""
  1333. output = []
  1334. for char in text:
  1335. cp = ord(char)
  1336. if cp == 0 or cp == 0xFFFD or _is_control(char):
  1337. continue
  1338. if _is_whitespace(char):
  1339. output.append(" ")
  1340. else:
  1341. output.append(char)
  1342. return "".join(output)
  1343. # Copied from transformers.models.bert.tokenization_bert.WordpieceTokenizer
  1344. class WordpieceTokenizer:
  1345. """Runs WordPiece tokenization."""
  1346. def __init__(self, vocab, unk_token, max_input_chars_per_word=100):
  1347. self.vocab = vocab
  1348. self.unk_token = unk_token
  1349. self.max_input_chars_per_word = max_input_chars_per_word
  1350. def tokenize(self, text):
  1351. """
  1352. Tokenizes a piece of text into its word pieces. This uses a greedy longest-match-first algorithm to perform
  1353. tokenization using the given vocabulary.
  1354. For example, `input = "unaffable"` will return as output `["un", "##aff", "##able"]`.
  1355. Args:
  1356. text: A single token or whitespace separated tokens. This should have
  1357. already been passed through *BasicTokenizer*.
  1358. Returns:
  1359. A list of wordpiece tokens.
  1360. """
  1361. output_tokens = []
  1362. for token in whitespace_tokenize(text):
  1363. chars = list(token)
  1364. if len(chars) > self.max_input_chars_per_word:
  1365. output_tokens.append(self.unk_token)
  1366. continue
  1367. is_bad = False
  1368. start = 0
  1369. sub_tokens = []
  1370. while start < len(chars):
  1371. end = len(chars)
  1372. cur_substr = None
  1373. while start < end:
  1374. substr = "".join(chars[start:end])
  1375. if start > 0:
  1376. substr = "##" + substr
  1377. if substr in self.vocab:
  1378. cur_substr = substr
  1379. break
  1380. end -= 1
  1381. if cur_substr is None:
  1382. is_bad = True
  1383. break
  1384. sub_tokens.append(cur_substr)
  1385. start = end
  1386. if is_bad:
  1387. output_tokens.append(self.unk_token)
  1388. else:
  1389. output_tokens.extend(sub_tokens)
  1390. return output_tokens
  1391. __all__ = ["LayoutLMv2Tokenizer"]