tokenization_udop.py 70 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490
  1. # coding=utf-8
  2. # Copyright 2024 The HuggingFace Inc. team.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License
  15. """Tokenization classes for UDOP model."""
  16. import os
  17. import re
  18. import warnings
  19. from shutil import copyfile
  20. from typing import Any, Optional, Union
  21. import sentencepiece as spm
  22. from ...tokenization_utils import PreTrainedTokenizer
  23. from ...tokenization_utils_base import (
  24. AddedToken,
  25. BatchEncoding,
  26. EncodedInput,
  27. PreTokenizedInput,
  28. TextInput,
  29. TextInputPair,
  30. TruncationStrategy,
  31. )
  32. from ...utils import PaddingStrategy, TensorType, add_end_docstrings, logging
  33. from ...utils.import_utils import requires
  34. logger = logging.get_logger(__name__)
  35. SPIECE_UNDERLINE = "▁"
  36. UDOP_ENCODE_KWARGS_DOCSTRING = r"""
  37. add_special_tokens (`bool`, *optional*, defaults to `True`):
  38. Whether or not to encode the sequences with the special tokens relative to their model.
  39. padding (`bool`, `str` or [`~file_utils.PaddingStrategy`], *optional*, defaults to `False`):
  40. Activates and controls padding. Accepts the following values:
  41. - `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single
  42. sequence if provided).
  43. - `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum
  44. acceptable input length for the model if that argument is not provided.
  45. - `False` or `'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of different
  46. lengths).
  47. truncation (`bool`, `str` or [`~tokenization_utils_base.TruncationStrategy`], *optional*, defaults to `False`):
  48. Activates and controls truncation. Accepts the following values:
  49. - `True` or `'longest_first'`: Truncate to a maximum length specified with the argument `max_length` or
  50. to the maximum acceptable input length for the model if that argument is not provided. This will
  51. truncate token by token, removing a token from the longest sequence in the pair if a pair of
  52. sequences (or a batch of pairs) is provided.
  53. - `'only_first'`: Truncate to a maximum length specified with the argument `max_length` or to the
  54. maximum acceptable input length for the model if that argument is not provided. This will only
  55. truncate the first sequence of a pair if a pair of sequences (or a batch of pairs) is provided.
  56. - `'only_second'`: Truncate to a maximum length specified with the argument `max_length` or to the
  57. maximum acceptable input length for the model if that argument is not provided. This will only
  58. truncate the second sequence of a pair if a pair of sequences (or a batch of pairs) is provided.
  59. - `False` or `'do_not_truncate'` (default): No truncation (i.e., can output batch with sequence lengths
  60. greater than the model maximum admissible input size).
  61. max_length (`int`, *optional*):
  62. Controls the maximum length to use by one of the truncation/padding parameters.
  63. If left unset or set to `None`, this will use the predefined model maximum length if a maximum length
  64. is required by one of the truncation/padding parameters. If the model has no specific maximum input
  65. length (like XLNet) truncation/padding to a maximum length will be deactivated.
  66. stride (`int`, *optional*, defaults to 0):
  67. If set to a number along with `max_length`, the overflowing tokens returned when
  68. `return_overflowing_tokens=True` will contain some tokens from the end of the truncated sequence
  69. returned to provide some overlap between truncated and overflowing sequences. The value of this
  70. argument defines the number of overlapping tokens.
  71. pad_to_multiple_of (`int`, *optional*):
  72. If set will pad the sequence to a multiple of the provided value. This is especially useful to enable
  73. the use of Tensor Cores on NVIDIA hardware with compute capability `>= 7.5` (Volta).
  74. return_tensors (`str` or [`~file_utils.TensorType`], *optional*):
  75. If set, will return tensors instead of list of python integers. Acceptable values are:
  76. - `'tf'`: Return TensorFlow `tf.constant` objects.
  77. - `'pt'`: Return PyTorch `torch.Tensor` objects.
  78. - `'np'`: Return Numpy `np.ndarray` objects.
  79. return_token_type_ids (`bool`, *optional*):
  80. Whether to return token type IDs. If left to the default, will return the token type IDs according to
  81. the specific tokenizer's default, defined by the `return_outputs` attribute.
  82. [What are token type IDs?](../glossary#token-type-ids)
  83. return_attention_mask (`bool`, *optional*):
  84. Whether to return the attention mask. If left to the default, will return the attention mask according
  85. to the specific tokenizer's default, defined by the `return_outputs` attribute.
  86. [What are attention masks?](../glossary#attention-mask)
  87. return_overflowing_tokens (`bool`, *optional*, defaults to `False`):
  88. Whether or not to return overflowing token sequences. If a pair of sequences of input ids (or a batch
  89. of pairs) is provided with `truncation_strategy = longest_first` or `True`, an error is raised instead
  90. of returning overflowing tokens.
  91. return_special_tokens_mask (`bool`, *optional*, defaults to `False`):
  92. Whether or not to return special tokens mask information.
  93. return_offsets_mapping (`bool`, *optional*, defaults to `False`):
  94. Whether or not to return `(char_start, char_end)` for each token.
  95. This is only available on fast tokenizers inheriting from [`PreTrainedTokenizerFast`], if using
  96. Python's tokenizer, this method will raise `NotImplementedError`.
  97. return_length (`bool`, *optional*, defaults to `False`):
  98. Whether or not to return the lengths of the encoded inputs.
  99. verbose (`bool`, *optional*, defaults to `True`):
  100. Whether or not to print more information and warnings.
  101. **kwargs: passed to the `self.tokenize()` method
  102. Return:
  103. [`BatchEncoding`]: A [`BatchEncoding`] with the following fields:
  104. - **input_ids** -- List of token ids to be fed to a model.
  105. [What are input IDs?](../glossary#input-ids)
  106. - **bbox** -- List of bounding boxes to be fed to a model.
  107. - **token_type_ids** -- List of token type ids to be fed to a model (when `return_token_type_ids=True` or
  108. if *"token_type_ids"* is in `self.model_input_names`).
  109. [What are token type IDs?](../glossary#token-type-ids)
  110. - **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
  111. `return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names`).
  112. [What are attention masks?](../glossary#attention-mask)
  113. - **labels** -- List of labels to be fed to a model. (when `word_labels` is specified).
  114. - **overflowing_tokens** -- List of overflowing tokens sequences (when a `max_length` is specified and
  115. `return_overflowing_tokens=True`).
  116. - **num_truncated_tokens** -- Number of tokens truncated (when a `max_length` is specified and
  117. `return_overflowing_tokens=True`).
  118. - **special_tokens_mask** -- List of 0s and 1s, with 1 specifying added special tokens and 0 specifying
  119. regular sequence tokens (when `add_special_tokens=True` and `return_special_tokens_mask=True`).
  120. - **length** -- The length of the inputs (when `return_length=True`).
  121. """
  122. VOCAB_FILES_NAMES = {"vocab_file": "spiece.model", "tokenizer_file": "tokenizer.json"}
  123. @requires(backends=("sentencepiece",))
  124. class UdopTokenizer(PreTrainedTokenizer):
  125. """
  126. Adapted from [`LayoutXLMTokenizer`] and [`T5Tokenizer`]. Based on
  127. [SentencePiece](https://github.com/google/sentencepiece).
  128. This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
  129. this superclass for more information regarding those methods.
  130. Args:
  131. vocab_file (`str`):
  132. Path to the vocabulary file.
  133. eos_token (`str`, *optional*, defaults to `"</s>"`):
  134. The end of sequence token.
  135. <Tip>
  136. When building a sequence using special tokens, this is not the token that is used for the end of sequence.
  137. The token used is the `sep_token`.
  138. </Tip>
  139. unk_token (`str`, *optional*, defaults to `"<unk>"`):
  140. The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
  141. token instead.
  142. sep_token (`str`, *optional*, defaults to `"</s>"`):
  143. The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
  144. sequence classification or for a text and a question for question answering. It is also used as the last
  145. token of a sequence built with special tokens.
  146. pad_token (`str`, *optional*, defaults to `"<pad>"`):
  147. The token used for padding, for example when batching sequences of different lengths.
  148. sep_token_box (`list[int]`, *optional*, defaults to `[1000, 1000, 1000, 1000]`):
  149. The bounding box to use for the special [SEP] token.
  150. pad_token_box (`list[int]`, *optional*, defaults to `[0, 0, 0, 0]`):
  151. The bounding box to use for the special [PAD] token.
  152. pad_token_label (`int`, *optional*, defaults to -100):
  153. The label to use for padding tokens. Defaults to -100, which is the `ignore_index` of PyTorch's
  154. CrossEntropyLoss.
  155. only_label_first_subword (`bool`, *optional*, defaults to `True`):
  156. Whether or not to only label the first subword, in case word labels are provided.
  157. additional_special_tokens (`list[str]`, *optional*, defaults to `["<s>NOTUSED", "</s>NOTUSED"]`):
  158. Additional special tokens used by the tokenizer.
  159. sp_model_kwargs (`dict`, *optional*):
  160. Will be passed to the `SentencePieceProcessor.__init__()` method. The [Python wrapper for
  161. SentencePiece](https://github.com/google/sentencepiece/tree/master/python) can be used, among other things,
  162. to set:
  163. - `enable_sampling`: Enable subword regularization.
  164. - `nbest_size`: Sampling parameters for unigram. Invalid for BPE-Dropout.
  165. - `nbest_size = {0,1}`: No sampling is performed.
  166. - `nbest_size > 1`: samples from the nbest_size results.
  167. - `nbest_size < 0`: assuming that nbest_size is infinite and samples from the all hypothesis (lattice)
  168. using forward-filtering-and-backward-sampling algorithm.
  169. - `alpha`: Smoothing parameter for unigram sampling, and dropout probability of merge operations for
  170. BPE-dropout.
  171. legacy (`bool`, *optional*, defaults to `True`):
  172. Whether or not the `legacy` behaviour of the tokenizer should be used. Legacy is before the merge of #24622
  173. which includes fixes to properly handle tokens that appear after special tokens. A simple example:
  174. - `legacy=True`:
  175. ```python
  176. >>> from transformers import T5Tokenizer
  177. >>> tokenizer = T5Tokenizer.from_pretrained("t5-base", legacy=True)
  178. >>> tokenizer.encode("Hello <extra_id_0>.")
  179. [8774, 32099, 3, 5, 1]
  180. ```
  181. - `legacy=False`:
  182. ```python
  183. >>> from transformers import T5Tokenizer
  184. >>> tokenizer = T5Tokenizer.from_pretrained("t5-base", legacy=False)
  185. >>> tokenizer.encode("Hello <extra_id_0>.") # the extra space `[3]` is no longer here
  186. [8774, 32099, 5, 1]
  187. ```
  188. Checkout the pull request and the issue [here](https://github.com/huggingface/transformers/pull/24565) for
  189. more details.
  190. add_prefix_space (`bool`, *optional*, defaults to `True`):
  191. Whether or not to add an initial space to the input. This allows to treat the leading word just as any
  192. other word.
  193. Attributes:
  194. sp_model (`SentencePieceProcessor`):
  195. The *SentencePiece* processor that is used for every conversion (string, tokens and IDs).
  196. """
  197. vocab_files_names = VOCAB_FILES_NAMES
  198. model_input_names = ["input_ids", "attention_mask"]
  199. def __init__(
  200. self,
  201. vocab_file,
  202. eos_token="</s>",
  203. unk_token="<unk>",
  204. sep_token="</s>",
  205. pad_token="<pad>",
  206. sep_token_box=[1000, 1000, 1000, 1000],
  207. pad_token_box=[0, 0, 0, 0],
  208. pad_token_label=-100,
  209. only_label_first_subword=True,
  210. additional_special_tokens=None,
  211. sp_model_kwargs: Optional[dict[str, Any]] = None,
  212. legacy=True,
  213. add_prefix_space=True,
  214. **kwargs,
  215. ) -> None:
  216. eos_token = AddedToken(eos_token, special=True) if isinstance(eos_token, str) else eos_token
  217. unk_token = AddedToken(unk_token, special=True) if isinstance(unk_token, str) else unk_token
  218. sep_token = AddedToken(sep_token, special=True) if isinstance(sep_token, str) else sep_token
  219. pad_token = AddedToken(pad_token, special=True) if isinstance(pad_token, str) else pad_token
  220. self.legacy = legacy
  221. self.add_prefix_space = add_prefix_space
  222. self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs
  223. self.vocab_file = vocab_file
  224. self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
  225. self.sp_model.Load(vocab_file)
  226. # additional properties
  227. self.sep_token_box = sep_token_box
  228. self.pad_token_box = pad_token_box
  229. self.pad_token_label = pad_token_label
  230. self.only_label_first_subword = only_label_first_subword
  231. super().__init__(
  232. eos_token=eos_token,
  233. unk_token=unk_token,
  234. sep_token=sep_token,
  235. pad_token=pad_token,
  236. sep_token_box=sep_token_box,
  237. pad_token_box=pad_token_box,
  238. pad_token_label=pad_token_label,
  239. only_label_first_subword=only_label_first_subword,
  240. additional_special_tokens=additional_special_tokens,
  241. sp_model_kwargs=self.sp_model_kwargs,
  242. legacy=legacy,
  243. add_prefix_space=add_prefix_space,
  244. **kwargs,
  245. )
  246. @property
  247. def vocab_size(self):
  248. return len(self.sp_model)
  249. # Copied from transformers.models.t5.tokenization_t5.T5Tokenizer.get_vocab
  250. def get_vocab(self):
  251. vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size)}
  252. vocab.update(self.added_tokens_encoder)
  253. return vocab
  254. # Copied from transformers.models.t5.tokenization_t5.T5Tokenizer.get_special_tokens_mask
  255. def get_special_tokens_mask(
  256. self, token_ids_0: list[int], token_ids_1: Optional[list[int]] = None, already_has_special_tokens: bool = False
  257. ) -> list[int]:
  258. """
  259. Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
  260. special tokens using the tokenizer `prepare_for_model` method.
  261. Args:
  262. token_ids_0 (`list[int]`):
  263. List of IDs.
  264. token_ids_1 (`list[int]`, *optional*):
  265. Optional second list of IDs for sequence pairs.
  266. already_has_special_tokens (`bool`, *optional*, defaults to `False`):
  267. Whether or not the token list is already formatted with special tokens for the model.
  268. Returns:
  269. `list[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
  270. """
  271. if already_has_special_tokens:
  272. return super().get_special_tokens_mask(
  273. token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
  274. )
  275. # normal case: some special tokens
  276. if token_ids_1 is None:
  277. return ([0] * len(token_ids_0)) + [1]
  278. return ([0] * len(token_ids_0)) + [1] + ([0] * len(token_ids_1)) + [1]
  279. # Copied from transformers.models.t5.tokenization_t5.T5Tokenizer.get_sentinel_tokens
  280. def get_sentinel_tokens(self):
  281. return list(
  282. set(filter(lambda x: bool(re.search(r"<extra_id_\d+>", x)) is not None, self.additional_special_tokens))
  283. )
  284. # Copied from transformers.models.t5.tokenization_t5.T5Tokenizer.get_sentinel_token_ids
  285. def get_sentinel_token_ids(self):
  286. return [self.convert_tokens_to_ids(token) for token in self.get_sentinel_tokens()]
  287. # Copied from transformers.models.t5.tokenization_t5.T5Tokenizer._add_eos_if_not_present
  288. def _add_eos_if_not_present(self, token_ids: list[int]) -> list[int]:
  289. """Do not add eos again if user already added it."""
  290. if len(token_ids) > 0 and token_ids[-1] == self.eos_token_id:
  291. warnings.warn(
  292. f"This sequence already has {self.eos_token}. In future versions this behavior may lead to duplicated"
  293. " eos tokens being added."
  294. )
  295. return token_ids
  296. else:
  297. return token_ids + [self.eos_token_id]
  298. # Copied from transformers.models.t5.tokenization_t5.T5Tokenizer.create_token_type_ids_from_sequences
  299. def create_token_type_ids_from_sequences(
  300. self, token_ids_0: list[int], token_ids_1: Optional[list[int]] = None
  301. ) -> list[int]:
  302. """
  303. Create a mask from the two sequences passed to be used in a sequence-pair classification task. T5 does not make
  304. use of token type ids, therefore a list of zeros is returned.
  305. Args:
  306. token_ids_0 (`list[int]`):
  307. List of IDs.
  308. token_ids_1 (`list[int]`, *optional*):
  309. Optional second list of IDs for sequence pairs.
  310. Returns:
  311. `list[int]`: List of zeros.
  312. """
  313. eos = [self.eos_token_id]
  314. if token_ids_1 is None:
  315. return len(token_ids_0 + eos) * [0]
  316. return len(token_ids_0 + eos + token_ids_1 + eos) * [0]
  317. # Copied from transformers.models.t5.tokenization_t5.T5Tokenizer.build_inputs_with_special_tokens
  318. def build_inputs_with_special_tokens(
  319. self, token_ids_0: list[int], token_ids_1: Optional[list[int]] = None
  320. ) -> list[int]:
  321. """
  322. Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
  323. adding special tokens. A sequence has the following format:
  324. - single sequence: `X </s>`
  325. - pair of sequences: `A </s> B </s>`
  326. Args:
  327. token_ids_0 (`list[int]`):
  328. List of IDs to which the special tokens will be added.
  329. token_ids_1 (`list[int]`, *optional*):
  330. Optional second list of IDs for sequence pairs.
  331. Returns:
  332. `list[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
  333. """
  334. token_ids_0 = self._add_eos_if_not_present(token_ids_0)
  335. if token_ids_1 is None:
  336. return token_ids_0
  337. else:
  338. token_ids_1 = self._add_eos_if_not_present(token_ids_1)
  339. return token_ids_0 + token_ids_1
  340. # Copied from transformers.models.t5.tokenization_t5.T5Tokenizer.__getstate__
  341. def __getstate__(self):
  342. state = self.__dict__.copy()
  343. state["sp_model"] = None
  344. return state
  345. def __setstate__(self, d):
  346. self.__dict__.update(d)
  347. self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
  348. self.sp_model.Load(self.vocab_file)
  349. # Copied from transformers.models.t5.tokenization_t5.T5Tokenizer.tokenize
  350. def tokenize(self, text: "TextInput", **kwargs) -> list[str]:
  351. """
  352. Converts a string to a list of tokens. If `self.legacy` is set to `False`, a prefix token is added unless the
  353. first token is special.
  354. """
  355. if self.legacy or len(text) == 0:
  356. return super().tokenize(text, **kwargs)
  357. text = text.replace(SPIECE_UNDERLINE, " ")
  358. if self.add_prefix_space:
  359. text = SPIECE_UNDERLINE + text
  360. tokens = super().tokenize(text, **kwargs)
  361. if len(tokens) > 1 and tokens[0] == SPIECE_UNDERLINE and tokens[1] in self.all_special_tokens:
  362. tokens = tokens[1:]
  363. return tokens
  364. # Copied from transformers.models.t5.tokenization_t5.T5Tokenizer._tokenize
  365. def _tokenize(self, text, **kwargs):
  366. """
  367. Returns a tokenized string.
  368. We de-activated the `add_dummy_prefix` option, thus the sentencepiece internals will always strip any
  369. SPIECE_UNDERLINE. For example: `self.sp_model.encode(f"{SPIECE_UNDERLINE}Hey", out_type = str)` will give
  370. `['H', 'e', 'y']` instead of `['▁He', 'y']`. Thus we always encode `f"{unk_token}text"` and strip the
  371. `unk_token`. Here is an example with `unk_token = "<unk>"` and `unk_token_length = 4`.
  372. `self.tokenizer.sp_model.encode("<unk> Hey", out_type = str)[4:]`.
  373. """
  374. if self.legacy or not text.startswith((SPIECE_UNDERLINE, " ")):
  375. return self.sp_model.encode(text, out_type=str)
  376. # 1. Encode string + prefix ex: "<unk> Hey"
  377. tokens = self.sp_model.encode(self.unk_token + text, out_type=str)
  378. # 2. Remove self.unk_token from ['<','unk','>', '▁Hey']
  379. return tokens[self.unk_token_length :] if len(tokens) >= self.unk_token_length else tokens
  380. def _convert_token_to_id(self, token):
  381. """Converts a token (str) in an id using the vocab."""
  382. return self.sp_model.piece_to_id(token)
  383. def _convert_id_to_token(self, index):
  384. """Converts an index (integer) in a token (str) using the vocab."""
  385. return self.sp_model.IdToPiece(index)
  386. # Copied from transformers.models.t5.tokenization_t5.T5Tokenizer.convert_tokens_to_string
  387. def convert_tokens_to_string(self, tokens):
  388. """Converts a sequence of tokens (string) in a single string."""
  389. # since we manually add the prefix space, we have to remove it when decoding
  390. if tokens[0].startswith(SPIECE_UNDERLINE) and self.add_prefix_space:
  391. tokens[0] = tokens[0][1:]
  392. current_sub_tokens = []
  393. out_string = ""
  394. prev_is_special = False
  395. for token in tokens:
  396. # make sure that special tokens are not decoded using sentencepiece model
  397. if token in self.all_special_tokens:
  398. if not prev_is_special:
  399. out_string += " "
  400. out_string += self.sp_model.decode(current_sub_tokens) + token
  401. prev_is_special = True
  402. current_sub_tokens = []
  403. else:
  404. current_sub_tokens.append(token)
  405. prev_is_special = False
  406. out_string += self.sp_model.decode(current_sub_tokens)
  407. return out_string.strip()
  408. # Copied from transformers.models.t5.tokenization_t5.T5Tokenizer.save_vocabulary
  409. def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> tuple[str]:
  410. if not os.path.isdir(save_directory):
  411. logger.error(f"Vocabulary path ({save_directory}) should be a directory")
  412. return
  413. out_vocab_file = os.path.join(
  414. save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
  415. )
  416. if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file) and os.path.isfile(self.vocab_file):
  417. copyfile(self.vocab_file, out_vocab_file)
  418. elif not os.path.isfile(self.vocab_file):
  419. with open(out_vocab_file, "wb") as fi:
  420. content_spiece_model = self.sp_model.serialized_model_proto()
  421. fi.write(content_spiece_model)
  422. return (out_vocab_file,)
  423. @add_end_docstrings(UDOP_ENCODE_KWARGS_DOCSTRING)
  424. def __call__(
  425. self,
  426. text: Union[TextInput, PreTokenizedInput, list[TextInput], list[PreTokenizedInput]] = None,
  427. text_pair: Optional[Union[PreTokenizedInput, list[PreTokenizedInput]]] = None,
  428. boxes: Optional[Union[list[list[int]], list[list[list[int]]]]] = None,
  429. word_labels: Optional[Union[list[int], list[list[int]]]] = None,
  430. text_target: Union[TextInput, PreTokenizedInput, list[TextInput], list[PreTokenizedInput]] = None,
  431. text_pair_target: Optional[
  432. Union[TextInput, PreTokenizedInput, list[TextInput], list[PreTokenizedInput]]
  433. ] = None,
  434. **kwargs,
  435. ) -> BatchEncoding:
  436. if text is None and text_target is None:
  437. raise ValueError("You need to specify either `text` or `text_target`.")
  438. if text is not None:
  439. # The context manager will send the inputs as normal texts and not text_target, but we shouldn't change the
  440. # input mode in this case.
  441. if not self._in_target_context_manager:
  442. self._switch_to_input_mode()
  443. encodings = self.call_boxes(text=text, text_pair=text_pair, boxes=boxes, word_labels=word_labels, **kwargs)
  444. if text_target is not None:
  445. self._switch_to_target_mode()
  446. target_encodings = self._call_one(text=text_target, text_pair=text_pair_target, **kwargs)
  447. # Leave back tokenizer in input mode
  448. self._switch_to_input_mode()
  449. if text_target is None:
  450. return encodings
  451. elif text is None:
  452. return target_encodings
  453. else:
  454. encodings["labels"] = target_encodings["input_ids"]
  455. return encodings
  456. def call_boxes(
  457. self,
  458. text: Union[TextInput, PreTokenizedInput, list[TextInput], list[PreTokenizedInput]],
  459. text_pair: Optional[Union[PreTokenizedInput, list[PreTokenizedInput]]] = None,
  460. boxes: Optional[Union[list[list[int]], list[list[list[int]]]]] = None,
  461. word_labels: Optional[Union[list[int], list[list[int]]]] = None,
  462. add_special_tokens: bool = True,
  463. padding: Union[bool, str, PaddingStrategy] = False,
  464. truncation: Union[bool, str, TruncationStrategy] = None,
  465. max_length: Optional[int] = None,
  466. stride: int = 0,
  467. pad_to_multiple_of: Optional[int] = None,
  468. padding_side: Optional[str] = None,
  469. return_tensors: Optional[Union[str, TensorType]] = None,
  470. return_token_type_ids: Optional[bool] = None,
  471. return_attention_mask: Optional[bool] = None,
  472. return_overflowing_tokens: bool = False,
  473. return_special_tokens_mask: bool = False,
  474. return_offsets_mapping: bool = False,
  475. return_length: bool = False,
  476. verbose: bool = True,
  477. **kwargs,
  478. ) -> BatchEncoding:
  479. """
  480. Main method to tokenize and prepare for the model one or several sequence(s) or one or several pair(s) of
  481. sequences with word-level normalized bounding boxes and optional labels.
  482. Args:
  483. text (`str`, `list[str]`, `list[list[str]]`):
  484. The sequence or batch of sequences to be encoded. Each sequence can be a string, a list of strings
  485. (words of a single example or questions of a batch of examples) or a list of list of strings (batch of
  486. words).
  487. text_pair (`list[str]`, `list[list[str]]`):
  488. The sequence or batch of sequences to be encoded. Each sequence should be a list of strings
  489. (pretokenized string).
  490. boxes (`list[list[int]]`, `list[list[list[int]]]`):
  491. Word-level bounding boxes. Each bounding box should be normalized to be on a 0-1000 scale.
  492. word_labels (`list[int]`, `list[list[int]]`, *optional*):
  493. Word-level integer labels (for token classification tasks such as FUNSD, CORD).
  494. """
  495. # Input type checking for clearer error
  496. def _is_valid_text_input(t):
  497. if isinstance(t, str):
  498. # Strings are fine
  499. return True
  500. elif isinstance(t, (list, tuple)):
  501. # List are fine as long as they are...
  502. if len(t) == 0:
  503. # ... empty
  504. return True
  505. elif isinstance(t[0], str):
  506. # ... list of strings
  507. return True
  508. elif isinstance(t[0], (list, tuple)):
  509. # ... list with an empty list or with a list of strings
  510. return len(t[0]) == 0 or isinstance(t[0][0], str)
  511. else:
  512. return False
  513. else:
  514. return False
  515. if text_pair is not None:
  516. # in case text + text_pair are provided, text = questions, text_pair = words
  517. if not _is_valid_text_input(text):
  518. raise ValueError("text input must of type `str` (single example) or `list[str]` (batch of examples). ")
  519. if not isinstance(text_pair, (list, tuple)):
  520. raise ValueError(
  521. "words must of type `list[str]` (single pretokenized example), "
  522. "or `list[list[str]]` (batch of pretokenized examples)."
  523. )
  524. else:
  525. # in case only text is provided => must be words
  526. if not isinstance(text, (list, tuple)):
  527. raise ValueError(
  528. "Words must of type `list[str]` (single pretokenized example), "
  529. "or `list[list[str]]` (batch of pretokenized examples)."
  530. )
  531. if text_pair is not None:
  532. is_batched = isinstance(text, (list, tuple))
  533. else:
  534. is_batched = isinstance(text, (list, tuple)) and text and isinstance(text[0], (list, tuple))
  535. words = text if text_pair is None else text_pair
  536. if boxes is None:
  537. raise ValueError("You must provide corresponding bounding boxes")
  538. if is_batched:
  539. if len(words) != len(boxes):
  540. raise ValueError("You must provide words and boxes for an equal amount of examples")
  541. for words_example, boxes_example in zip(words, boxes):
  542. if len(words_example) != len(boxes_example):
  543. raise ValueError("You must provide as many words as there are bounding boxes")
  544. else:
  545. if len(words) != len(boxes):
  546. raise ValueError("You must provide as many words as there are bounding boxes")
  547. if is_batched:
  548. if text_pair is not None and len(text) != len(text_pair):
  549. raise ValueError(
  550. f"batch length of `text`: {len(text)} does not match batch length of `text_pair`:"
  551. f" {len(text_pair)}."
  552. )
  553. batch_text_or_text_pairs = list(zip(text, text_pair)) if text_pair is not None else text
  554. is_pair = bool(text_pair is not None)
  555. return self.batch_encode_plus_boxes(
  556. batch_text_or_text_pairs=batch_text_or_text_pairs,
  557. is_pair=is_pair,
  558. boxes=boxes,
  559. word_labels=word_labels,
  560. add_special_tokens=add_special_tokens,
  561. padding=padding,
  562. truncation=truncation,
  563. max_length=max_length,
  564. stride=stride,
  565. pad_to_multiple_of=pad_to_multiple_of,
  566. padding_side=padding_side,
  567. return_tensors=return_tensors,
  568. return_token_type_ids=return_token_type_ids,
  569. return_attention_mask=return_attention_mask,
  570. return_overflowing_tokens=return_overflowing_tokens,
  571. return_special_tokens_mask=return_special_tokens_mask,
  572. return_offsets_mapping=return_offsets_mapping,
  573. return_length=return_length,
  574. verbose=verbose,
  575. **kwargs,
  576. )
  577. else:
  578. return self.encode_plus_boxes(
  579. text=text,
  580. text_pair=text_pair,
  581. boxes=boxes,
  582. word_labels=word_labels,
  583. add_special_tokens=add_special_tokens,
  584. padding=padding,
  585. truncation=truncation,
  586. max_length=max_length,
  587. stride=stride,
  588. pad_to_multiple_of=pad_to_multiple_of,
  589. padding_side=padding_side,
  590. return_tensors=return_tensors,
  591. return_token_type_ids=return_token_type_ids,
  592. return_attention_mask=return_attention_mask,
  593. return_overflowing_tokens=return_overflowing_tokens,
  594. return_special_tokens_mask=return_special_tokens_mask,
  595. return_offsets_mapping=return_offsets_mapping,
  596. return_length=return_length,
  597. verbose=verbose,
  598. **kwargs,
  599. )
  600. def batch_encode_plus_boxes(
  601. self,
  602. batch_text_or_text_pairs: Union[
  603. list[TextInput],
  604. list[TextInputPair],
  605. list[PreTokenizedInput],
  606. ],
  607. is_pair: Optional[bool] = None,
  608. boxes: Optional[list[list[list[int]]]] = None,
  609. word_labels: Optional[list[list[int]]] = None,
  610. add_special_tokens: bool = True,
  611. padding: Union[bool, str, PaddingStrategy] = False,
  612. truncation: Union[bool, str, TruncationStrategy] = None,
  613. max_length: Optional[int] = None,
  614. stride: int = 0,
  615. is_split_into_words: bool = False,
  616. pad_to_multiple_of: Optional[int] = None,
  617. padding_side: Optional[str] = None,
  618. return_tensors: Optional[Union[str, TensorType]] = None,
  619. return_token_type_ids: Optional[bool] = None,
  620. return_attention_mask: Optional[bool] = None,
  621. return_overflowing_tokens: bool = False,
  622. return_special_tokens_mask: bool = False,
  623. return_offsets_mapping: bool = False,
  624. return_length: bool = False,
  625. verbose: bool = True,
  626. **kwargs,
  627. ) -> BatchEncoding:
  628. """
  629. Tokenize and prepare for the model a list of sequences or a list of pairs of sequences.
  630. Args:
  631. batch_text_or_text_pairs (`list[str]`, `list[tuple[str, str]]`, `list[list[str]]`, `list[tuple[list[str], list[str]]]`, and for not-fast tokenizers, also `list[list[int]]`, `list[tuple[list[int], list[int]]]`):
  632. Batch of sequences or pair of sequences to be encoded. This can be a list of
  633. string/string-sequences/int-sequences or a list of pair of string/string-sequences/int-sequence (see
  634. details in `encode_plus`).
  635. """
  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_boxes(
  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. is_split_into_words=is_split_into_words,
  656. pad_to_multiple_of=pad_to_multiple_of,
  657. padding_side=padding_side,
  658. return_tensors=return_tensors,
  659. return_token_type_ids=return_token_type_ids,
  660. return_attention_mask=return_attention_mask,
  661. return_overflowing_tokens=return_overflowing_tokens,
  662. return_special_tokens_mask=return_special_tokens_mask,
  663. return_offsets_mapping=return_offsets_mapping,
  664. return_length=return_length,
  665. verbose=verbose,
  666. **kwargs,
  667. )
  668. def encode_boxes(
  669. self,
  670. text: Union[TextInput, PreTokenizedInput, EncodedInput],
  671. text_pair: Optional[Union[TextInput, PreTokenizedInput, EncodedInput]] = None,
  672. boxes: Optional[list[list[int]]] = None,
  673. word_labels: Optional[list[list[int]]] = None,
  674. add_special_tokens: bool = True,
  675. padding: Union[bool, str, PaddingStrategy] = False,
  676. truncation: Union[bool, str, TruncationStrategy] = None,
  677. max_length: Optional[int] = None,
  678. stride: int = 0,
  679. return_tensors: Optional[Union[str, TensorType]] = None,
  680. **kwargs,
  681. ) -> list[int]:
  682. """
  683. Args:
  684. Converts a string to a sequence of ids (integer), using the tokenizer and vocabulary. Same as doing
  685. `self.convert_tokens_to_ids(self.tokenize(text))`.
  686. text (`str`, `list[str]` or `list[int]`):
  687. The first sequence to be encoded. This can be a string, a list of strings (tokenized string using the
  688. `tokenize` method) or a list of integers (tokenized string ids using the `convert_tokens_to_ids`
  689. method).
  690. text_pair (`str`, `list[str]` or `list[int]`, *optional*):
  691. Optional second sequence to be encoded. This can be a string, a list of strings (tokenized string using
  692. the `tokenize` method) or a list of integers (tokenized string ids using the `convert_tokens_to_ids`
  693. method).
  694. """
  695. encoded_inputs = self.encode_plus_boxes(
  696. text,
  697. text_pair=text_pair,
  698. boxes=boxes,
  699. word_labels=word_labels,
  700. add_special_tokens=add_special_tokens,
  701. padding=padding,
  702. truncation=truncation,
  703. max_length=max_length,
  704. stride=stride,
  705. return_tensors=return_tensors,
  706. **kwargs,
  707. )
  708. return encoded_inputs["input_ids"]
  709. def encode_plus_boxes(
  710. self,
  711. text: Union[TextInput, PreTokenizedInput],
  712. text_pair: Optional[PreTokenizedInput] = None,
  713. boxes: Optional[list[list[int]]] = None,
  714. word_labels: Optional[list[list[int]]] = None,
  715. add_special_tokens: bool = True,
  716. padding: Union[bool, str, PaddingStrategy] = False,
  717. truncation: Union[bool, str, TruncationStrategy] = None,
  718. max_length: Optional[int] = None,
  719. stride: int = 0,
  720. is_split_into_words: bool = False,
  721. pad_to_multiple_of: Optional[int] = None,
  722. padding_side: Optional[str] = None,
  723. return_tensors: Optional[Union[str, TensorType]] = None,
  724. return_token_type_ids: Optional[bool] = None,
  725. return_attention_mask: Optional[bool] = None,
  726. return_overflowing_tokens: bool = False,
  727. return_special_tokens_mask: bool = False,
  728. return_offsets_mapping: bool = False,
  729. return_length: bool = False,
  730. verbose: bool = True,
  731. **kwargs,
  732. ) -> BatchEncoding:
  733. """
  734. Tokenize and prepare for the model a sequence or a pair of sequences.
  735. <Tip warning={true}>
  736. This method is deprecated, `__call__` should be used instead.
  737. </Tip>
  738. Args:
  739. text (`str`, `list[str]` or (for non-fast tokenizers) `list[int]`):
  740. The first sequence to be encoded. This can be a string, a list of strings (tokenized string using the
  741. `tokenize` method) or a list of integers (tokenized string ids using the `convert_tokens_to_ids`
  742. method).
  743. text_pair (`str`, `list[str]` or `list[int]`, *optional*):
  744. Optional second sequence to be encoded. This can be a string, a list of strings (tokenized string using
  745. the `tokenize` method) or a list of integers (tokenized string ids using the `convert_tokens_to_ids`
  746. method).
  747. """
  748. # Backward compatibility for 'truncation_strategy', 'pad_to_max_length'
  749. padding_strategy, truncation_strategy, max_length, kwargs = self._get_padding_truncation_strategies(
  750. padding=padding,
  751. truncation=truncation,
  752. max_length=max_length,
  753. pad_to_multiple_of=pad_to_multiple_of,
  754. verbose=verbose,
  755. **kwargs,
  756. )
  757. return self._encode_plus_boxes(
  758. text=text,
  759. text_pair=text_pair,
  760. boxes=boxes,
  761. word_labels=word_labels,
  762. add_special_tokens=add_special_tokens,
  763. padding_strategy=padding_strategy,
  764. truncation_strategy=truncation_strategy,
  765. max_length=max_length,
  766. stride=stride,
  767. is_split_into_words=is_split_into_words,
  768. pad_to_multiple_of=pad_to_multiple_of,
  769. padding_side=padding_side,
  770. return_tensors=return_tensors,
  771. return_token_type_ids=return_token_type_ids,
  772. return_attention_mask=return_attention_mask,
  773. return_overflowing_tokens=return_overflowing_tokens,
  774. return_special_tokens_mask=return_special_tokens_mask,
  775. return_offsets_mapping=return_offsets_mapping,
  776. return_length=return_length,
  777. verbose=verbose,
  778. **kwargs,
  779. )
  780. def _batch_encode_plus_boxes(
  781. self,
  782. batch_text_or_text_pairs: Union[
  783. list[TextInput],
  784. list[TextInputPair],
  785. list[PreTokenizedInput],
  786. ],
  787. is_pair: Optional[bool] = None,
  788. boxes: Optional[list[list[list[int]]]] = None,
  789. word_labels: Optional[list[list[int]]] = None,
  790. add_special_tokens: bool = True,
  791. padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
  792. truncation_strategy: TruncationStrategy = TruncationStrategy.DO_NOT_TRUNCATE,
  793. max_length: Optional[int] = None,
  794. stride: int = 0,
  795. pad_to_multiple_of: Optional[int] = None,
  796. padding_side: Optional[str] = None,
  797. return_tensors: Optional[Union[str, TensorType]] = None,
  798. return_token_type_ids: Optional[bool] = None,
  799. return_attention_mask: Optional[bool] = None,
  800. return_overflowing_tokens: bool = False,
  801. return_special_tokens_mask: bool = False,
  802. return_offsets_mapping: bool = False,
  803. return_length: bool = False,
  804. verbose: bool = True,
  805. **kwargs,
  806. ) -> BatchEncoding:
  807. if return_offsets_mapping:
  808. raise NotImplementedError(
  809. "return_offset_mapping is not available when using Python tokenizers. "
  810. "To use this feature, change your tokenizer to one deriving from "
  811. "transformers.PreTrainedTokenizerFast."
  812. )
  813. batch_outputs = self._batch_prepare_for_model_boxes(
  814. batch_text_or_text_pairs=batch_text_or_text_pairs,
  815. is_pair=is_pair,
  816. boxes=boxes,
  817. word_labels=word_labels,
  818. add_special_tokens=add_special_tokens,
  819. padding_strategy=padding_strategy,
  820. truncation_strategy=truncation_strategy,
  821. max_length=max_length,
  822. stride=stride,
  823. pad_to_multiple_of=pad_to_multiple_of,
  824. padding_side=padding_side,
  825. return_attention_mask=return_attention_mask,
  826. return_token_type_ids=return_token_type_ids,
  827. return_overflowing_tokens=return_overflowing_tokens,
  828. return_special_tokens_mask=return_special_tokens_mask,
  829. return_length=return_length,
  830. return_tensors=return_tensors,
  831. verbose=verbose,
  832. )
  833. return BatchEncoding(batch_outputs)
  834. @add_end_docstrings(UDOP_ENCODE_KWARGS_DOCSTRING)
  835. def _batch_prepare_for_model_boxes(
  836. self,
  837. batch_text_or_text_pairs,
  838. is_pair: Optional[bool] = None,
  839. boxes: Optional[list[list[int]]] = None,
  840. word_labels: Optional[list[list[int]]] = None,
  841. add_special_tokens: bool = True,
  842. padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
  843. truncation_strategy: TruncationStrategy = TruncationStrategy.DO_NOT_TRUNCATE,
  844. max_length: Optional[int] = None,
  845. stride: int = 0,
  846. pad_to_multiple_of: Optional[int] = None,
  847. padding_side: Optional[str] = None,
  848. return_tensors: Optional[str] = None,
  849. return_token_type_ids: Optional[bool] = None,
  850. return_attention_mask: Optional[bool] = None,
  851. return_overflowing_tokens: bool = False,
  852. return_special_tokens_mask: bool = False,
  853. return_length: bool = False,
  854. verbose: bool = True,
  855. ) -> BatchEncoding:
  856. """
  857. Prepares a sequence of input id, or a pair of sequences of inputs ids so that it can be used by the model. It
  858. adds special tokens, truncates sequences if overflowing while taking into account the special tokens and
  859. manages a moving window (with user defined stride) for overflowing tokens
  860. Args:
  861. batch_ids_pairs: list of tokenized input ids or input ids pairs
  862. """
  863. batch_outputs = {}
  864. for idx, example in enumerate(zip(batch_text_or_text_pairs, boxes)):
  865. batch_text_or_text_pair, boxes_example = example
  866. outputs = self.prepare_for_model_boxes(
  867. batch_text_or_text_pair[0] if is_pair else batch_text_or_text_pair,
  868. batch_text_or_text_pair[1] if is_pair else None,
  869. boxes_example,
  870. word_labels=word_labels[idx] if word_labels is not None else None,
  871. add_special_tokens=add_special_tokens,
  872. padding=PaddingStrategy.DO_NOT_PAD.value, # we pad in batch afterward
  873. truncation=truncation_strategy.value,
  874. max_length=max_length,
  875. stride=stride,
  876. pad_to_multiple_of=None, # we pad in batch afterward
  877. padding_side=None, # we pad in batch afterward
  878. return_attention_mask=False, # we pad in batch afterward
  879. return_token_type_ids=return_token_type_ids,
  880. return_overflowing_tokens=return_overflowing_tokens,
  881. return_special_tokens_mask=return_special_tokens_mask,
  882. return_length=return_length,
  883. return_tensors=None, # We convert the whole batch to tensors at the end
  884. prepend_batch_axis=False,
  885. verbose=verbose,
  886. )
  887. for key, value in outputs.items():
  888. if key not in batch_outputs:
  889. batch_outputs[key] = []
  890. batch_outputs[key].append(value)
  891. batch_outputs = self.pad(
  892. batch_outputs,
  893. padding=padding_strategy.value,
  894. max_length=max_length,
  895. pad_to_multiple_of=pad_to_multiple_of,
  896. padding_side=padding_side,
  897. return_attention_mask=return_attention_mask,
  898. )
  899. batch_outputs = BatchEncoding(batch_outputs, tensor_type=return_tensors)
  900. return batch_outputs
  901. def _encode_plus_boxes(
  902. self,
  903. text: Union[TextInput, PreTokenizedInput],
  904. text_pair: Optional[PreTokenizedInput] = None,
  905. boxes: Optional[list[list[int]]] = None,
  906. word_labels: Optional[list[int]] = None,
  907. add_special_tokens: bool = True,
  908. padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
  909. truncation_strategy: TruncationStrategy = TruncationStrategy.DO_NOT_TRUNCATE,
  910. max_length: Optional[int] = None,
  911. stride: int = 0,
  912. pad_to_multiple_of: Optional[int] = None,
  913. padding_side: Optional[str] = None,
  914. return_tensors: Optional[Union[str, TensorType]] = None,
  915. return_token_type_ids: Optional[bool] = None,
  916. return_attention_mask: Optional[bool] = None,
  917. return_overflowing_tokens: bool = False,
  918. return_special_tokens_mask: bool = False,
  919. return_offsets_mapping: bool = False,
  920. return_length: bool = False,
  921. verbose: bool = True,
  922. **kwargs,
  923. ) -> BatchEncoding:
  924. if return_offsets_mapping:
  925. raise NotImplementedError(
  926. "return_offset_mapping is not available when using Python tokenizers. "
  927. "To use this feature, change your tokenizer to one deriving from "
  928. "transformers.PreTrainedTokenizerFast. "
  929. "More information on available tokenizers at "
  930. "https://github.com/huggingface/transformers/pull/2674"
  931. )
  932. return self.prepare_for_model_boxes(
  933. text=text,
  934. text_pair=text_pair,
  935. boxes=boxes,
  936. word_labels=word_labels,
  937. add_special_tokens=add_special_tokens,
  938. padding=padding_strategy.value,
  939. truncation=truncation_strategy.value,
  940. max_length=max_length,
  941. stride=stride,
  942. pad_to_multiple_of=pad_to_multiple_of,
  943. padding_side=padding_side,
  944. return_tensors=return_tensors,
  945. prepend_batch_axis=True,
  946. return_attention_mask=return_attention_mask,
  947. return_token_type_ids=return_token_type_ids,
  948. return_overflowing_tokens=return_overflowing_tokens,
  949. return_special_tokens_mask=return_special_tokens_mask,
  950. return_length=return_length,
  951. verbose=verbose,
  952. )
  953. @add_end_docstrings(UDOP_ENCODE_KWARGS_DOCSTRING)
  954. def prepare_for_model_boxes(
  955. self,
  956. text: Union[TextInput, PreTokenizedInput],
  957. text_pair: Optional[PreTokenizedInput] = None,
  958. boxes: Optional[list[list[int]]] = None,
  959. word_labels: Optional[list[int]] = None,
  960. add_special_tokens: bool = True,
  961. padding: Union[bool, str, PaddingStrategy] = False,
  962. truncation: Union[bool, str, TruncationStrategy] = None,
  963. max_length: Optional[int] = None,
  964. stride: int = 0,
  965. pad_to_multiple_of: Optional[int] = None,
  966. padding_side: Optional[str] = None,
  967. return_tensors: Optional[Union[str, TensorType]] = None,
  968. return_token_type_ids: Optional[bool] = None,
  969. return_attention_mask: Optional[bool] = None,
  970. return_overflowing_tokens: bool = False,
  971. return_special_tokens_mask: bool = False,
  972. return_offsets_mapping: bool = False,
  973. return_length: bool = False,
  974. verbose: bool = True,
  975. prepend_batch_axis: bool = False,
  976. **kwargs,
  977. ) -> BatchEncoding:
  978. """
  979. Prepares a sequence or a pair of sequences so that it can be used by the model. It adds special tokens,
  980. truncates sequences if overflowing while taking into account the special tokens and manages a moving window
  981. (with user defined stride) for overflowing tokens.
  982. Word-level `boxes` are turned into token-level `bbox`. If provided, word-level `word_labels` are turned into
  983. token-level `labels`. The word label is used for the first token of the word, while remaining tokens are
  984. labeled with -100, such that they will be ignored by the loss function.
  985. Args:
  986. text (`str`, `list[str]`, `list[list[str]]`):
  987. The first sequence to be encoded. This can be a string, a list of strings or a list of list of strings.
  988. text_pair (`list[str]` or `list[int]`, *optional*):
  989. Optional second sequence to be encoded. This can be a list of strings (words of a single example) or a
  990. list of list of strings (words of a batch of examples).
  991. """
  992. # Backward compatibility for 'truncation_strategy', 'pad_to_max_length'
  993. padding_strategy, truncation_strategy, max_length, kwargs = self._get_padding_truncation_strategies(
  994. padding=padding,
  995. truncation=truncation,
  996. max_length=max_length,
  997. pad_to_multiple_of=pad_to_multiple_of,
  998. verbose=verbose,
  999. **kwargs,
  1000. )
  1001. tokens = []
  1002. pair_tokens = []
  1003. token_boxes = []
  1004. pair_token_boxes = []
  1005. labels = []
  1006. if text_pair is None:
  1007. if word_labels is None:
  1008. # CASE 1: document image classification (training + inference) + CASE 2: token classification (inference)
  1009. for word, box in zip(text, boxes):
  1010. if len(word) < 1: # skip empty words
  1011. continue
  1012. word_tokens = self.tokenize(word)
  1013. tokens.extend(word_tokens)
  1014. token_boxes.extend([box] * len(word_tokens))
  1015. else:
  1016. # CASE 2: token classification (training)
  1017. for word, box, label in zip(text, boxes, word_labels):
  1018. if len(word) < 1: # skip empty words
  1019. continue
  1020. word_tokens = self.tokenize(word)
  1021. tokens.extend(word_tokens)
  1022. token_boxes.extend([box] * len(word_tokens))
  1023. if self.only_label_first_subword:
  1024. # Use the real label id for the first token of the word, and padding ids for the remaining tokens
  1025. labels.extend([label] + [self.pad_token_label] * (len(word_tokens) - 1))
  1026. else:
  1027. labels.extend([label] * len(word_tokens))
  1028. else:
  1029. # CASE 3: document visual question answering (inference)
  1030. # text = question
  1031. # text_pair = words
  1032. tokens = self.tokenize(text)
  1033. token_boxes = [self.pad_token_box for _ in range(len(tokens))]
  1034. for word, box in zip(text_pair, boxes):
  1035. if len(word) < 1: # skip empty words
  1036. continue
  1037. word_tokens = self.tokenize(word)
  1038. pair_tokens.extend(word_tokens)
  1039. pair_token_boxes.extend([box] * len(word_tokens))
  1040. # Create ids + pair_ids
  1041. ids = self.convert_tokens_to_ids(tokens)
  1042. pair_ids = self.convert_tokens_to_ids(pair_tokens) if pair_tokens else None
  1043. # Compute the total size of the returned encodings
  1044. pair = bool(pair_ids is not None)
  1045. len_ids = len(ids)
  1046. len_pair_ids = len(pair_ids) if pair else 0
  1047. total_len = len_ids + len_pair_ids + (self.num_special_tokens_to_add(pair=pair) if add_special_tokens else 0)
  1048. # Truncation: Handle max sequence length
  1049. overflowing_tokens = []
  1050. overflowing_token_boxes = []
  1051. overflowing_labels = []
  1052. if truncation_strategy != TruncationStrategy.DO_NOT_TRUNCATE and max_length and total_len > max_length:
  1053. (
  1054. ids,
  1055. token_boxes,
  1056. pair_ids,
  1057. pair_token_boxes,
  1058. labels,
  1059. overflowing_tokens,
  1060. overflowing_token_boxes,
  1061. overflowing_labels,
  1062. ) = self.truncate_sequences(
  1063. ids,
  1064. token_boxes,
  1065. pair_ids=pair_ids,
  1066. pair_token_boxes=pair_token_boxes,
  1067. labels=labels,
  1068. num_tokens_to_remove=total_len - max_length,
  1069. truncation_strategy=truncation_strategy,
  1070. stride=stride,
  1071. )
  1072. if return_token_type_ids and not add_special_tokens:
  1073. raise ValueError(
  1074. "Asking to return token_type_ids while setting add_special_tokens to False "
  1075. "results in an undefined behavior. Please set add_special_tokens to True or "
  1076. "set return_token_type_ids to None."
  1077. )
  1078. # Load from model defaults
  1079. if return_token_type_ids is None:
  1080. return_token_type_ids = "token_type_ids" in self.model_input_names
  1081. if return_attention_mask is None:
  1082. return_attention_mask = "attention_mask" in self.model_input_names
  1083. encoded_inputs = {}
  1084. if return_overflowing_tokens:
  1085. encoded_inputs["overflowing_tokens"] = overflowing_tokens
  1086. encoded_inputs["overflowing_token_boxes"] = overflowing_token_boxes
  1087. encoded_inputs["overflowing_labels"] = overflowing_labels
  1088. encoded_inputs["num_truncated_tokens"] = total_len - max_length
  1089. # Add special tokens
  1090. if add_special_tokens:
  1091. sequence = self.build_inputs_with_special_tokens(ids, pair_ids)
  1092. token_type_ids = self.create_token_type_ids_from_sequences(ids, pair_ids)
  1093. token_boxes = token_boxes + [self.sep_token_box]
  1094. if pair_token_boxes:
  1095. pair_token_boxes = pair_token_boxes + [self.sep_token_box]
  1096. if labels:
  1097. labels = labels + [self.pad_token_label]
  1098. else:
  1099. sequence = ids + pair_ids if pair else ids
  1100. token_type_ids = [0] * len(ids) + ([0] * len(pair_ids) if pair else [])
  1101. # Build output dictionary
  1102. encoded_inputs["input_ids"] = sequence
  1103. encoded_inputs["bbox"] = token_boxes + pair_token_boxes
  1104. if return_token_type_ids:
  1105. encoded_inputs["token_type_ids"] = token_type_ids
  1106. if return_special_tokens_mask:
  1107. if add_special_tokens:
  1108. encoded_inputs["special_tokens_mask"] = self.get_special_tokens_mask(ids, pair_ids)
  1109. else:
  1110. encoded_inputs["special_tokens_mask"] = [0] * len(sequence)
  1111. if labels:
  1112. encoded_inputs["labels"] = labels
  1113. # Check lengths
  1114. self._eventual_warn_about_too_long_sequence(encoded_inputs["input_ids"], max_length, verbose)
  1115. # Padding
  1116. if padding_strategy != PaddingStrategy.DO_NOT_PAD or return_attention_mask:
  1117. encoded_inputs = self.pad(
  1118. encoded_inputs,
  1119. max_length=max_length,
  1120. padding=padding_strategy.value,
  1121. pad_to_multiple_of=pad_to_multiple_of,
  1122. padding_side=padding_side,
  1123. return_attention_mask=return_attention_mask,
  1124. )
  1125. if return_length:
  1126. encoded_inputs["length"] = len(encoded_inputs["input_ids"])
  1127. batch_outputs = BatchEncoding(
  1128. encoded_inputs, tensor_type=return_tensors, prepend_batch_axis=prepend_batch_axis
  1129. )
  1130. return batch_outputs
  1131. # Copied from transformers.models.layoutxlm.tokenization_layoutxlm.LayoutXLMTokenizer.truncate_sequences
  1132. def truncate_sequences(
  1133. self,
  1134. ids: list[int],
  1135. token_boxes: list[list[int]],
  1136. pair_ids: Optional[list[int]] = None,
  1137. pair_token_boxes: Optional[list[list[int]]] = None,
  1138. labels: Optional[list[int]] = None,
  1139. num_tokens_to_remove: int = 0,
  1140. truncation_strategy: Union[str, TruncationStrategy] = "longest_first",
  1141. stride: int = 0,
  1142. ) -> tuple[list[int], list[int], list[int]]:
  1143. """
  1144. Truncates a sequence pair in-place following the strategy.
  1145. Args:
  1146. ids (`list[int]`):
  1147. Tokenized input ids of the first sequence. Can be obtained from a string by chaining the `tokenize` and
  1148. `convert_tokens_to_ids` methods.
  1149. token_boxes (`list[list[int]]`):
  1150. Bounding boxes of the first sequence.
  1151. pair_ids (`list[int]`, *optional*):
  1152. Tokenized input ids of the second sequence. Can be obtained from a string by chaining the `tokenize`
  1153. and `convert_tokens_to_ids` methods.
  1154. pair_token_boxes (`list[list[int]]`, *optional*):
  1155. Bounding boxes of the second sequence.
  1156. labels (`list[int]`, *optional*):
  1157. Labels of the first sequence (for token classification tasks).
  1158. num_tokens_to_remove (`int`, *optional*, defaults to 0):
  1159. Number of tokens to remove using the truncation strategy.
  1160. truncation_strategy (`str` or [`~tokenization_utils_base.TruncationStrategy`], *optional*, defaults to `False`):
  1161. The strategy to follow for truncation. Can be:
  1162. - `'longest_first'`: Truncate to a maximum length specified with the argument `max_length` or to the
  1163. maximum acceptable input length for the model if that argument is not provided. This will truncate
  1164. token by token, removing a token from the longest sequence in the pair if a pair of sequences (or a
  1165. batch of pairs) is provided.
  1166. - `'only_first'`: Truncate to a maximum length specified with the argument `max_length` or to the
  1167. maximum acceptable input length for the model if that argument is not provided. This will only
  1168. truncate the first sequence of a pair if a pair of sequences (or a batch of pairs) is provided.
  1169. - `'only_second'`: Truncate to a maximum length specified with the argument `max_length` or to the
  1170. maximum acceptable input length for the model if that argument is not provided. This will only
  1171. truncate the second sequence of a pair if a pair of sequences (or a batch of pairs) is provided.
  1172. - `'do_not_truncate'` (default): No truncation (i.e., can output batch with sequence lengths greater
  1173. than the model maximum admissible input size).
  1174. stride (`int`, *optional*, defaults to 0):
  1175. If set to a positive number, the overflowing tokens returned will contain some tokens from the main
  1176. sequence returned. The value of this argument defines the number of additional tokens.
  1177. Returns:
  1178. `tuple[list[int], list[int], list[int]]`: The truncated `ids`, the truncated `pair_ids` and the list of
  1179. overflowing tokens.
  1180. """
  1181. if num_tokens_to_remove <= 0:
  1182. return ids, token_boxes, pair_ids, pair_token_boxes, labels, [], [], []
  1183. if not isinstance(truncation_strategy, TruncationStrategy):
  1184. truncation_strategy = TruncationStrategy(truncation_strategy)
  1185. overflowing_tokens = []
  1186. overflowing_token_boxes = []
  1187. overflowing_labels = []
  1188. if truncation_strategy == TruncationStrategy.LONGEST_FIRST:
  1189. for _ in range(num_tokens_to_remove):
  1190. if pair_ids is None or len(ids) > len(pair_ids):
  1191. if not overflowing_tokens:
  1192. window_len = min(len(ids), stride + 1)
  1193. else:
  1194. window_len = 1
  1195. overflowing_tokens.extend(ids[-window_len:])
  1196. overflowing_token_boxes.extend(token_boxes[-window_len:])
  1197. overflowing_labels.extend(labels[-window_len:])
  1198. ids = ids[:-1]
  1199. token_boxes = token_boxes[:-1]
  1200. labels = labels[:-1]
  1201. else:
  1202. if not overflowing_tokens:
  1203. window_len = min(len(pair_ids), stride + 1)
  1204. else:
  1205. window_len = 1
  1206. overflowing_tokens.extend(pair_ids[-window_len:])
  1207. overflowing_token_boxes.extend(pair_token_boxes[-window_len:])
  1208. pair_ids = pair_ids[:-1]
  1209. pair_token_boxes = pair_token_boxes[:-1]
  1210. elif truncation_strategy == TruncationStrategy.ONLY_FIRST:
  1211. if len(ids) > num_tokens_to_remove:
  1212. window_len = min(len(ids), stride + num_tokens_to_remove)
  1213. overflowing_tokens = ids[-window_len:]
  1214. overflowing_token_boxes = token_boxes[-window_len:]
  1215. overflowing_labels = labels[-window_len:]
  1216. ids = ids[:-num_tokens_to_remove]
  1217. token_boxes = token_boxes[:-num_tokens_to_remove]
  1218. labels = labels[:-num_tokens_to_remove]
  1219. else:
  1220. logger.error(
  1221. f"We need to remove {num_tokens_to_remove} to truncate the input "
  1222. f"but the first sequence has a length {len(ids)}. "
  1223. f"Please select another truncation strategy than {truncation_strategy}, "
  1224. "for instance 'longest_first' or 'only_second'."
  1225. )
  1226. elif truncation_strategy == TruncationStrategy.ONLY_SECOND and pair_ids is not None:
  1227. if len(pair_ids) > num_tokens_to_remove:
  1228. window_len = min(len(pair_ids), stride + num_tokens_to_remove)
  1229. overflowing_tokens = pair_ids[-window_len:]
  1230. overflowing_token_boxes = pair_token_boxes[-window_len:]
  1231. pair_ids = pair_ids[:-num_tokens_to_remove]
  1232. pair_token_boxes = pair_token_boxes[:-num_tokens_to_remove]
  1233. else:
  1234. logger.error(
  1235. f"We need to remove {num_tokens_to_remove} to truncate the input "
  1236. f"but the second sequence has a length {len(pair_ids)}. "
  1237. f"Please select another truncation strategy than {truncation_strategy}, "
  1238. "for instance 'longest_first' or 'only_first'."
  1239. )
  1240. return (
  1241. ids,
  1242. token_boxes,
  1243. pair_ids,
  1244. pair_token_boxes,
  1245. labels,
  1246. overflowing_tokens,
  1247. overflowing_token_boxes,
  1248. overflowing_labels,
  1249. )
  1250. # Copied from transformers.models.layoutxlm.tokenization_layoutxlm.LayoutXLMTokenizer._pad
  1251. def _pad(
  1252. self,
  1253. encoded_inputs: Union[dict[str, EncodedInput], BatchEncoding],
  1254. max_length: Optional[int] = None,
  1255. padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
  1256. pad_to_multiple_of: Optional[int] = None,
  1257. padding_side: Optional[str] = None,
  1258. return_attention_mask: Optional[bool] = None,
  1259. ) -> dict:
  1260. """
  1261. Pad encoded inputs (on left/right and up to predefined length or max length in the batch)
  1262. Args:
  1263. encoded_inputs:
  1264. Dictionary of tokenized inputs (`list[int]`) or batch of tokenized inputs (`list[list[int]]`).
  1265. max_length: maximum length of the returned list and optionally padding length (see below).
  1266. Will truncate by taking into account the special tokens.
  1267. padding_strategy: PaddingStrategy to use for padding.
  1268. - PaddingStrategy.LONGEST Pad to the longest sequence in the batch
  1269. - PaddingStrategy.MAX_LENGTH: Pad to the max length (default)
  1270. - PaddingStrategy.DO_NOT_PAD: Do not pad
  1271. The tokenizer padding sides are defined in self.padding_side:
  1272. - 'left': pads on the left of the sequences
  1273. - 'right': pads on the right of the sequences
  1274. pad_to_multiple_of: (optional) Integer if set will pad the sequence to a multiple of the provided value.
  1275. This is especially useful to enable the use of Tensor Core on NVIDIA hardware with compute capability
  1276. `>= 7.5` (Volta).
  1277. padding_side (`str`, *optional*):
  1278. The side on which the model should have padding applied. Should be selected between ['right', 'left'].
  1279. Default value is picked from the class attribute of the same name.
  1280. return_attention_mask:
  1281. (optional) Set to False to avoid returning attention mask (default: set to model specifics)
  1282. """
  1283. # Load from model defaults
  1284. if return_attention_mask is None:
  1285. return_attention_mask = "attention_mask" in self.model_input_names
  1286. required_input = encoded_inputs[self.model_input_names[0]]
  1287. if padding_strategy == PaddingStrategy.LONGEST:
  1288. max_length = len(required_input)
  1289. if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0):
  1290. max_length = ((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of
  1291. needs_to_be_padded = padding_strategy != PaddingStrategy.DO_NOT_PAD and len(required_input) != max_length
  1292. # Initialize attention mask if not present.
  1293. if return_attention_mask and "attention_mask" not in encoded_inputs:
  1294. encoded_inputs["attention_mask"] = [1] * len(required_input)
  1295. if needs_to_be_padded:
  1296. difference = max_length - len(required_input)
  1297. padding_side = padding_side if padding_side is not None else self.padding_side
  1298. if padding_side == "right":
  1299. if return_attention_mask:
  1300. encoded_inputs["attention_mask"] = encoded_inputs["attention_mask"] + [0] * difference
  1301. if "token_type_ids" in encoded_inputs:
  1302. encoded_inputs["token_type_ids"] = (
  1303. encoded_inputs["token_type_ids"] + [self.pad_token_type_id] * difference
  1304. )
  1305. if "bbox" in encoded_inputs:
  1306. encoded_inputs["bbox"] = encoded_inputs["bbox"] + [self.pad_token_box] * difference
  1307. if "labels" in encoded_inputs:
  1308. encoded_inputs["labels"] = encoded_inputs["labels"] + [self.pad_token_label] * difference
  1309. if "special_tokens_mask" in encoded_inputs:
  1310. encoded_inputs["special_tokens_mask"] = encoded_inputs["special_tokens_mask"] + [1] * difference
  1311. encoded_inputs[self.model_input_names[0]] = required_input + [self.pad_token_id] * difference
  1312. elif padding_side == "left":
  1313. if return_attention_mask:
  1314. encoded_inputs["attention_mask"] = [0] * difference + encoded_inputs["attention_mask"]
  1315. if "token_type_ids" in encoded_inputs:
  1316. encoded_inputs["token_type_ids"] = [self.pad_token_type_id] * difference + encoded_inputs[
  1317. "token_type_ids"
  1318. ]
  1319. if "bbox" in encoded_inputs:
  1320. encoded_inputs["bbox"] = [self.pad_token_box] * difference + encoded_inputs["bbox"]
  1321. if "labels" in encoded_inputs:
  1322. encoded_inputs["labels"] = [self.pad_token_label] * difference + encoded_inputs["labels"]
  1323. if "special_tokens_mask" in encoded_inputs:
  1324. encoded_inputs["special_tokens_mask"] = [1] * difference + encoded_inputs["special_tokens_mask"]
  1325. encoded_inputs[self.model_input_names[0]] = [self.pad_token_id] * difference + required_input
  1326. else:
  1327. raise ValueError("Invalid padding strategy:" + str(padding_side))
  1328. return encoded_inputs
  1329. __all__ = ["UdopTokenizer"]