tokenization_layoutlmv3.py 71 KB

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