tokenizer_utils_base.py 151 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500
  1. # Copyright (c) 2024 PaddlePaddle Authors. All Rights Reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import copy
  15. import io
  16. import json
  17. import os
  18. import warnings
  19. from collections import OrderedDict, UserDict
  20. from dataclasses import dataclass, field
  21. from enum import Enum
  22. from typing import Any, Dict, List, NamedTuple, Optional, Sequence, Tuple, Union
  23. import lazy_paddle as paddle
  24. import numpy as np
  25. from .....utils import logging
  26. __all__ = [
  27. "AddedToken",
  28. "FastEncoding",
  29. "ExplicitEnum",
  30. "PaddingStrategy",
  31. "TensorType",
  32. "TruncationStrategy",
  33. "CharSpan",
  34. "TokenSpan",
  35. "BatchEncoding",
  36. "SpecialTokensMixin",
  37. "PretrainedTokenizerBase",
  38. ]
  39. TOKENIZER_CONFIG_NAME = "tokenizer_config.json"
  40. CHAT_TEMPLATE_CONFIG_NAME = "chat_template.json"
  41. CHAT_TEMPLATE_CONFIG_NAME = "chat_template.json"
  42. VERY_LARGE_INTEGER = int(
  43. 1e30
  44. ) # This is used to set the max input length for a model with infinite size input
  45. LARGE_INTEGER = int(
  46. 1e20
  47. ) # This is used when we need something big but slightly smaller than VERY_LARGE_INTEGER
  48. # Define type aliases and NamedTuples
  49. TextInput = str
  50. PreTokenizedInput = List[str]
  51. EncodedInput = List[int]
  52. TextInputPair = Tuple[str, str]
  53. PreTokenizedInputPair = Tuple[List[str], List[str]]
  54. EncodedInputPair = Tuple[List[int], List[int]]
  55. # Slow tokenizers used to be saved in three separated files
  56. SPECIAL_TOKENS_MAP_FILE = "special_tokens_map.json"
  57. ADDED_TOKENS_FILE = "added_tokens.json"
  58. TOKENIZER_CONFIG_FILE = "tokenizer_config.json"
  59. @dataclass(frozen=True, eq=True)
  60. class AddedToken:
  61. """
  62. AddedToken represents a token to be added to a Tokenizer An AddedToken can have special options defining the
  63. way it should behave.
  64. """
  65. content: str = field(default_factory=str)
  66. single_word: bool = False
  67. lstrip: bool = False
  68. rstrip: bool = False
  69. normalized: bool = True
  70. special: bool = True
  71. def __getstate__(self):
  72. return self.__dict__
  73. def __str__(self):
  74. return self.content
  75. @dataclass
  76. class FastEncoding:
  77. """This is dummy class reserved for fast tokenizer"""
  78. class ExplicitEnum(Enum):
  79. """
  80. Enum with more explicit error message for missing values.
  81. """
  82. @classmethod
  83. def _missing_(cls, value):
  84. raise ValueError(
  85. f"{value} is not a valid {cls.__name__}, please select one of {list(cls._value2member_map_.keys())}"
  86. )
  87. class PaddingStrategy(ExplicitEnum):
  88. """
  89. Possible values for the `padding` argument in [`PretrainedTokenizerBase.__call__`]. Useful for tab-completion in an
  90. IDE.
  91. """
  92. LONGEST = "longest"
  93. MAX_LENGTH = "max_length"
  94. DO_NOT_PAD = "do_not_pad"
  95. class TensorType(ExplicitEnum):
  96. """
  97. Possible values for the `return_tensors` argument in [`PretrainedTokenizerBase.__call__`]. Useful for
  98. tab-completion in an IDE.
  99. """
  100. PADDLE = "pd"
  101. NUMPY = "np"
  102. def to_py_obj(obj):
  103. """
  104. Convert a Paddle tensor, Numpy array or python list to a python list.
  105. """
  106. if isinstance(obj, (dict, UserDict)):
  107. return {k: to_py_obj(v) for k, v in obj.items()}
  108. elif isinstance(obj, (list, tuple)):
  109. return [to_py_obj(o) for o in obj]
  110. elif isinstance(obj, paddle.Tensor):
  111. return obj.numpy().tolist()
  112. elif isinstance(obj, (np.ndarray, np.number)): # tolist also works on 0d np arrays
  113. return obj.tolist()
  114. else:
  115. return obj
  116. def _is_numpy(x):
  117. return isinstance(x, np.ndarray)
  118. class TruncationStrategy(ExplicitEnum):
  119. """
  120. Possible values for the `truncation` argument in [`PretrainedTokenizerBase.__call__`]. Useful for tab-completion in
  121. an IDE.
  122. """
  123. ONLY_FIRST = "only_first"
  124. ONLY_SECOND = "only_second"
  125. LONGEST_FIRST = "longest_first"
  126. DO_NOT_TRUNCATE = "do_not_truncate"
  127. class CharSpan(NamedTuple):
  128. """
  129. Character span in the original string.
  130. Args:
  131. start (`int`): Index of the first character in the original string.
  132. end (`int`): Index of the character following the last character in the original string.
  133. """
  134. start: int
  135. end: int
  136. class TokenSpan(NamedTuple):
  137. """
  138. Token span in an encoded string (list of tokens).
  139. Args:
  140. start (`int`): Index of the first token in the span.
  141. end (`int`): Index of the token following the last token in the span.
  142. """
  143. start: int
  144. end: int
  145. class BatchEncoding(UserDict):
  146. """
  147. Holds the output of the [`PretrainedTokenizerBase.__call__`],
  148. [`PretrainedTokenizerBase.encode_plus`] and
  149. [`PretrainedTokenizerBase.batch_encode_plus`] methods (tokens, attention_masks, etc).
  150. This class is derived from a python dictionary and can be used as a dictionary. In addition, this class exposes
  151. utility methods to map from word/character space to token space.
  152. Args:
  153. data (`dict`):
  154. Dictionary of lists/arrays/tensors returned by the `__call__`/`encode`/`batch_encode` methods
  155. ('input_ids', 'attention_mask', etc.).
  156. tensor_type (`Union[None, str, TensorType]`, *optional*):
  157. You can give a tensor_type here to convert the lists of integers in Paddle/Numpy Tensors at
  158. initialization.
  159. prepend_batch_axis (`bool`, *optional*, defaults to `False`):
  160. Whether or not to add a batch axis when converting to tensors (see `tensor_type` above).
  161. """
  162. def __init__(
  163. self,
  164. data: Optional[Dict[str, Any]] = None,
  165. encoding: Optional[Union[FastEncoding, Sequence[FastEncoding]]] = None,
  166. tensor_type: Union[None, str] = None,
  167. prepend_batch_axis: bool = False,
  168. n_sequences: Optional[int] = None,
  169. ):
  170. super().__init__(data)
  171. if isinstance(encoding, FastEncoding):
  172. encoding = [encoding]
  173. self._encodings = encoding
  174. if n_sequences is None and encoding is not None and len(encoding):
  175. n_sequences = encoding[0].n_sequences
  176. self._n_sequences = n_sequences
  177. self.convert_to_tensors(
  178. tensor_type=tensor_type, prepend_batch_axis=prepend_batch_axis
  179. )
  180. @property
  181. def n_sequences(self) -> Optional[int]:
  182. """
  183. `Optional[int]`: The number of sequences used to generate each sample from the batch encoded in this
  184. [`BatchEncoding`]. Currently can be one of `None` (unknown), `1` (a single sentence) or `2` (a pair of
  185. sentences)
  186. """
  187. return self._n_sequences
  188. @property
  189. def is_fast(self) -> bool:
  190. """
  191. `bool`: Indicate whether this [`BatchEncoding`] was generated from the result of a [`PretrainedFastTokenizer`]
  192. or not.
  193. """
  194. return self._encodings is not None
  195. def __getitem__(self, item: Union[int, str]) -> Union[Any, FastEncoding]:
  196. """
  197. If the key is a string, returns the value of the dict associated to `key` ('input_ids', 'attention_mask',
  198. etc.).
  199. If the key is an integer, get the `Encoding` for batch item with index `key`.
  200. """
  201. if isinstance(item, str):
  202. return self.data[item]
  203. elif self._encodings is not None:
  204. return self._encodings[item]
  205. else:
  206. raise KeyError(
  207. "Indexing with integers is not available when using tokenizer.__call__()"
  208. " with return_dict=True. Please set return_dict to False to use integer indexing."
  209. )
  210. def __getattr__(self, item: str):
  211. try:
  212. return self.data[item]
  213. except KeyError:
  214. raise AttributeError
  215. def __getstate__(self):
  216. return {"data": self.data, "encodings": self._encodings}
  217. def __setstate__(self, state):
  218. if "data" in state:
  219. self.data = state["data"]
  220. if "encodings" in state:
  221. self._encodings = state["encodings"]
  222. def keys(self):
  223. return self.data.keys()
  224. def values(self):
  225. return self.data.values()
  226. def items(self):
  227. return self.data.items()
  228. # After this point:
  229. # Extended properties and methods only available for fast tokenizers
  230. # not yet supported
  231. @property
  232. def encodings(self) -> Optional[List[FastEncoding]]:
  233. """
  234. `Optional[List[FastEncoding]]`: The list all encodings from the tokenization process. Returns `None` if
  235. the input was tokenized through Python (i.e., not a fast) tokenizer.
  236. """
  237. return self._encodings
  238. def tokens(self, batch_index: int = 0) -> List[str]:
  239. """
  240. Return the list of tokens (sub-parts of the input strings after word/subword splitting and before conversion to
  241. integer indices) at a given batch index (only works for the output of a fast tokenizer).
  242. Args:
  243. batch_index (`int`, *optional*, defaults to 0): The index to access in the batch.
  244. Returns:
  245. `List[str]`: The list of tokens at that index.
  246. """
  247. if not self._encodings:
  248. raise ValueError(
  249. "tokens() is not available when using Python-based tokenizers"
  250. )
  251. return self._encodings[batch_index].tokens
  252. def sequence_ids(self, batch_index: int = 0) -> List[Optional[int]]:
  253. """
  254. Return a list mapping the tokens to the id of their original sentences:
  255. - `None` for special tokens added around or between sequences,
  256. - `0` for tokens corresponding to words in the first sequence,
  257. - `1` for tokens corresponding to words in the second sequence when a pair of sequences was jointly
  258. encoded.
  259. Args:
  260. batch_index (`int`, *optional*, defaults to 0): The index to access in the batch.
  261. Returns:
  262. `List[Optional[int]]`: A list indicating the sequence id corresponding to each token. Special tokens added
  263. by the tokenizer are mapped to `None` and other tokens are mapped to the index of their corresponding
  264. sequence.
  265. """
  266. if not self._encodings:
  267. raise ValueError(
  268. "sequence_ids() is not available when using Python-based tokenizers"
  269. )
  270. return self._encodings[batch_index].sequence_ids
  271. def words(self, batch_index: int = 0) -> List[Optional[int]]:
  272. """
  273. Return a list mapping the tokens to their actual word in the initial sentence for a fast tokenizer.
  274. Args:
  275. batch_index (`int`, *optional*, defaults to 0): The index to access in the batch.
  276. Returns:
  277. `List[Optional[int]]`: A list indicating the word corresponding to each token. Special tokens added by the
  278. tokenizer are mapped to `None` and other tokens are mapped to the index of their corresponding word
  279. (several tokens will be mapped to the same word index if they are parts of that word).
  280. """
  281. if not self._encodings:
  282. raise ValueError(
  283. "words() is not available when using Python-based tokenizers"
  284. )
  285. warnings.warn(
  286. "`BatchEncoding.words()` property is deprecated and should be replaced with the identical, "
  287. "but more self-explanatory `BatchEncoding.word_ids()` property.",
  288. FutureWarning,
  289. )
  290. return self.word_ids(batch_index)
  291. def word_ids(self, batch_index: int = 0) -> List[Optional[int]]:
  292. """
  293. Return a list mapping the tokens to their actual word in the initial sentence for a fast tokenizer.
  294. Args:
  295. batch_index (`int`, *optional*, defaults to 0): The index to access in the batch.
  296. Returns:
  297. `List[Optional[int]]`: A list indicating the word corresponding to each token. Special tokens added by the
  298. tokenizer are mapped to `None` and other tokens are mapped to the index of their corresponding word
  299. (several tokens will be mapped to the same word index if they are parts of that word).
  300. """
  301. if not self._encodings:
  302. raise ValueError(
  303. "word_ids() is not available when using Python-based tokenizers"
  304. )
  305. return self._encodings[batch_index].word_ids
  306. def token_to_sequence(
  307. self, batch_or_token_index: int, token_index: Optional[int] = None
  308. ) -> int:
  309. """
  310. Get the index of the sequence represented by the given token. In the general use case, this method returns `0`
  311. for a single sequence or the first sequence of a pair, and `1` for the second sequence of a pair
  312. Can be called as:
  313. - `self.token_to_sequence(token_index)` if batch size is 1
  314. - `self.token_to_sequence(batch_index, token_index)` if batch size is greater than 1
  315. This method is particularly suited when the input sequences are provided as pre-tokenized sequences (i.e.,
  316. words are defined by the user). In this case it allows to easily associate encoded tokens with provided
  317. tokenized words.
  318. Args:
  319. batch_or_token_index (`int`):
  320. Index of the sequence in the batch. If the batch only comprises one sequence, this can be the index of
  321. the token in the sequence.
  322. token_index (`int`, *optional*):
  323. If a batch index is provided in *batch_or_token_index*, this can be the index of the token in the
  324. sequence.
  325. Returns:
  326. `int`: Index of the word in the input sequence.
  327. """
  328. if not self._encodings:
  329. raise ValueError(
  330. "token_to_sequence() is not available when using Python based tokenizers"
  331. )
  332. if token_index is not None:
  333. batch_index = batch_or_token_index
  334. else:
  335. batch_index = 0
  336. token_index = batch_or_token_index
  337. if batch_index < 0:
  338. batch_index = self._batch_size + batch_index
  339. if token_index < 0:
  340. token_index = self._seq_len + token_index
  341. return self._encodings[batch_index].token_to_sequence(token_index)
  342. def token_to_word(
  343. self, batch_or_token_index: int, token_index: Optional[int] = None
  344. ) -> int:
  345. """
  346. Get the index of the word corresponding (i.e. comprising) to an encoded token in a sequence of the batch.
  347. Can be called as:
  348. - `self.token_to_word(token_index)` if batch size is 1
  349. - `self.token_to_word(batch_index, token_index)` if batch size is greater than 1
  350. This method is particularly suited when the input sequences are provided as pre-tokenized sequences (i.e.,
  351. words are defined by the user). In this case it allows to easily associate encoded tokens with provided
  352. tokenized words.
  353. Args:
  354. batch_or_token_index (`int`):
  355. Index of the sequence in the batch. If the batch only comprise one sequence, this can be the index of
  356. the token in the sequence.
  357. token_index (`int`, *optional*):
  358. If a batch index is provided in *batch_or_token_index*, this can be the index of the token in the
  359. sequence.
  360. Returns:
  361. `int`: Index of the word in the input sequence.
  362. """
  363. if not self._encodings:
  364. raise ValueError(
  365. "token_to_word() is not available when using Python based tokenizers"
  366. )
  367. if token_index is not None:
  368. batch_index = batch_or_token_index
  369. else:
  370. batch_index = 0
  371. token_index = batch_or_token_index
  372. if batch_index < 0:
  373. batch_index = self._batch_size + batch_index
  374. if token_index < 0:
  375. token_index = self._seq_len + token_index
  376. return self._encodings[batch_index].token_to_word(token_index)
  377. def word_to_tokens(
  378. self,
  379. batch_or_word_index: int,
  380. word_index: Optional[int] = None,
  381. sequence_index: int = 0,
  382. ) -> Optional[TokenSpan]:
  383. """
  384. Get the encoded token span corresponding to a word in a sequence of the batch.
  385. Token spans are returned as a [`TokenSpan`] with:
  386. - **start** -- Index of the first token.
  387. - **end** -- Index of the token following the last token.
  388. Can be called as:
  389. - `self.word_to_tokens(word_index, sequence_index: int = 0)` if batch size is 1
  390. - `self.word_to_tokens(batch_index, word_index, sequence_index: int = 0)` if batch size is greater or equal to
  391. 1
  392. This method is particularly suited when the input sequences are provided as pre-tokenized sequences (i.e. words
  393. are defined by the user). In this case it allows to easily associate encoded tokens with provided tokenized
  394. words.
  395. Args:
  396. batch_or_word_index (`int`):
  397. Index of the sequence in the batch. If the batch only comprises one sequence, this can be the index of
  398. the word in the sequence.
  399. word_index (`int`, *optional*):
  400. If a batch index is provided in *batch_or_token_index*, this can be the index of the word in the
  401. sequence.
  402. sequence_index (`int`, *optional*, defaults to 0):
  403. If pair of sequences are encoded in the batch this can be used to specify which sequence in the pair (0
  404. or 1) the provided word index belongs to.
  405. Returns:
  406. Optional [`TokenSpan`] Span of tokens in the encoded sequence. Returns `None` if
  407. no tokens correspond to the word.
  408. """
  409. if not self._encodings:
  410. raise ValueError(
  411. "word_to_tokens() is not available when using Python based tokenizers"
  412. )
  413. if word_index is not None:
  414. batch_index = batch_or_word_index
  415. else:
  416. batch_index = 0
  417. word_index = batch_or_word_index
  418. if batch_index < 0:
  419. batch_index = self._batch_size + batch_index
  420. if word_index < 0:
  421. word_index = self._seq_len + word_index
  422. span = self._encodings[batch_index].word_to_tokens(word_index, sequence_index)
  423. return TokenSpan(*span) if span is not None else None
  424. def token_to_chars(
  425. self, batch_or_token_index: int, token_index: Optional[int] = None
  426. ) -> CharSpan:
  427. """
  428. Get the character span corresponding to an encoded token in a sequence of the batch.
  429. Character spans are returned as a [`CharSpan`] with:
  430. - **start** -- Index of the first character in the original string associated to the token.
  431. - **end** -- Index of the character following the last character in the original string associated to the
  432. token.
  433. Can be called as:
  434. - `self.token_to_chars(token_index)` if batch size is 1
  435. - `self.token_to_chars(batch_index, token_index)` if batch size is greater or equal to 1
  436. Args:
  437. batch_or_token_index (`int`):
  438. Index of the sequence in the batch. If the batch only comprise one sequence, this can be the index of
  439. the token in the sequence.
  440. token_index (`int`, *optional*):
  441. If a batch index is provided in *batch_or_token_index*, this can be the index of the token or tokens in
  442. the sequence.
  443. Returns:
  444. [`CharSpan`]: Span of characters in the original string.
  445. """
  446. if not self._encodings:
  447. raise ValueError(
  448. "token_to_chars() is not available when using Python based tokenizers"
  449. )
  450. if token_index is not None:
  451. batch_index = batch_or_token_index
  452. else:
  453. batch_index = 0
  454. token_index = batch_or_token_index
  455. return CharSpan(*(self._encodings[batch_index].token_to_chars(token_index)))
  456. def char_to_token(
  457. self,
  458. batch_or_char_index: int,
  459. char_index: Optional[int] = None,
  460. sequence_index: int = 0,
  461. ) -> int:
  462. """
  463. Get the index of the token in the encoded output comprising a character in the original string for a sequence
  464. of the batch.
  465. Can be called as:
  466. - `self.char_to_token(char_index)` if batch size is 1
  467. - `self.char_to_token(batch_index, char_index)` if batch size is greater or equal to 1
  468. This method is particularly suited when the input sequences are provided as pre-tokenized sequences (i.e. words
  469. are defined by the user). In this case it allows to easily associate encoded tokens with provided tokenized
  470. words.
  471. Args:
  472. batch_or_char_index (`int`):
  473. Index of the sequence in the batch. If the batch only comprise one sequence, this can be the index of
  474. the word in the sequence
  475. char_index (`int`, *optional*):
  476. If a batch index is provided in *batch_or_token_index*, this can be the index of the word in the
  477. sequence.
  478. sequence_index (`int`, *optional*, defaults to 0):
  479. If pair of sequences are encoded in the batch this can be used to specify which sequence in the pair (0
  480. or 1) the provided character index belongs to.
  481. Returns:
  482. `int`: Index of the token.
  483. """
  484. if not self._encodings:
  485. raise ValueError(
  486. "char_to_token() is not available when using Python based tokenizers"
  487. )
  488. if char_index is not None:
  489. batch_index = batch_or_char_index
  490. else:
  491. batch_index = 0
  492. char_index = batch_or_char_index
  493. return self._encodings[batch_index].char_to_token(char_index, sequence_index)
  494. def word_to_chars(
  495. self,
  496. batch_or_word_index: int,
  497. word_index: Optional[int] = None,
  498. sequence_index: int = 0,
  499. ) -> CharSpan:
  500. """
  501. Get the character span in the original string corresponding to given word in a sequence of the batch.
  502. Character spans are returned as a CharSpan NamedTuple with:
  503. - start: index of the first character in the original string
  504. - end: index of the character following the last character in the original string
  505. Can be called as:
  506. - `self.word_to_chars(word_index)` if batch size is 1
  507. - `self.word_to_chars(batch_index, word_index)` if batch size is greater or equal to 1
  508. Args:
  509. batch_or_word_index (`int`):
  510. Index of the sequence in the batch. If the batch only comprise one sequence, this can be the index of
  511. the word in the sequence
  512. word_index (`int`, *optional*):
  513. If a batch index is provided in *batch_or_token_index*, this can be the index of the word in the
  514. sequence.
  515. sequence_index (`int`, *optional*, defaults to 0):
  516. If pair of sequences are encoded in the batch this can be used to specify which sequence in the pair (0
  517. or 1) the provided word index belongs to.
  518. Returns:
  519. `CharSpan` or `List[CharSpan]`: Span(s) of the associated character or characters in the string. CharSpan
  520. are NamedTuple with:
  521. - start: index of the first character associated to the token in the original string
  522. - end: index of the character following the last character associated to the token in the original
  523. string
  524. """
  525. if not self._encodings:
  526. raise ValueError(
  527. "word_to_chars() is not available when using Python based tokenizers"
  528. )
  529. if word_index is not None:
  530. batch_index = batch_or_word_index
  531. else:
  532. batch_index = 0
  533. word_index = batch_or_word_index
  534. return CharSpan(
  535. *(self._encodings[batch_index].word_to_chars(word_index, sequence_index))
  536. )
  537. def char_to_word(
  538. self,
  539. batch_or_char_index: int,
  540. char_index: Optional[int] = None,
  541. sequence_index: int = 0,
  542. ) -> int:
  543. """
  544. Get the word in the original string corresponding to a character in the original string of a sequence of the
  545. batch.
  546. Can be called as:
  547. - `self.char_to_word(char_index)` if batch size is 1
  548. - `self.char_to_word(batch_index, char_index)` if batch size is greater than 1
  549. This method is particularly suited when the input sequences are provided as pre-tokenized sequences (i.e. words
  550. are defined by the user). In this case it allows to easily associate encoded tokens with provided tokenized
  551. words.
  552. Args:
  553. batch_or_char_index (`int`):
  554. Index of the sequence in the batch. If the batch only comprise one sequence, this can be the index of
  555. the character in the original string.
  556. char_index (`int`, *optional*):
  557. If a batch index is provided in *batch_or_token_index*, this can be the index of the character in the
  558. original string.
  559. sequence_index (`int`, *optional*, defaults to 0):
  560. If pair of sequences are encoded in the batch this can be used to specify which sequence in the pair (0
  561. or 1) the provided character index belongs to.
  562. Returns:
  563. `int` or `List[int]`: Index or indices of the associated encoded token(s).
  564. """
  565. if not self._encodings:
  566. raise ValueError(
  567. "char_to_word() is not available when using Python based tokenizers"
  568. )
  569. if char_index is not None:
  570. batch_index = batch_or_char_index
  571. else:
  572. batch_index = 0
  573. char_index = batch_or_char_index
  574. return self._encodings[batch_index].char_to_word(char_index, sequence_index)
  575. def convert_to_tensors(
  576. self,
  577. tensor_type: Optional[Union[str, TensorType]] = None,
  578. prepend_batch_axis: bool = False,
  579. ):
  580. """
  581. Convert the inner content to tensors.
  582. Args:
  583. tensor_type (`str` or [`TensorType`], *optional*):
  584. The type of tensors to use. If `str`, should be one of the values of the enum [`TensorType`]. If
  585. `None`, no modification is done.
  586. prepend_batch_axis (`int`, *optional*, defaults to `False`):
  587. Whether or not to add the batch dimension during the conversion.
  588. """
  589. if tensor_type is None:
  590. return self
  591. # Convert to TensorType
  592. if not isinstance(tensor_type, TensorType):
  593. tensor_type = TensorType(tensor_type)
  594. # Get a function reference for the correct framework
  595. if tensor_type == TensorType.PADDLE:
  596. as_tensor = paddle.to_tensor
  597. is_tensor = paddle.is_tensor
  598. else:
  599. as_tensor = np.asarray
  600. is_tensor = _is_numpy
  601. # Do the tensor conversion in batch
  602. for key, value in self.items():
  603. try:
  604. if prepend_batch_axis:
  605. value = [value]
  606. if not is_tensor(value):
  607. tensor = as_tensor(value)
  608. self[key] = tensor
  609. except: # noqa E722
  610. if key == "overflowing_tokens":
  611. raise ValueError(
  612. "Unable to create tensor returning overflowing tokens of different lengths. "
  613. "Please see if a fast version of this tokenizer is available to have this feature available."
  614. )
  615. raise ValueError(
  616. "Unable to create tensor, you should probably activate truncation and/or padding "
  617. "with 'padding=True' 'truncation=True' to have batched tensors with the same length."
  618. )
  619. return self
  620. class SpecialTokensMixin:
  621. """
  622. A mixin derived by [`PretrainedTokenizer`] to handle specific behaviors related to
  623. special tokens. In particular, this class hold the attributes which can be used to directly access these special
  624. tokens in a model-independent manner and allow to set and update the special tokens.
  625. Args:
  626. bos_token (`str` or `AddedToken`, *optional*):
  627. A special token representing the beginning of a sentence.
  628. eos_token (`str` or `AddedToken`, *optional*):
  629. A special token representing the end of a sentence.
  630. unk_token (`str` or `AddedToken`, *optional*):
  631. A special token representing an out-of-vocabulary token.
  632. sep_token (`str` or `AddedToken`, *optional*):
  633. A special token separating two different sentences in the same input (used by BERT for instance).
  634. pad_token (`str` or `AddedToken`, *optional*):
  635. A special token used to make arrays of tokens the same size for batching purpose. Will then be ignored by
  636. attention mechanisms or loss computation.
  637. cls_token (`str` or `AddedToken`, *optional*):
  638. A special token representing the class of the input (used by BERT for instance).
  639. mask_token (`str` or `AddedToken`, *optional*):
  640. A special token representing a masked token (used by masked-language modeling pretraining objectives, like
  641. BERT).
  642. additional_special_tokens (tuple or list of `str` or `AddedToken`, *optional*):
  643. A tuple or a list of additional special tokens.
  644. """
  645. SPECIAL_TOKENS_ATTRIBUTES = [
  646. "bos_token",
  647. "eos_token",
  648. "unk_token",
  649. "sep_token",
  650. "pad_token",
  651. "cls_token",
  652. "mask_token",
  653. "additional_special_tokens",
  654. ]
  655. def __init__(self, verbose=True, **kwargs):
  656. # note(guosheng): Since `__init__` might be called multiple times which
  657. # is hooked before `PretrainedTokenizer` init, we do not set to None as
  658. # HF to avoid unintentional overriding.
  659. self._bos_token = getattr(self, "_bos_token", None)
  660. self._eos_token = getattr(self, "_eos_token", None)
  661. self._unk_token = getattr(self, "_unk_token", None)
  662. self._sep_token = getattr(self, "_sep_token", None)
  663. self._pad_token = getattr(self, "_pad_token", None)
  664. self._cls_token = getattr(self, "_cls_token", None)
  665. self._mask_token = getattr(self, "_mask_token", None)
  666. self._pad_token_type_id = getattr(self, "_pad_token_type_id", 0)
  667. self._additional_special_tokens = getattr(
  668. self, "_additional_special_tokens", []
  669. )
  670. self.verbose = verbose
  671. # We directly set the hidden value to allow initialization with special tokens
  672. # which are not yet in the vocabulary. Necessary for serialization/de-serialization
  673. # TODO clean this up at some point (probably by switching to fast tokenizers)
  674. for key, value in kwargs.items():
  675. if value is None:
  676. continue
  677. if key in self.SPECIAL_TOKENS_ATTRIBUTES:
  678. if key == "additional_special_tokens":
  679. assert isinstance(
  680. value, (list, tuple)
  681. ), f"Value {value} is not a list or tuple"
  682. assert all(
  683. isinstance(t, (str, AddedToken)) for t in value
  684. ), "One of the tokens is not a string or an AddedToken"
  685. setattr(self, key, value)
  686. elif isinstance(value, (str, AddedToken)):
  687. setattr(self, key, value)
  688. else:
  689. raise TypeError(
  690. f"special token {key} has to be either str or AddedToken but got: {type(value)}"
  691. )
  692. def sanitize_special_tokens(self) -> int:
  693. """
  694. Make sure that all the special tokens attributes of the tokenizer (`tokenizer.mask_token`,
  695. `tokenizer.cls_token`, etc.) are in the vocabulary.
  696. Add the missing ones to the vocabulary if needed.
  697. Return:
  698. `int`: The number of tokens added in the vocabulary during the operation.
  699. """
  700. return self.add_tokens(self.all_special_tokens_extended, special_tokens=True)
  701. def add_special_tokens(
  702. self, special_tokens_dict: Dict[str, Union[str, AddedToken]]
  703. ) -> int:
  704. """
  705. Add a dictionary of special tokens (eos, pad, cls, etc.) to the encoder and link them to class attributes. If
  706. special tokens are NOT in the vocabulary, they are added to it (indexed starting from the last index of the
  707. current vocabulary).
  708. Note,None When adding new tokens to the vocabulary, you should make sure to also resize the token embedding
  709. matrix of the model so that its embedding matrix matches the tokenizer.
  710. In order to do that, please use the [`~PreTrainedModel.resize_token_embeddings`] method.
  711. Using `add_special_tokens` will ensure your special tokens can be used in several ways:
  712. - Special tokens are carefully handled by the tokenizer (they are never split).
  713. - You can easily refer to special tokens using tokenizer class attributes like `tokenizer.cls_token`. This
  714. makes it easy to develop model-agnostic training and fine-tuning scripts.
  715. When possible, special tokens are already registered for provided pretrained models (for instance
  716. [`BertTokenizer`] `cls_token` is already registered to be :obj*'[CLS]'* and XLM's one is also registered to be
  717. `'</s>'`).
  718. Args:
  719. special_tokens_dict (dictionary *str* to *str* or `AddedToken`):
  720. Keys should be in the list of predefined special attributes: [`bos_token`, `eos_token`, `unk_token`,
  721. `sep_token`, `pad_token`, `cls_token`, `mask_token`, `additional_special_tokens`].
  722. Tokens are only added if they are not already in the vocabulary (tested by checking if the tokenizer
  723. assign the index of the `unk_token` to them).
  724. Returns:
  725. `int`: Number of tokens added to the vocabulary.
  726. Examples:
  727. ```python
  728. # Let's see how to add a new classification token to GPT-2
  729. tokenizer = GPT2Tokenizer.from_pretrained("gpt2")
  730. model = GPT2Model.from_pretrained("gpt2")
  731. special_tokens_dict = {"cls_token": "<CLS>"}
  732. num_added_toks = tokenizer.add_special_tokens(special_tokens_dict)
  733. print("We have added", num_added_toks, "tokens")
  734. # Notice: resize_token_embeddings expect to receive the full size of the new vocabulary, i.e., the length of the tokenizer.
  735. model.resize_token_embeddings(len(tokenizer))
  736. assert tokenizer.cls_token == "<CLS>"
  737. ```"""
  738. if not special_tokens_dict:
  739. return 0
  740. added_tokens = 0
  741. for key, value in special_tokens_dict.items():
  742. assert (
  743. key in self.SPECIAL_TOKENS_ATTRIBUTES
  744. ), f"Key {key} is not a special token"
  745. if self.verbose:
  746. logging.info(f"Assigning {value} to the {key} key of the tokenizer")
  747. setattr(self, key, value)
  748. if key == "additional_special_tokens":
  749. assert isinstance(value, (list, tuple)) and all(
  750. isinstance(t, (str, AddedToken)) for t in value
  751. ), f"Tokens {value} for key {key} should all be str or AddedToken instances"
  752. added_tokens += self.add_tokens(value, special_tokens=True)
  753. else:
  754. assert isinstance(
  755. value, (str, AddedToken)
  756. ), f"Token {value} for key {key} should be a str or an AddedToken instance"
  757. added_tokens += self.add_tokens([value], special_tokens=True)
  758. return added_tokens
  759. def add_tokens(
  760. self,
  761. new_tokens: Union[str, AddedToken, List[Union[str, AddedToken]]],
  762. special_tokens: bool = False,
  763. ) -> int:
  764. """
  765. Add a list of new tokens to the tokenizer class. If the new tokens are not in the vocabulary, they are added to
  766. it with indices starting from length of the current vocabulary.
  767. Note,None When adding new tokens to the vocabulary, you should make sure to also resize the token embedding
  768. matrix of the model so that its embedding matrix matches the tokenizer.
  769. In order to do that, please use the [`~PreTrainedModel.resize_token_embeddings`] method.
  770. Args:
  771. new_tokens (`str`, `AddedToken` or a list of *str* or `AddedToken`):
  772. Tokens are only added if they are not already in the vocabulary. `AddedToken` wraps a string
  773. token to let you personalize its behavior: whether this token should only match against a single word,
  774. whether this token should strip all potential whitespaces on the left side, whether this token should
  775. strip all potential whitespaces on the right side, etc.
  776. special_tokens (`bool`, *optional*, defaults to `False`):
  777. Can be used to specify if the token is a special token. This mostly change the normalization behavior
  778. (special tokens like CLS or [MASK] are usually not lower-cased for instance).
  779. Returns:
  780. `int`: Number of tokens added to the vocabulary.
  781. Examples:
  782. ```python
  783. # Let's see how to increase the vocabulary of Bert model and tokenizer
  784. tokenizer = BertTokenizer.from_pretrained("bert-base-uncased")
  785. model = BertModel.from_pretrained("bert-base-uncased")
  786. num_added_toks = tokenizer.add_tokens(["new_tok1", "my_new-tok2"])
  787. print("We have added", num_added_toks, "tokens")
  788. # Notice: resize_token_embeddings expect to receive the full size of the new vocabulary, i.e., the length of the tokenizer.
  789. model.resize_token_embeddings(len(tokenizer))
  790. ```"""
  791. if not new_tokens:
  792. return 0
  793. if not isinstance(new_tokens, (list, tuple)):
  794. new_tokens = [new_tokens]
  795. return self._add_tokens(new_tokens, special_tokens=special_tokens)
  796. def _add_tokens(
  797. self,
  798. new_tokens: Union[List[str], List[AddedToken]],
  799. special_tokens: bool = False,
  800. ) -> int:
  801. raise NotImplementedError
  802. @property
  803. def bos_token(self) -> str:
  804. """
  805. `str`: Beginning of sentence token. Log an error if used while not having been set.
  806. """
  807. if self._bos_token is None and self.verbose:
  808. logging.error("Using bos_token, but it is not set yet.")
  809. return None
  810. return str(self._bos_token)
  811. @property
  812. def eos_token(self) -> str:
  813. """
  814. `str`: End of sentence token. Log an error if used while not having been set.
  815. """
  816. if self._eos_token is None and self.verbose:
  817. logging.error("Using eos_token, but it is not set yet.")
  818. return None
  819. return str(self._eos_token)
  820. @property
  821. def unk_token(self) -> str:
  822. """
  823. `str`: Unknown token. Log an error if used while not having been set.
  824. """
  825. if self._unk_token is None and self.verbose:
  826. logging.error("Using unk_token, but it is not set yet.")
  827. return None
  828. return str(self._unk_token)
  829. @property
  830. def sep_token(self) -> str:
  831. """
  832. `str`: Separation token, to separate context and query in an input sequence. Log an error if used while not
  833. having been set.
  834. """
  835. if self._sep_token is None and self.verbose:
  836. logging.error("Using sep_token, but it is not set yet.")
  837. return None
  838. return str(self._sep_token)
  839. @property
  840. def pad_token(self) -> str:
  841. """
  842. `str`: Padding token. Log an error if used while not having been set.
  843. """
  844. if self._pad_token is None and self.verbose:
  845. logging.error("Using pad_token, but it is not set yet.")
  846. return None
  847. return str(self._pad_token)
  848. @property
  849. def cls_token(self) -> str:
  850. """
  851. `str`: Classification token, to extract a summary of an input sequence leveraging self-attention along the full
  852. depth of the model. Log an error if used while not having been set.
  853. """
  854. if self._cls_token is None and self.verbose:
  855. logging.error("Using cls_token, but it is not set yet.")
  856. return None
  857. return str(self._cls_token)
  858. @property
  859. def mask_token(self) -> str:
  860. """
  861. `str`: Mask token, to use when training a model with masked-language modeling. Log an error if used while not
  862. having been set.
  863. """
  864. if self._mask_token is None and self.verbose:
  865. logging.error("Using mask_token, but it is not set yet.")
  866. return None
  867. return str(self._mask_token)
  868. @property
  869. def additional_special_tokens(self) -> List[str]:
  870. """
  871. `List[str]`: All the additional special tokens you may want to use. Log an error if used while not having been
  872. set.
  873. """
  874. if self._additional_special_tokens is None and self.verbose:
  875. logging.error("Using additional_special_tokens, but it is not set yet.")
  876. return None
  877. return [str(tok) for tok in self._additional_special_tokens]
  878. @bos_token.setter
  879. def bos_token(self, value):
  880. self._bos_token = value
  881. @eos_token.setter
  882. def eos_token(self, value):
  883. self._eos_token = value
  884. @unk_token.setter
  885. def unk_token(self, value):
  886. self._unk_token = value
  887. @sep_token.setter
  888. def sep_token(self, value):
  889. self._sep_token = value
  890. @pad_token.setter
  891. def pad_token(self, value):
  892. self._pad_token = value
  893. @cls_token.setter
  894. def cls_token(self, value):
  895. self._cls_token = value
  896. @mask_token.setter
  897. def mask_token(self, value):
  898. self._mask_token = value
  899. @additional_special_tokens.setter
  900. def additional_special_tokens(self, value):
  901. self._additional_special_tokens = value
  902. @property
  903. def bos_token_id(self) -> Optional[int]:
  904. """
  905. `Optional[int]`: Id of the beginning of sentence token in the vocabulary. Returns `None` if the token has not
  906. been set.
  907. """
  908. if self._bos_token is None:
  909. return None
  910. return self.convert_tokens_to_ids(self.bos_token)
  911. @property
  912. def eos_token_id(self) -> Optional[int]:
  913. """
  914. `Optional[int]`: Id of the end of sentence token in the vocabulary. Returns `None` if the token has not been
  915. set.
  916. """
  917. if self._eos_token is None:
  918. return None
  919. return self.convert_tokens_to_ids(self.eos_token)
  920. @property
  921. def unk_token_id(self) -> Optional[int]:
  922. """
  923. `Optional[int]`: Id of the unknown token in the vocabulary. Returns `None` if the token has not been set.
  924. """
  925. if self._unk_token is None:
  926. return None
  927. return self.convert_tokens_to_ids(self.unk_token)
  928. @property
  929. def sep_token_id(self) -> Optional[int]:
  930. """
  931. `Optional[int]`: Id of the separation token in the vocabulary, to separate context and query in an input
  932. sequence. Returns `None` if the token has not been set.
  933. """
  934. if self._sep_token is None:
  935. return None
  936. return self.convert_tokens_to_ids(self.sep_token)
  937. @property
  938. def pad_token_id(self) -> Optional[int]:
  939. """
  940. `Optional[int]`: Id of the padding token in the vocabulary. Returns `None` if the token has not been set.
  941. """
  942. if self._pad_token is None:
  943. return None
  944. return self.convert_tokens_to_ids(self.pad_token)
  945. @property
  946. def pad_token_type_id(self) -> int:
  947. """
  948. `int`: Id of the padding token type in the vocabulary.
  949. """
  950. return self._pad_token_type_id
  951. @property
  952. def cls_token_id(self) -> Optional[int]:
  953. """
  954. `Optional[int]`: Id of the classification token in the vocabulary, to extract a summary of an input sequence
  955. leveraging self-attention along the full depth of the model.
  956. Returns `None` if the token has not been set.
  957. """
  958. if self._cls_token is None:
  959. return None
  960. return self.convert_tokens_to_ids(self.cls_token)
  961. @property
  962. def mask_token_id(self) -> Optional[int]:
  963. """
  964. `Optional[int]`: Id of the mask token in the vocabulary, used when training a model with masked-language
  965. modeling. Returns `None` if the token has not been set.
  966. """
  967. if self._mask_token is None:
  968. return None
  969. return self.convert_tokens_to_ids(self.mask_token)
  970. @property
  971. def additional_special_tokens_ids(self) -> List[int]:
  972. """
  973. `List[int]`: Ids of all the additional special tokens in the vocabulary. Log an error if used while not having
  974. been set.
  975. """
  976. return self.convert_tokens_to_ids(self.additional_special_tokens)
  977. @bos_token_id.setter
  978. def bos_token_id(self, value):
  979. self._bos_token = (
  980. self.convert_ids_to_tokens(value) if value is not None else None
  981. )
  982. @eos_token_id.setter
  983. def eos_token_id(self, value):
  984. self._eos_token = (
  985. self.convert_ids_to_tokens(value) if value is not None else None
  986. )
  987. @unk_token_id.setter
  988. def unk_token_id(self, value):
  989. self._unk_token = (
  990. self.convert_ids_to_tokens(value) if value is not None else None
  991. )
  992. @sep_token_id.setter
  993. def sep_token_id(self, value):
  994. self._sep_token = (
  995. self.convert_ids_to_tokens(value) if value is not None else None
  996. )
  997. @pad_token_id.setter
  998. def pad_token_id(self, value):
  999. self._pad_token = (
  1000. self.convert_ids_to_tokens(value) if value is not None else None
  1001. )
  1002. @cls_token_id.setter
  1003. def cls_token_id(self, value):
  1004. self._cls_token = (
  1005. self.convert_ids_to_tokens(value) if value is not None else None
  1006. )
  1007. @mask_token_id.setter
  1008. def mask_token_id(self, value):
  1009. self._mask_token = (
  1010. self.convert_ids_to_tokens(value) if value is not None else None
  1011. )
  1012. @additional_special_tokens_ids.setter
  1013. def additional_special_tokens_ids(self, values):
  1014. self._additional_special_tokens = [
  1015. self.convert_ids_to_tokens(value) for value in values
  1016. ]
  1017. @property
  1018. def special_tokens_map(self) -> Dict[str, Union[str, List[str]]]:
  1019. """
  1020. `Dict[str, Union[str, List[str]]]`: A dictionary mapping special token class attributes (`cls_token`,
  1021. `unk_token`, etc.) to their values (`'<unk>'`, `'<cls>'`, etc.).
  1022. Convert potential tokens of `AddedToken` type to string.
  1023. """
  1024. set_attr = {}
  1025. for attr in self.SPECIAL_TOKENS_ATTRIBUTES:
  1026. attr_value = getattr(self, "_" + attr)
  1027. if attr_value:
  1028. set_attr[attr] = (
  1029. type(attr_value)(
  1030. str(attr_value_sub) for attr_value_sub in attr_value
  1031. )
  1032. if isinstance(attr_value, (list, tuple))
  1033. else str(attr_value)
  1034. )
  1035. return set_attr
  1036. @property
  1037. def special_tokens_map_extended(
  1038. self,
  1039. ) -> Dict[str, Union[str, AddedToken, List[Union[str, AddedToken]]]]:
  1040. """
  1041. `Dict[str, Union[str, AddedToken, List[Union[str, AddedToken]]]]`: A dictionary mapping
  1042. special token class attributes (`cls_token`, `unk_token`, etc.) to their values (`'<unk>'`, `'<cls>'`, etc.).
  1043. Don't convert tokens of `AddedToken` type to string so they can be used to control more finely how
  1044. special tokens are tokenized.
  1045. """
  1046. set_attr = {}
  1047. for attr in self.SPECIAL_TOKENS_ATTRIBUTES:
  1048. attr_value = getattr(self, "_" + attr, None)
  1049. if attr_value:
  1050. set_attr[attr] = attr_value
  1051. return set_attr
  1052. @property
  1053. def all_special_tokens(self) -> List[str]:
  1054. """
  1055. `List[str]`: All the special tokens (`'<unk>'`, `'<cls>'`, etc.) mapped to class attributes.
  1056. Convert tokens of `AddedToken` type to string.
  1057. """
  1058. all_toks = [str(s) for s in self.all_special_tokens_extended]
  1059. return all_toks
  1060. @property
  1061. def all_special_tokens_extended(self) -> List[Union[str, AddedToken]]:
  1062. """
  1063. `List[Union[str, AddedToken]]`: All the special tokens (`'<unk>'`, `'<cls>'`, etc.) mapped to class
  1064. attributes.
  1065. Don't convert tokens of `AddedToken` type to string so they can be used to control more finely how
  1066. special tokens are tokenized.
  1067. """
  1068. all_toks = []
  1069. set_attr = self.special_tokens_map_extended
  1070. for attr_value in set_attr.values():
  1071. all_toks = all_toks + (
  1072. list(attr_value)
  1073. if isinstance(attr_value, (list, tuple))
  1074. else [attr_value]
  1075. )
  1076. all_toks = list(OrderedDict.fromkeys(all_toks))
  1077. return all_toks
  1078. @property
  1079. def all_special_ids(self) -> List[int]:
  1080. """
  1081. `List[int]`: List the ids of the special tokens(`'<unk>'`, `'<cls>'`, etc.) mapped to class attributes.
  1082. """
  1083. all_toks = self.all_special_tokens
  1084. all_ids = self.convert_tokens_to_ids(all_toks)
  1085. return all_ids
  1086. class PretrainedTokenizerBase(SpecialTokensMixin):
  1087. """
  1088. Base class for [`PretrainedTokenizer`].
  1089. Class attributes (overridden by derived classes)
  1090. - **resource_files_names** (`Dict[str, str]`) -- A dictionary with, as keys, the `__init__` keyword name of each
  1091. vocabulary file required by the model, and as associated values, the filename for saving the associated file
  1092. (string).
  1093. - **pretrained_resource_files_map** (`Dict[str, Dict[str, str]]`) -- A dictionary of dictionaries, with the
  1094. high-level keys being the `__init__` keyword name of each vocabulary file required by the model, the
  1095. low-level being the `short-cut-names` of the pretrained models with, as associated values, the `url` to the
  1096. associated pretrained vocabulary file.
  1097. - **max_model_input_sizes** (`Dict[str, Optional[int]]`) -- A dictionary with, as keys, the `short-cut-names`
  1098. of the pretrained models, and as associated values, the maximum length of the sequence inputs of this model,
  1099. or `None` if the model has no maximum input size.
  1100. - **pretrained_init_configuration** (`Dict[str, Dict[str, Any]]`) -- A dictionary with, as keys, the
  1101. `short-cut-names` of the pretrained models, and as associated values, a dictionary of specific arguments to
  1102. pass to the `__init__` method of the tokenizer class for this pretrained model when loading the tokenizer
  1103. with the [`~tokenizer_utils_base.PretrainedTokenizerBase.from_pretrained`] method.
  1104. - **model_input_names** (`List[str]`) -- A list of inputs expected in the forward pass of the model.
  1105. - **padding_side** (`str`) -- The default value for the side on which the model should have padding applied.
  1106. Should be `'right'` or `'left'`.
  1107. - **truncation_side** (`str`) -- The default value for the side on which the model should have truncation
  1108. applied. Should be `'right'` or `'left'`.
  1109. Args:
  1110. model_max_length (`int`, *optional*):
  1111. The maximum length (in number of tokens) for the inputs to the transformer model. When the tokenizer is
  1112. loaded with [`~tokenizer_utils_base.PretrainedTokenizerBase.from_pretrained`], this will be set to the
  1113. value stored for the associated model in `max_model_input_sizes` (see above). If no value is provided, will
  1114. default to VERY_LARGE_INTEGER (`int(1e30)`).
  1115. padding_side (`str`, *optional*):
  1116. The side on which the model should have padding applied. Should be selected between ['right', 'left'].
  1117. Default value is picked from the class attribute of the same name.
  1118. truncation_side (`str`, *optional*):
  1119. The side on which the model should have truncation applied. Should be selected between ['right', 'left'].
  1120. Default value is picked from the class attribute of the same name.
  1121. model_input_names (`List[string]`, *optional*):
  1122. The list of inputs accepted by the forward pass of the model (like `"token_type_ids"` or
  1123. `"attention_mask"`). Default value is picked from the class attribute of the same name.
  1124. bos_token (`str` or `AddedToken`, *optional*):
  1125. A special token representing the beginning of a sentence. Will be associated to `self.bos_token` and
  1126. `self.bos_token_id`.
  1127. eos_token (`str` or `AddedToken`, *optional*):
  1128. A special token representing the end of a sentence. Will be associated to `self.eos_token` and
  1129. `self.eos_token_id`.
  1130. unk_token (`str` or `AddedToken`, *optional*):
  1131. A special token representing an out-of-vocabulary token. Will be associated to `self.unk_token` and
  1132. `self.unk_token_id`.
  1133. sep_token (`str` or `AddedToken`, *optional*):
  1134. A special token separating two different sentences in the same input (used by BERT for instance). Will be
  1135. associated to `self.sep_token` and `self.sep_token_id`.
  1136. pad_token (`str` or `AddedToken`, *optional*):
  1137. A special token used to make arrays of tokens the same size for batching purpose. Will then be ignored by
  1138. attention mechanisms or loss computation. Will be associated to `self.pad_token` and `self.pad_token_id`.
  1139. cls_token (`str` or `AddedToken`, *optional*):
  1140. A special token representing the class of the input (used by BERT for instance). Will be associated to
  1141. `self.cls_token` and `self.cls_token_id`.
  1142. mask_token (`str` or `AddedToken`, *optional*):
  1143. A special token representing a masked token (used by masked-language modeling pretraining objectives, like
  1144. BERT). Will be associated to `self.mask_token` and `self.mask_token_id`.
  1145. additional_special_tokens (tuple or list of `str` or `AddedToken`, *optional*):
  1146. A tuple or a list of additional special tokens. Add them here to ensure they won't be split by the
  1147. tokenization process. Will be associated to `self.additional_special_tokens` and
  1148. `self.additional_special_tokens_ids`.
  1149. """
  1150. resource_files_names: Dict[str, str] = {}
  1151. pretrained_resource_files_map: Dict[str, Dict[str, str]] = {}
  1152. pretrained_init_configuration: Dict[str, Dict[str, Any]] = {}
  1153. max_model_input_sizes: Dict[str, Optional[int]] = {}
  1154. _auto_class: Optional[str] = None
  1155. tokenizer_config_file = TOKENIZER_CONFIG_NAME
  1156. # first name has to correspond to main model input name
  1157. # to make sure `tokenizer.pad(...)` works correctly
  1158. model_input_names: List[str] = ["input_ids", "token_type_ids"]
  1159. padding_side: str = "right"
  1160. truncation_side: str = "right"
  1161. slow_tokenizer_class = None
  1162. def __init__(self, **kwargs):
  1163. # inputs and kwargs for saving and re-loading (see ``from_pretrained`` and ``save_pretrained``)
  1164. self.init_inputs = ()
  1165. self.init_kwargs = getattr(self, "init_kwargs", None) or copy.deepcopy(kwargs)
  1166. self.name_or_path = kwargs.pop("name_or_path", "")
  1167. self._processor_class = kwargs.pop("processor_class", None)
  1168. # For backward compatibility we fallback to set model_max_length from max_len if provided
  1169. model_max_length = kwargs.pop("model_max_length", kwargs.pop("max_len", None))
  1170. self.model_max_length = (
  1171. model_max_length if model_max_length is not None else VERY_LARGE_INTEGER
  1172. )
  1173. # Padding and truncation side are right by default and overridden in subclasses. If specified in the kwargs, it
  1174. # is changed.
  1175. self.padding_side = kwargs.pop("padding_side", self.padding_side)
  1176. if self.padding_side not in ["right", "left"]:
  1177. raise ValueError(
  1178. f"Padding side should be selected between 'right' and 'left', current value: {self.padding_side}"
  1179. )
  1180. self.truncation_side = kwargs.pop("truncation_side", self.truncation_side)
  1181. if self.truncation_side not in ["right", "left"]:
  1182. raise ValueError(
  1183. f"Padding side should be selected between 'right' and 'left', current value: {self.truncation_side}"
  1184. )
  1185. self.model_input_names = kwargs.pop("model_input_names", self.model_input_names)
  1186. self.deprecation_warnings = (
  1187. {}
  1188. ) # Use to store when we have already noticed a deprecation warning (avoid overlogging).
  1189. super().__init__(**kwargs)
  1190. @property
  1191. def max_len_single_sentence(self) -> int:
  1192. """
  1193. `int`: The maximum length of a sentence that can be fed to the model.
  1194. """
  1195. return self.model_max_length - self.num_special_tokens_to_add(pair=False)
  1196. @property
  1197. def max_len_sentences_pair(self) -> int:
  1198. """
  1199. `int`: The maximum combined length of a pair of sentences that can be fed to the model.
  1200. """
  1201. return self.model_max_length - self.num_special_tokens_to_add(pair=True)
  1202. @max_len_single_sentence.setter
  1203. def max_len_single_sentence(self, value) -> int:
  1204. # For backward compatibility, allow to try to setup 'max_len_single_sentence'.
  1205. if (
  1206. value == self.model_max_length - self.num_special_tokens_to_add(pair=False)
  1207. and self.verbose
  1208. ):
  1209. if not self.deprecation_warnings.get("max_len_single_sentence", False):
  1210. warnings.warn(
  1211. "Setting 'max_len_single_sentence' is now deprecated. "
  1212. "This value is automatically set up."
  1213. )
  1214. self.deprecation_warnings["max_len_single_sentence"] = True
  1215. else:
  1216. raise ValueError(
  1217. "Setting 'max_len_single_sentence' is now deprecated. "
  1218. "This value is automatically set up."
  1219. )
  1220. def _switch_to_input_mode(self):
  1221. """
  1222. Private method to put the tokenizer in input mode (when it has different modes for input/outputs)
  1223. """
  1224. @max_len_sentences_pair.setter
  1225. def max_len_sentences_pair(self, value) -> int:
  1226. # For backward compatibility, allow to try to setup 'max_len_sentences_pair'.
  1227. if (
  1228. value == self.model_max_length - self.num_special_tokens_to_add(pair=True)
  1229. and self.verbose
  1230. ):
  1231. if not self.deprecation_warnings.get("max_len_sentences_pair", False):
  1232. warnings.warn(
  1233. "Setting 'max_len_sentences_pair' is now deprecated. "
  1234. "This value is automatically set up."
  1235. )
  1236. self.deprecation_warnings["max_len_sentences_pair"] = True
  1237. else:
  1238. raise ValueError(
  1239. "Setting 'max_len_sentences_pair' is now deprecated. "
  1240. "This value is automatically set up."
  1241. )
  1242. def _set_processor_class(self, processor_class: str):
  1243. """Sets processor class as an attribute."""
  1244. self._processor_class = processor_class
  1245. def __repr__(self) -> str:
  1246. return (
  1247. f"{'PretrainedTokenizer'}(name_or_path='{self.name_or_path}', "
  1248. f"vocab_size={self.vocab_size}, model_max_len={self.model_max_length}, "
  1249. f"padding_side='{self.padding_side}', truncation_side='{self.truncation_side}', special_tokens={self.special_tokens_map_extended})"
  1250. )
  1251. def get_vocab(self) -> Dict[str, int]:
  1252. """
  1253. Returns the vocabulary as a dictionary of token to index.
  1254. `tokenizer.get_vocab()[token]` is equivalent to `tokenizer.convert_tokens_to_ids(token)` when `token` is in the
  1255. vocab.
  1256. Returns:
  1257. `Dict[str, int]`: The vocabulary.
  1258. """
  1259. raise NotImplementedError()
  1260. @classmethod
  1261. def from_pretrained(cls, pretrained_model_name_or_path, *args, **kwargs):
  1262. """
  1263. Creates an instance of `PretrainedTokenizer`. Related resources are loaded
  1264. by specifying name of a built-in pretrained model, or a community-contributed
  1265. pretrained model, or a local file directory path.
  1266. Args:
  1267. pretrained_model_name_or_path (str): Name of pretrained model or dir path
  1268. to load from. The string can be:
  1269. - Name of built-in pretrained model
  1270. - Name of a community-contributed pretrained model.
  1271. - Local directory path which contains tokenizer related resources
  1272. and tokenizer config file ("tokenizer_config.json").
  1273. from_hf_hub (bool, optional): whether to load from Huggingface Hub
  1274. subfolder (str, optional) An optional value corresponding to a folder inside the repo.
  1275. Only works when loading from Huggingface Hub.
  1276. *args (tuple): position arguments for model `__init__`. If provided,
  1277. use these as position argument values for tokenizer initialization.
  1278. **kwargs (dict): keyword arguments for model `__init__`. If provided,
  1279. use these to update pre-defined keyword argument values for tokenizer
  1280. initialization.
  1281. Returns:
  1282. PretrainedTokenizer: An instance of `PretrainedTokenizer`.
  1283. Example:
  1284. .. code-block::
  1285. from paddlenlp.transformers import BertTokenizer
  1286. # Name of built-in pretrained model
  1287. tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
  1288. # Name of community-contributed pretrained model
  1289. tokenizer = BertTokenizer.from_pretrained('yingyibiao/bert-base-uncased-sst-2-finetuned')
  1290. # Load from local directory path
  1291. tokenizer = BertTokenizer.from_pretrained('./my_bert/')
  1292. """
  1293. pretrained_model_name_or_path = str(pretrained_model_name_or_path)
  1294. cache_dir = kwargs.pop("cache_dir", None)
  1295. from_hf_hub = kwargs.pop("from_hf_hub", False)
  1296. from_aistudio = kwargs.pop("from_aistudio", False)
  1297. subfolder = kwargs.pop("subfolder", "")
  1298. return_tokenizer_file_dir = kwargs.pop("return_tokenizer_file_dir", False)
  1299. if subfolder is None:
  1300. subfolder = ""
  1301. vocab_files = {}
  1302. init_configuration = {}
  1303. additional_files_names = {
  1304. "added_tokens_file": ADDED_TOKENS_FILE,
  1305. "special_tokens_map_file": SPECIAL_TOKENS_MAP_FILE,
  1306. "tokenizer_config_file": TOKENIZER_CONFIG_FILE,
  1307. "chat_template_file": CHAT_TEMPLATE_CONFIG_NAME,
  1308. }
  1309. vocab_files_target = {**cls.resource_files_names, **additional_files_names}
  1310. # From HF Hub or AI Studio
  1311. if from_hf_hub or from_aistudio:
  1312. # Only include the necessary resource files specified by the tokenizer cls
  1313. # Deep copy to avoid modifiying the class attributes
  1314. vocab_files = copy.deepcopy(cls.resource_files_names)
  1315. vocab_files["tokenizer_config_file"] = cls.tokenizer_config_file
  1316. # From built-in pretrained models
  1317. elif pretrained_model_name_or_path in cls.pretrained_init_configuration:
  1318. for file_id, map_list in cls.pretrained_resource_files_map.items():
  1319. vocab_files[file_id] = map_list[pretrained_model_name_or_path]
  1320. init_configuration = copy.deepcopy(
  1321. cls.pretrained_init_configuration[pretrained_model_name_or_path]
  1322. )
  1323. # From local dir path
  1324. elif os.path.isdir(pretrained_model_name_or_path):
  1325. vocab_files_target["tokenizer_config_file"] = cls.tokenizer_config_file
  1326. for file_id, file_name in vocab_files_target.items():
  1327. full_file_name = os.path.join(
  1328. pretrained_model_name_or_path, subfolder, file_name
  1329. )
  1330. if os.path.isfile(full_file_name):
  1331. vocab_files[file_id] = full_file_name
  1332. else:
  1333. # Assuming from community-contributed pretrained models
  1334. for file_id, file_name in vocab_files_target.items():
  1335. vocab_files[file_id] = file_name
  1336. resolved_vocab_files = {}
  1337. for file_id, file_path in vocab_files.items():
  1338. if file_path is None or os.path.isfile(file_path):
  1339. resolved_vocab_files[file_id] = file_path
  1340. continue
  1341. else:
  1342. logging.warnings("need to download tokenizer, but not support yet.")
  1343. # tokenizer download not support yet
  1344. # resolved_vocab_files[file_id] = resolve_file_path(
  1345. # pretrained_model_name_or_path,
  1346. # [file_path],
  1347. # subfolder,
  1348. # cache_dir=cache_dir,
  1349. # from_aistudio=from_aistudio,
  1350. # from_hf_hub=from_hf_hub,
  1351. # )
  1352. for file_id, file_path in resolved_vocab_files.items():
  1353. if resolved_vocab_files[file_id] is not None:
  1354. cache_dir = os.path.dirname(resolved_vocab_files[file_id])
  1355. break
  1356. tokenizer_config_file_dir_list = set()
  1357. for k, v in resolved_vocab_files.items():
  1358. if v is not None and os.path.isfile(v):
  1359. tokenizer_config_file_dir_list.add(os.path.dirname(v))
  1360. tokenizer_config_file_dir_list = list(tokenizer_config_file_dir_list)
  1361. # TODO: check this
  1362. assert (
  1363. len(tokenizer_config_file_dir_list) > 0
  1364. ), "All tokenizer files should be in the same directory."
  1365. # Prepare tokenizer initialization kwargs
  1366. # Did we saved some inputs and kwargs to reload ?
  1367. has_tokenizer_file = (
  1368. resolved_vocab_files.get("tokenizer_file", None) is not None
  1369. )
  1370. tokenizer_config_file = resolved_vocab_files.pop("tokenizer_config_file", None)
  1371. if tokenizer_config_file is not None:
  1372. with io.open(tokenizer_config_file, encoding="utf-8") as f:
  1373. init_kwargs = json.load(f)
  1374. else:
  1375. init_kwargs = init_configuration
  1376. # position args are stored in kwargs, maybe better not include
  1377. init_args = init_kwargs.pop("init_args", ())
  1378. init_kwargs.pop("init_class", None)
  1379. # Update with newly provided args and kwargs
  1380. init_args = init_args if not args else args
  1381. init_kwargs.update(kwargs)
  1382. def convert_added_tokens(obj):
  1383. if (
  1384. isinstance(obj, dict)
  1385. and "__type" in obj
  1386. and obj["__type"] == "AddedToken"
  1387. ):
  1388. obj.pop("__type")
  1389. return AddedToken(**obj)
  1390. elif isinstance(obj, (list, tuple)):
  1391. return list(convert_added_tokens(o) for o in obj)
  1392. elif isinstance(obj, dict):
  1393. return {k: convert_added_tokens(v) for k, v in obj.items()}
  1394. return obj
  1395. init_kwargs = convert_added_tokens(init_kwargs)
  1396. # Set max length if needed
  1397. if pretrained_model_name_or_path in cls.max_model_input_sizes:
  1398. # if we're using a pretrained model, ensure the tokenizer
  1399. # wont index sequences longer than the number of positional embeddings
  1400. model_max_length = cls.max_model_input_sizes[pretrained_model_name_or_path]
  1401. if model_max_length is not None and isinstance(
  1402. model_max_length, (int, float)
  1403. ):
  1404. init_kwargs["model_max_length"] = min(
  1405. init_kwargs.get("model_max_length", int(1e30)), model_max_length
  1406. )
  1407. added_tokens_file = resolved_vocab_files.pop("added_tokens_file", None)
  1408. # Merge resolved_vocab_files arguments in init_kwargs if not including.
  1409. # Maybe need more ways to load resources.
  1410. for args_name, file_path in resolved_vocab_files.items():
  1411. # when `pretrained_model_name_or_path` is a pretrained model name,
  1412. # use pretrained_init_configuration as `init_kwargs` to init which
  1413. # does not include the vocab file in it, thus add vocab file into
  1414. # args.
  1415. if args_name not in init_kwargs:
  1416. init_kwargs[args_name] = file_path
  1417. # when `pretrained_model_name_or_path` is a pretrained model dir,
  1418. # use tokenizer_config_file.json as `init_kwargs` to init which
  1419. # does include a vocab file path in it. However, if the vocab file
  1420. # path included in json does not exist, such as was deleted, to make
  1421. # it still work, use the vocab file under this dir.
  1422. elif not os.path.isfile(init_kwargs[args_name] or "") and os.path.isfile(
  1423. file_path
  1424. ):
  1425. init_kwargs[args_name] = file_path
  1426. # TODO(zhoushunjie): It's not supportted to load tokenizer.json of hf so far.
  1427. if from_hf_hub and "tokenizer_file" in init_kwargs:
  1428. init_kwargs.pop("tokenizer_file")
  1429. # TODO(guosheng): avoid reduplication of position args and key word args
  1430. tokenizer = cls(*init_args, **init_kwargs)
  1431. chat_template = init_kwargs.pop("chat_template", None)
  1432. if chat_template is not None:
  1433. tokenizer.init_chat_template(chat_template)
  1434. special_tokens_map_file = resolved_vocab_files.pop(
  1435. "special_tokens_map_file", None
  1436. )
  1437. if special_tokens_map_file is not None:
  1438. with open(
  1439. special_tokens_map_file, encoding="utf-8"
  1440. ) as special_tokens_map_handle:
  1441. special_tokens_map = json.load(special_tokens_map_handle)
  1442. for key, value in special_tokens_map.items():
  1443. if key in kwargs and kwargs[key]:
  1444. # This value has already been redefined by the kwargs
  1445. # We keep this new value and ignore the one stored in the special_tokens_map_file
  1446. continue
  1447. if isinstance(value, dict):
  1448. value = AddedToken(**value)
  1449. elif isinstance(value, list):
  1450. value = [
  1451. AddedToken(**token) if isinstance(token, dict) else token
  1452. for token in value
  1453. ]
  1454. setattr(tokenizer, key, value)
  1455. # Add supplementary tokens.
  1456. special_tokens = tokenizer.all_special_tokens
  1457. if added_tokens_file is not None:
  1458. with open(added_tokens_file, encoding="utf-8") as added_tokens_handle:
  1459. added_tok_encoder = json.load(added_tokens_handle)
  1460. # Sort added tokens by index
  1461. added_tok_encoder_sorted = list(
  1462. sorted(added_tok_encoder.items(), key=lambda x: x[1])
  1463. )
  1464. for token, index in added_tok_encoder_sorted:
  1465. if (
  1466. has_tokenizer_file
  1467. and index != len(tokenizer)
  1468. and tokenizer.convert_tokens_to_ids(token) != index
  1469. ):
  1470. # index is the current length of the tokenizer (not in vocabulary)
  1471. raise ValueError(
  1472. f"Wrong index found for {token}: should be {tokenizer.convert_tokens_to_ids(token)} but found "
  1473. f"{index}."
  1474. )
  1475. elif not has_tokenizer_file and index != len(tokenizer):
  1476. # Tokenizer slow: added token cannot already be in the vocabulary so its index needs to be the
  1477. # current length of the tokenizer.
  1478. raise ValueError(
  1479. f"Non-consecutive added token '{token}' found. "
  1480. f"Should have index {len(tokenizer)} but has index {index} in saved vocabulary."
  1481. )
  1482. tokenizer.add_tokens(
  1483. token, special_tokens=bool(token in special_tokens)
  1484. )
  1485. # Check all our special tokens are registered as "no split" token (we don't cut them) and are in the vocab
  1486. added_tokens = tokenizer.sanitize_special_tokens()
  1487. if added_tokens:
  1488. logging.info(
  1489. "Special tokens have been added in the vocabulary, make sure the associated word embeddings are fine-tuned or trained."
  1490. )
  1491. # save all of related things into default root dir
  1492. if pretrained_model_name_or_path in cls.pretrained_init_configuration:
  1493. # tokenizer.save_pretrained(os.path.join(cache_dir, pretrained_model_name_or_path, subfolder))
  1494. tokenizer.save_pretrained(cache_dir)
  1495. if return_tokenizer_file_dir:
  1496. return tokenizer, list(tokenizer_config_file_dir_list)[0]
  1497. return tokenizer
  1498. def save_pretrained(
  1499. self, save_directory, filename_prefix: Optional[str] = None, **kwargs
  1500. ):
  1501. """
  1502. Save tokenizer configuration and related resources to files under
  1503. `save_directory`. The tokenizer configuration would be saved into
  1504. `tokenizer_config_file` indicating file (thus `tokenizer_config.json`),
  1505. and resources would be saved into `resource_files_names` indicating files
  1506. by using `self.save_resources(save_directory)`.
  1507. The `save_directory` can be used in `from_pretrained` as argument value
  1508. of `pretrained_model_name_or_path` to re-load the tokenizer.
  1509. Args:
  1510. save_directory (str): Directory to save files into.
  1511. filename_prefix: (str, optional):
  1512. A prefix to add to the names of the files saved by the tokenizer.
  1513. Example:
  1514. .. code-block::
  1515. from paddlenlp.transformers import BertTokenizer
  1516. tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
  1517. tokenizer.save_pretrained('trained_model')
  1518. # reload from save_directory
  1519. tokenizer = BertTokenizer.from_pretrained('trained_model')
  1520. """
  1521. assert not os.path.isfile(
  1522. save_directory
  1523. ), "Saving directory ({}) should be a directory, not a file".format(
  1524. save_directory
  1525. )
  1526. os.makedirs(save_directory, exist_ok=True)
  1527. special_tokens_map_file = os.path.join(
  1528. save_directory,
  1529. (filename_prefix + "-" if filename_prefix else "")
  1530. + SPECIAL_TOKENS_MAP_FILE,
  1531. )
  1532. tokenizer_config_file = os.path.join(
  1533. save_directory,
  1534. (filename_prefix + "-" if filename_prefix else "")
  1535. + self.tokenizer_config_file,
  1536. )
  1537. tokenizer_config = copy.deepcopy(self.init_kwargs)
  1538. if len(self.init_inputs) > 0:
  1539. tokenizer_config["init_inputs"] = copy.deepcopy(self.init_inputs)
  1540. for file_id in self.resource_files_names.keys():
  1541. tokenizer_config.pop(file_id, None)
  1542. # Sanitize AddedTokens
  1543. def convert_added_tokens(obj: Union[AddedToken, Any], add_type_field=True):
  1544. if isinstance(obj, AddedToken):
  1545. out = obj.__getstate__()
  1546. if add_type_field:
  1547. out["__type"] = "AddedToken"
  1548. return out
  1549. elif isinstance(obj, (list, tuple)):
  1550. return list(
  1551. convert_added_tokens(o, add_type_field=add_type_field) for o in obj
  1552. )
  1553. elif isinstance(obj, dict):
  1554. return {
  1555. k: convert_added_tokens(v, add_type_field=add_type_field)
  1556. for k, v in obj.items()
  1557. }
  1558. return obj
  1559. # add_type_field=True to allow dicts in the kwargs / differentiate from AddedToken serialization
  1560. tokenizer_config = convert_added_tokens(tokenizer_config, add_type_field=True)
  1561. # Add tokenizer class to the tokenizer config to be able to reload it with from_pretrained
  1562. tokenizer_class = self.__class__.__name__
  1563. tokenizer_config["tokenizer_class"] = tokenizer_class
  1564. with io.open(tokenizer_config_file, "w", encoding="utf-8") as f:
  1565. f.write(json.dumps(tokenizer_config, ensure_ascii=False))
  1566. logging.info(f"tokenizer config file saved in {tokenizer_config_file}")
  1567. # Sanitize AddedTokens in special_tokens_map
  1568. write_dict = convert_added_tokens(
  1569. self.special_tokens_map_extended, add_type_field=False
  1570. )
  1571. with open(special_tokens_map_file, "w", encoding="utf-8") as f:
  1572. f.write(json.dumps(write_dict, ensure_ascii=False))
  1573. logging.info(f"Special tokens file saved in {special_tokens_map_file}")
  1574. file_names = (tokenizer_config_file, special_tokens_map_file)
  1575. save_files = self._save_pretrained(
  1576. save_directory=save_directory,
  1577. file_names=file_names,
  1578. filename_prefix=filename_prefix,
  1579. )
  1580. return save_files
  1581. def _save_pretrained(
  1582. self,
  1583. save_directory: Union[str, os.PathLike],
  1584. file_names: Tuple[str],
  1585. filename_prefix: Optional[str] = None,
  1586. ) -> Tuple[str]:
  1587. """
  1588. Save a tokenizer using the tokenizer format: vocabulary + added tokens.
  1589. """
  1590. save_directory = str(save_directory)
  1591. added_tokens_file = os.path.join(
  1592. save_directory,
  1593. (filename_prefix + "-" if filename_prefix else "") + ADDED_TOKENS_FILE,
  1594. )
  1595. added_vocab = self.get_added_vocab()
  1596. if added_vocab:
  1597. with open(added_tokens_file, "w", encoding="utf-8") as f:
  1598. out_str = json.dumps(added_vocab, ensure_ascii=False)
  1599. f.write(out_str)
  1600. logging.info(f"added tokens file saved in {added_tokens_file}")
  1601. self.save_resources(save_directory)
  1602. return file_names + (added_tokens_file,)
  1603. def tokenize(
  1604. self,
  1605. text: str,
  1606. pair: Optional[str] = None,
  1607. add_special_tokens: bool = False,
  1608. **kwargs,
  1609. ) -> List[str]:
  1610. """
  1611. Converts a string in a sequence of tokens, replacing unknown tokens with the `unk_token`.
  1612. Args:
  1613. text (`str`):
  1614. The sequence to be encoded.
  1615. pair (`str`, *optional*):
  1616. A second sequence to be encoded with the first.
  1617. add_special_tokens (`bool`, *optional*, defaults to `False`):
  1618. Whether or not to add the special tokens associated with the corresponding model.
  1619. kwargs (additional keyword arguments, *optional*):
  1620. Will be passed to the underlying model specific encode method. See details in
  1621. [`~PretrainedTokenizerBase.__call__`]
  1622. Returns:
  1623. `List[str]`: The list of tokens.
  1624. """
  1625. raise NotImplementedError
  1626. def num_special_tokens_to_add(self, pair: bool = False) -> int:
  1627. raise NotImplementedError
  1628. def _get_padding_truncation_strategies(
  1629. self,
  1630. padding=False,
  1631. truncation=False,
  1632. max_length=None,
  1633. pad_to_multiple_of=None,
  1634. verbose=True,
  1635. **kwargs,
  1636. ):
  1637. """
  1638. Find the correct padding/truncation strategy with backward compatibility for old arguments (truncation_strategy
  1639. and pad_to_max_length) and behaviors.
  1640. """
  1641. old_truncation_strategy = kwargs.pop("truncation_strategy", "do_not_truncate")
  1642. old_pad_to_max_length = kwargs.pop("pad_to_max_seq_len", False)
  1643. # Backward compatibility for previous behavior, maybe we should deprecate it:
  1644. # If you only set max_length, it activates truncation for max_length
  1645. if max_length is not None and padding is False and truncation is False:
  1646. if verbose:
  1647. if not self.deprecation_warnings.get(
  1648. "Truncation-not-explicitly-activated", False
  1649. ):
  1650. warnings.warn(
  1651. "Truncation was not explicitly activated but `max_length` is provided a specific value, "
  1652. "please use `truncation=True` to explicitly truncate examples to max length. "
  1653. "Defaulting to 'longest_first' truncation strategy. "
  1654. "If you encode pairs of sequences (GLUE-style) with the tokenizer you can select this strategy "
  1655. "more precisely by providing a specific strategy to `truncation`."
  1656. )
  1657. self.deprecation_warnings["Truncation-not-explicitly-activated"] = True
  1658. truncation = "longest_first"
  1659. # Get padding strategy
  1660. if padding is False and old_pad_to_max_length:
  1661. if verbose:
  1662. warnings.warn(
  1663. "The `pad_to_max_length` argument is deprecated and will be removed in a future version, "
  1664. "use `padding=True` or `padding='longest'` to pad to the longest sequence in the batch, or "
  1665. "use `padding='max_length'` to pad to a max length. In this case, you can give a specific "
  1666. "length with `max_length` (e.g. `max_length=45`) or leave max_length to None to pad to the "
  1667. "maximal input size of the model (e.g. 512 for Bert).",
  1668. FutureWarning,
  1669. )
  1670. if max_length is None:
  1671. padding_strategy = PaddingStrategy.LONGEST
  1672. else:
  1673. padding_strategy = PaddingStrategy.MAX_LENGTH
  1674. elif padding is not False:
  1675. if padding is True:
  1676. if verbose:
  1677. if max_length is not None and (
  1678. truncation is False or truncation == "do_not_truncate"
  1679. ):
  1680. warnings.warn(
  1681. "`max_length` is ignored when `padding`=`True` and there is no truncation strategy. "
  1682. "To pad to max length, use `padding='max_length'`."
  1683. )
  1684. if old_pad_to_max_length is not False:
  1685. warnings.warn(
  1686. "Though `pad_to_max_length` = `True`, it is ignored because `padding`=`True`."
  1687. )
  1688. # Default to pad to the longest sequence in the batch
  1689. padding_strategy = PaddingStrategy.LONGEST
  1690. elif not isinstance(padding, PaddingStrategy):
  1691. padding_strategy = PaddingStrategy(padding)
  1692. elif isinstance(padding, PaddingStrategy):
  1693. padding_strategy = padding
  1694. else:
  1695. padding_strategy = PaddingStrategy.DO_NOT_PAD
  1696. # Get truncation strategy
  1697. if truncation is False and old_truncation_strategy != "do_not_truncate":
  1698. if verbose:
  1699. warnings.warn(
  1700. "The `truncation_strategy` argument is deprecated and will be removed in a future version, "
  1701. "use `truncation=True` to truncate examples to a max length. You can give a specific "
  1702. "length with `max_length` (e.g. `max_length=45`) or leave max_length to None to truncate to the "
  1703. "maximal input size of the model (e.g. 512 for Bert). "
  1704. " If you have pairs of inputs, you can give a specific truncation strategy selected among "
  1705. "`truncation='only_first'` (will only truncate the first sentence in the pairs) "
  1706. "`truncation='only_second'` (will only truncate the second sentence in the pairs) "
  1707. "or `truncation='longest_first'` (will iteratively remove tokens from the longest sentence in the pairs).",
  1708. FutureWarning,
  1709. )
  1710. truncation_strategy = TruncationStrategy(old_truncation_strategy)
  1711. elif truncation is not False and truncation is not None:
  1712. if truncation is True:
  1713. truncation_strategy = (
  1714. TruncationStrategy.LONGEST_FIRST
  1715. ) # Default to truncate the longest sequences in pairs of inputs
  1716. elif not isinstance(truncation, TruncationStrategy):
  1717. truncation_strategy = TruncationStrategy(truncation)
  1718. elif isinstance(truncation, TruncationStrategy):
  1719. truncation_strategy = truncation
  1720. else:
  1721. truncation_strategy = TruncationStrategy.DO_NOT_TRUNCATE
  1722. # Set max length if needed
  1723. if max_length is None:
  1724. if padding_strategy == PaddingStrategy.MAX_LENGTH:
  1725. if self.model_max_length > LARGE_INTEGER:
  1726. if verbose:
  1727. if not self.deprecation_warnings.get(
  1728. "Asking-to-pad-to-max_length", False
  1729. ):
  1730. warnings.warn(
  1731. "Asking to pad to max_length but no maximum length is provided and the model has no predefined maximum length. "
  1732. "Default to no padding."
  1733. )
  1734. self.deprecation_warnings["Asking-to-pad-to-max_length"] = True
  1735. padding_strategy = PaddingStrategy.DO_NOT_PAD
  1736. else:
  1737. max_length = self.model_max_length
  1738. if truncation_strategy != TruncationStrategy.DO_NOT_TRUNCATE:
  1739. if self.model_max_length > LARGE_INTEGER:
  1740. if verbose:
  1741. if not self.deprecation_warnings.get(
  1742. "Asking-to-truncate-to-max_length", False
  1743. ):
  1744. warnings.warn(
  1745. "Asking to truncate to max_length but no maximum length is provided and the model has no predefined maximum length. "
  1746. "Default to no truncation."
  1747. )
  1748. self.deprecation_warnings[
  1749. "Asking-to-truncate-to-max_length"
  1750. ] = True
  1751. truncation_strategy = TruncationStrategy.DO_NOT_TRUNCATE
  1752. else:
  1753. max_length = self.model_max_length
  1754. # Test if we have a padding token
  1755. if padding_strategy != PaddingStrategy.DO_NOT_PAD and (
  1756. not self.pad_token or self.pad_token_id < 0
  1757. ):
  1758. raise ValueError(
  1759. "Asking to pad but the tokenizer does not have a padding token. "
  1760. "Please select a token to use as `pad_token` `(tokenizer.pad_token = tokenizer.eos_token e.g.)` "
  1761. "or add a new pad token via `tokenizer.add_special_tokens({'pad_token': '[PAD]'})`."
  1762. )
  1763. # Check that we will truncate to a multiple of pad_to_multiple_of if both are provided
  1764. if (
  1765. truncation_strategy != TruncationStrategy.DO_NOT_TRUNCATE
  1766. and padding_strategy != PaddingStrategy.DO_NOT_PAD
  1767. and pad_to_multiple_of is not None
  1768. and max_length is not None
  1769. and (max_length % pad_to_multiple_of != 0)
  1770. ):
  1771. raise ValueError(
  1772. f"Truncation and padding are both activated but "
  1773. f"truncation length ({max_length}) is not a multiple of pad_to_multiple_of ({pad_to_multiple_of})."
  1774. )
  1775. return padding_strategy, truncation_strategy, max_length, kwargs
  1776. def __call__(
  1777. self,
  1778. text: Union[str, List[str], List[List[str]]],
  1779. text_pair: Optional[Union[str, List[str], List[List[str]]]] = None,
  1780. max_length: Optional[int] = None,
  1781. stride: int = 0,
  1782. is_split_into_words: Union[bool, str] = False,
  1783. padding: Union[bool, str, PaddingStrategy] = False,
  1784. truncation: Union[bool, str, TruncationStrategy] = False,
  1785. return_position_ids: bool = None,
  1786. return_token_type_ids: Optional[bool] = None,
  1787. return_attention_mask: Optional[bool] = None,
  1788. return_length: bool = False,
  1789. return_overflowing_tokens: bool = False,
  1790. return_special_tokens_mask: bool = False,
  1791. return_dict: bool = True,
  1792. return_offsets_mapping: bool = False,
  1793. add_special_tokens: bool = True,
  1794. pad_to_multiple_of: Optional[int] = None,
  1795. return_tensors: Optional[Union[str, TensorType]] = None,
  1796. verbose: bool = True,
  1797. **kwargs,
  1798. ):
  1799. """
  1800. Performs tokenization and uses the tokenized tokens to prepare model
  1801. inputs. It supports sequence or sequence pair as input, and batch input
  1802. is allowed. `self.encode()` or `self.batch_encode()` would be called
  1803. separately for single or batch input depending on input format and
  1804. `is_split_into_words` argument.
  1805. Args:
  1806. text (str, List[str] or List[List[str]]):
  1807. The sequence or batch of sequences to be processed. One sequence
  1808. is a string or a list of strings depending on whether it has been
  1809. pretokenized. If each sequence is provided as a list of strings
  1810. (pretokenized), you must set `is_split_into_words` as `True` to
  1811. disambiguate with a batch of sequences.
  1812. text_pair (str, List[str] or List[List[str]], optional):
  1813. Same as `text` argument, while it represents for the latter
  1814. sequence of the sequence pair.
  1815. max_length (int, optional):
  1816. If set to a number, will limit the total sequence returned so
  1817. that it has a maximum length. If there are overflowing tokens,
  1818. those overflowing tokens will be added to the returned dictionary
  1819. when `return_overflowing_tokens` is `True`. Defaults to `None`.
  1820. stride (int, optional):
  1821. Only available for batch input of sequence pair and mainly for
  1822. question answering usage. When for QA, `text` represents questions
  1823. and `text_pair` represents contexts. If `stride` is set to a
  1824. positive number, the context will be split into multiple spans
  1825. where `stride` defines the number of (tokenized) tokens to skip
  1826. from the start of one span to get the next span, thus will produce
  1827. a bigger batch than inputs to include all spans. Moreover, 'overflow_to_sample'
  1828. and 'offset_mapping' preserving the original example and position
  1829. information will be added to the returned dictionary. Defaults to 0.
  1830. is_split_into_words (Union[bool, str], optional):
  1831. when the text is words or tokens, `is_split_into_words` should be True or `token`.
  1832. `True`: means that the text should be words which should be tokenized.
  1833. `token`: means that the text should be tokens which already be tokenized, so it should not be tokenized again.
  1834. padding (bool, str or [PaddingStrategy], optional):
  1835. Activates and controls padding. Accepts the following values:
  1836. - `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single
  1837. sequence if provided).
  1838. - `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum
  1839. acceptable input length for the model if that argument is not provided.
  1840. - `False` or `'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of different
  1841. lengths).
  1842. Defaults to `False`.
  1843. truncation (bool, str or [TruncationStrategy], optional):
  1844. Activates and controls truncation. Accepts the following values:
  1845. - `True` or `'longest_first'`: Truncate to a maximum length specified with the argument `max_length` or
  1846. to the maximum acceptable input length for the model if that argument is not provided. This will
  1847. truncate token by token, removing a token from the longest sequence in the pair if a pair of
  1848. sequences (or a batch of pairs) is provided.
  1849. - `'only_first'`: Truncate to a maximum length specified with the argument `max_length` or to the
  1850. maximum acceptable input length for the model if that argument is not provided. This will only
  1851. truncate the first sequence of a pair if a pair of sequences (or a batch of pairs) is provided.
  1852. - `'only_second'`: Truncate to a maximum length specified with the argument `max_length` or to the
  1853. maximum acceptable input length for the model if that argument is not provided. This will only
  1854. truncate the second sequence of a pair if a pair of sequences (or a batch of pairs) is provided.
  1855. - `False` or `'do_not_truncate'` (default): No truncation (i.e., can output batch with sequence lengths
  1856. greater than the model maximum admissible input size).
  1857. Defaults to `False`.
  1858. return_position_ids (bool, optional):
  1859. Whether to include tokens position ids in the returned dictionary.
  1860. Defaults to `False`.
  1861. return_token_type_ids (bool, optional):
  1862. Whether to include token type ids in the returned dictionary.
  1863. Defaults to `True`.
  1864. return_attention_mask (bool, optional):
  1865. Whether to include the attention mask in the returned dictionary.
  1866. Defaults to `False`.
  1867. return_length (bool, optional):
  1868. Whether to include the length of each encoded inputs in the
  1869. returned dictionary. Defaults to `False`.
  1870. return_overflowing_tokens (bool, optional):
  1871. Whether to include overflowing token information in the returned
  1872. dictionary. Defaults to `False`.
  1873. return_special_tokens_mask (bool, optional):
  1874. Whether to include special tokens mask information in the returned
  1875. dictionary. Defaults to `False`.
  1876. return_dict (bool, optional):
  1877. Decide the format for returned encoded batch inputs. Only works when
  1878. input is a batch of data.
  1879. ::
  1880. - If True, encoded inputs would be a dictionary like:
  1881. {'input_ids': [[1, 4444, 4385, 1545, 6712],[1, 4444, 4385]],
  1882. 'token_type_ids': [[0, 0, 0, 0, 0], [0, 0, 0]]}
  1883. - If False, encoded inputs would be a list like:
  1884. [{'input_ids': [1, 4444, 4385, 1545, 6712],
  1885. 'token_type_ids': [0, 0, 0, 0, 0]},
  1886. {'input_ids': [1, 4444, 4385], 'token_type_ids': [0, 0, 0]}]
  1887. Defaults to `True`.
  1888. return_offsets_mapping (bool, optional):
  1889. Whether to include the list of pair preserving the index of start
  1890. and end char in original input for each token in the returned
  1891. dictionary. Would be automatically set to `True` when `stride` > 0.
  1892. Defaults to `False`.
  1893. add_special_tokens (bool, optional):
  1894. Whether to add the special tokens associated with the corresponding model
  1895. to the encoded inputs. Defaults to `True`
  1896. pad_to_multiple_of (int, optional):
  1897. If set will pad the sequence to a multiple of the provided value. This is especially useful to enable
  1898. the use of Tensor Cores on NVIDIA hardware with compute capability >= 7.5 (Volta).
  1899. Defaults to `None`.
  1900. return_tensors (str or [TensorType], optional):
  1901. If set, will return tensors instead of list of python integers. Acceptable values are:
  1902. - `'pd'`: Return Paddle `paddle.Tensor` objects.
  1903. - `'np'`: Return Numpy `np.ndarray` objects.
  1904. Defaults to `None`.
  1905. verbose (bool, optional):
  1906. Whether or not to print more information and warnings. Defaults to True.
  1907. Returns:
  1908. dict or list[dict] (for batch input):
  1909. The dict has the following optional items:
  1910. - **input_ids** (list[int] or list[list[int]]): List of token ids to be fed to a model.
  1911. - **position_ids** (list[int] or list[list[int]], optional): List of token position ids to be
  1912. fed to a model. Included when `return_position_ids` is `True`
  1913. - **token_type_ids** (list[int] or list[list[int]], optional): List of token type ids to be
  1914. fed to a model. Included when `return_token_type_ids` is `True`.
  1915. - **attention_mask** (list[int] or list[list[int]], optional): List of integers valued 0 or 1,
  1916. where 0 specifies paddings and should not be attended to by the
  1917. model. Included when `return_attention_mask` is `True`.
  1918. - **seq_len** (int or list[int], optional): The input_ids length. Included when `return_length`
  1919. is `True`.
  1920. - **overflowing_tokens** (list[int] or list[list[int]], optional): List of overflowing tokens.
  1921. Included when if `max_length` is specified and `return_overflowing_tokens`
  1922. is True.
  1923. - **num_truncated_tokens** (int or list[int], optional): The number of overflowing tokens.
  1924. Included when if `max_length` is specified and `return_overflowing_tokens`
  1925. is True.
  1926. - **special_tokens_mask** (list[int] or list[list[int]], optional): List of integers valued 0 or 1,
  1927. with 0 specifying special added tokens and 1 specifying sequence tokens.
  1928. Included when `return_special_tokens_mask` is `True`.
  1929. - **offset_mapping** (list[int], optional): list of pair preserving the
  1930. index of start and end char in original input for each token.
  1931. For a sqecial token, the index pair is `(0, 0)`. Included when
  1932. `return_overflowing_tokens` is True or `stride` > 0.
  1933. - **overflow_to_sample** (int or list[int], optional): Index of example from which this
  1934. feature is generated. Included when `stride` works.
  1935. """
  1936. # Input type checking for clearer error
  1937. def _is_valid_text_input(t):
  1938. if isinstance(t, str):
  1939. # Strings are fine
  1940. return True
  1941. elif isinstance(t, (list, tuple)):
  1942. # List are fine as long as they are...
  1943. if len(t) == 0:
  1944. # ... empty
  1945. return True
  1946. elif isinstance(t[0], str):
  1947. # ... list of strings
  1948. return True
  1949. elif isinstance(t[0], (list, tuple)):
  1950. # ... list with an empty list or with a list of strings
  1951. return len(t[0]) == 0 or isinstance(t[0][0], str)
  1952. else:
  1953. return False
  1954. else:
  1955. return False
  1956. if not _is_valid_text_input(text):
  1957. raise ValueError(
  1958. "text input must of type `str` (single example), `List[str]` (batch or single pretokenized example) "
  1959. "or `List[List[str]]` (batch of pretokenized examples)."
  1960. )
  1961. if text_pair is not None and not _is_valid_text_input(text_pair):
  1962. raise ValueError(
  1963. "text input must of type `str` (single example), `List[str]` (batch or single pretokenized example) "
  1964. "or `List[List[str]]` (batch of pretokenized examples)."
  1965. )
  1966. # check `split_into_words` value
  1967. if isinstance(is_split_into_words, str) and is_split_into_words != "token":
  1968. raise ValueError(
  1969. "the value of `is_split_into_words` should be one of: {True, False, 'token'} but receive: <%s>",
  1970. is_split_into_words,
  1971. )
  1972. if is_split_into_words:
  1973. is_batched = (
  1974. isinstance(text, (list, tuple))
  1975. and text
  1976. and isinstance(text[0], (list, tuple))
  1977. )
  1978. else:
  1979. is_batched = isinstance(text, (list, tuple))
  1980. if is_batched:
  1981. if isinstance(text_pair, str):
  1982. raise TypeError(
  1983. "when tokenizing batches of text, `text_pair` must be a list or tuple with the same length as `text`."
  1984. )
  1985. if text_pair is not None and len(text) != len(text_pair):
  1986. raise ValueError(
  1987. f"batch length of `text`: {len(text)} does not match batch length of `text_pair`: {len(text_pair)}."
  1988. )
  1989. batch_text_or_text_pairs = (
  1990. list(zip(text, text_pair)) if text_pair is not None else text
  1991. )
  1992. return self.batch_encode(
  1993. batch_text_or_text_pairs=batch_text_or_text_pairs,
  1994. max_length=max_length,
  1995. stride=stride,
  1996. is_split_into_words=is_split_into_words,
  1997. padding=padding,
  1998. truncation=truncation,
  1999. return_position_ids=return_position_ids,
  2000. return_token_type_ids=return_token_type_ids,
  2001. return_attention_mask=return_attention_mask,
  2002. return_length=return_length,
  2003. return_overflowing_tokens=return_overflowing_tokens,
  2004. return_special_tokens_mask=return_special_tokens_mask,
  2005. return_dict=return_dict,
  2006. return_offsets_mapping=return_offsets_mapping,
  2007. add_special_tokens=add_special_tokens,
  2008. pad_to_multiple_of=pad_to_multiple_of,
  2009. return_tensors=return_tensors,
  2010. verbose=verbose,
  2011. **kwargs,
  2012. )
  2013. else:
  2014. return self.encode(
  2015. text=text,
  2016. text_pair=text_pair,
  2017. max_length=max_length,
  2018. stride=stride,
  2019. is_split_into_words=is_split_into_words,
  2020. padding=padding,
  2021. truncation=truncation,
  2022. return_position_ids=return_position_ids,
  2023. return_token_type_ids=return_token_type_ids,
  2024. return_attention_mask=return_attention_mask,
  2025. return_length=return_length,
  2026. return_overflowing_tokens=return_overflowing_tokens,
  2027. return_special_tokens_mask=return_special_tokens_mask,
  2028. return_offsets_mapping=return_offsets_mapping,
  2029. add_special_tokens=add_special_tokens,
  2030. pad_to_multiple_of=pad_to_multiple_of,
  2031. return_tensors=return_tensors,
  2032. verbose=verbose,
  2033. **kwargs,
  2034. )
  2035. def encode(
  2036. self,
  2037. text,
  2038. text_pair=None,
  2039. add_special_tokens=True,
  2040. padding: Union[bool, str, PaddingStrategy] = False,
  2041. truncation: Union[bool, str, TruncationStrategy] = False,
  2042. max_length: Optional[int] = None,
  2043. stride: int = 0,
  2044. is_split_into_words: bool = False,
  2045. pad_to_multiple_of: Optional[int] = None,
  2046. return_tensors: Optional[Union[str, TensorType]] = None,
  2047. return_token_type_ids: Optional[bool] = None,
  2048. return_attention_mask: Optional[bool] = None,
  2049. return_overflowing_tokens: bool = False,
  2050. return_special_tokens_mask: bool = False,
  2051. return_offsets_mapping: bool = False,
  2052. return_length: bool = False,
  2053. verbose: bool = True,
  2054. return_position_ids=None,
  2055. **kwargs,
  2056. ) -> BatchEncoding:
  2057. """
  2058. Tokenize and prepare for the model a sequence or a pair of sequences.
  2059. Args:
  2060. text (`str`, `List[str]` or `List[int]`):
  2061. The first sequence to be encoded. This can be a string, a list of strings (tokenized string using the
  2062. `tokenize` method) or a list of integers (tokenized string ids using the `convert_tokens_to_ids`
  2063. method).
  2064. text_pair (`str`, `List[str]` or `List[int]`, *optional*):
  2065. Optional second sequence to be encoded. This can be a string, a list of strings (tokenized string using
  2066. the `tokenize` method) or a list of integers (tokenized string ids using the `convert_tokens_to_ids`
  2067. method).
  2068. """
  2069. # Backward compatibility for 'max_seq_len'
  2070. old_max_seq_len = kwargs.get("max_seq_len", None)
  2071. if max_length is None and old_max_seq_len:
  2072. if verbose:
  2073. warnings.warn(
  2074. "The `max_seq_len` argument is deprecated and will be removed in a future version, "
  2075. "please use `max_length` instead.",
  2076. FutureWarning,
  2077. )
  2078. max_length = old_max_seq_len
  2079. # Backward compatibility for 'truncation_strategy', 'pad_to_max_length'
  2080. padding_strategy, truncation_strategy, max_length, kwargs = (
  2081. self._get_padding_truncation_strategies(
  2082. padding=padding,
  2083. truncation=truncation,
  2084. max_length=max_length,
  2085. pad_to_multiple_of=pad_to_multiple_of,
  2086. verbose=verbose,
  2087. **kwargs,
  2088. )
  2089. )
  2090. return self._encode_plus(
  2091. text=text,
  2092. text_pair=text_pair,
  2093. add_special_tokens=add_special_tokens,
  2094. padding_strategy=padding_strategy,
  2095. truncation_strategy=truncation_strategy,
  2096. max_length=max_length,
  2097. stride=stride,
  2098. is_split_into_words=is_split_into_words,
  2099. pad_to_multiple_of=pad_to_multiple_of,
  2100. return_tensors=return_tensors,
  2101. return_position_ids=return_position_ids,
  2102. return_token_type_ids=return_token_type_ids,
  2103. return_attention_mask=return_attention_mask,
  2104. return_overflowing_tokens=return_overflowing_tokens,
  2105. return_special_tokens_mask=return_special_tokens_mask,
  2106. return_offsets_mapping=return_offsets_mapping,
  2107. return_length=return_length,
  2108. verbose=verbose,
  2109. **kwargs,
  2110. )
  2111. def encode_plus(
  2112. self,
  2113. text: Union[TextInput, PreTokenizedInput, EncodedInput],
  2114. text_pair: Optional[Union[TextInput, PreTokenizedInput, EncodedInput]] = None,
  2115. add_special_tokens: bool = True,
  2116. padding: Union[bool, str, PaddingStrategy] = False,
  2117. truncation: Union[bool, str, TruncationStrategy] = None,
  2118. max_length: Optional[int] = None,
  2119. stride: int = 0,
  2120. is_split_into_words: bool = False,
  2121. pad_to_multiple_of: Optional[int] = None,
  2122. return_tensors: Optional[Union[str, TensorType]] = None,
  2123. return_token_type_ids: Optional[bool] = None,
  2124. return_attention_mask: Optional[bool] = None,
  2125. return_overflowing_tokens: bool = False,
  2126. return_special_tokens_mask: bool = False,
  2127. return_offsets_mapping: bool = False,
  2128. return_length: bool = False,
  2129. verbose: bool = True,
  2130. **kwargs,
  2131. ) -> BatchEncoding:
  2132. """
  2133. Tokenize and prepare for the model a sequence or a pair of sequences.
  2134. <Tip warning={true}>
  2135. This method is deprecated, `__call__` should be used instead.
  2136. </Tip>
  2137. Args:
  2138. text (`str`, `List[str]` or `List[int]` (the latter only for not-fast tokenizers)):
  2139. The first sequence to be encoded. This can be a string, a list of strings (tokenized string using the
  2140. `tokenize` method) or a list of integers (tokenized string ids using the `convert_tokens_to_ids`
  2141. method).
  2142. text_pair (`str`, `List[str]` or `List[int]`, *optional*):
  2143. Optional second sequence to be encoded. This can be a string, a list of strings (tokenized string using
  2144. the `tokenize` method) or a list of integers (tokenized string ids using the `convert_tokens_to_ids`
  2145. method).
  2146. """
  2147. # Backward compatibility for 'truncation_strategy', 'pad_to_max_length'
  2148. padding_strategy, truncation_strategy, max_length, kwargs = (
  2149. self._get_padding_truncation_strategies(
  2150. padding=padding,
  2151. truncation=truncation,
  2152. max_length=max_length,
  2153. pad_to_multiple_of=pad_to_multiple_of,
  2154. verbose=verbose,
  2155. **kwargs,
  2156. )
  2157. )
  2158. return self._encode_plus(
  2159. text=text,
  2160. text_pair=text_pair,
  2161. add_special_tokens=add_special_tokens,
  2162. padding_strategy=padding_strategy,
  2163. truncation_strategy=truncation_strategy,
  2164. max_length=max_length,
  2165. stride=stride,
  2166. is_split_into_words=is_split_into_words,
  2167. pad_to_multiple_of=pad_to_multiple_of,
  2168. return_tensors=return_tensors,
  2169. return_token_type_ids=return_token_type_ids,
  2170. return_attention_mask=return_attention_mask,
  2171. return_overflowing_tokens=return_overflowing_tokens,
  2172. return_special_tokens_mask=return_special_tokens_mask,
  2173. return_offsets_mapping=return_offsets_mapping,
  2174. return_length=return_length,
  2175. verbose=verbose,
  2176. **kwargs,
  2177. )
  2178. def _encode_plus(
  2179. self,
  2180. text: Union[TextInput, PreTokenizedInput, EncodedInput],
  2181. text_pair: Optional[Union[TextInput, PreTokenizedInput, EncodedInput]] = None,
  2182. add_special_tokens: bool = True,
  2183. padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
  2184. truncation_strategy: TruncationStrategy = TruncationStrategy.DO_NOT_TRUNCATE,
  2185. max_length: Optional[int] = None,
  2186. stride: int = 0,
  2187. is_split_into_words: bool = False,
  2188. pad_to_multiple_of: Optional[int] = None,
  2189. return_position_ids: Optional[bool] = None,
  2190. return_tensors: Optional[Union[str, TensorType]] = None,
  2191. return_token_type_ids: Optional[bool] = None,
  2192. return_attention_mask: Optional[bool] = None,
  2193. return_overflowing_tokens: bool = False,
  2194. return_special_tokens_mask: bool = False,
  2195. return_offsets_mapping: bool = False,
  2196. return_length: bool = False,
  2197. verbose: bool = True,
  2198. **kwargs,
  2199. ) -> BatchEncoding:
  2200. raise NotImplementedError
  2201. def batch_encode(
  2202. self,
  2203. batch_text_or_text_pairs: Union[
  2204. List[TextInput],
  2205. List[TextInputPair],
  2206. List[PreTokenizedInput],
  2207. List[PreTokenizedInputPair],
  2208. List[EncodedInput],
  2209. List[EncodedInputPair],
  2210. ],
  2211. max_length=None,
  2212. stride: int = 0,
  2213. is_split_into_words: bool = False,
  2214. padding: Union[bool, str, PaddingStrategy] = False,
  2215. truncation: Union[bool, str, TruncationStrategy] = False,
  2216. return_position_ids=None,
  2217. # TODO(wj-mcat): keep align with `encode` method
  2218. return_token_type_ids=None,
  2219. return_attention_mask=None,
  2220. return_length=False,
  2221. return_overflowing_tokens=False,
  2222. return_special_tokens_mask=False,
  2223. return_dict=True,
  2224. return_offsets_mapping=False,
  2225. add_special_tokens=True,
  2226. pad_to_multiple_of: Optional[int] = None,
  2227. return_tensors: Optional[Union[str, TensorType]] = None,
  2228. verbose: bool = True,
  2229. **kwargs,
  2230. ) -> BatchEncoding:
  2231. """
  2232. Performs tokenization and uses the tokenized tokens to prepare model
  2233. inputs. It supports batch inputs of sequence or sequence pair.
  2234. Args:
  2235. batch_text_or_text_pairs (list):
  2236. The element of list can be sequence or sequence pair, and the
  2237. sequence is a string or a list of strings depending on whether
  2238. it has been pretokenized. If each sequence is provided as a list
  2239. of strings (pretokenized), you must set `is_split_into_words` as
  2240. `True` to disambiguate with a sequence pair.
  2241. Returns:
  2242. dict or list[dict]:
  2243. The dict has the following optional items:
  2244. """
  2245. # Backward compatibility for 'max_seq_len'
  2246. old_max_seq_len = kwargs.get("max_seq_len", None)
  2247. if max_length is None and old_max_seq_len:
  2248. if verbose:
  2249. warnings.warn(
  2250. "The `max_seq_len` argument is deprecated and will be removed in a future version, "
  2251. "please use `max_length` instead.",
  2252. FutureWarning,
  2253. )
  2254. max_length = old_max_seq_len
  2255. # Backward compatibility for 'truncation_strategy', 'pad_to_max_length'
  2256. padding_strategy, truncation_strategy, max_length, kwargs = (
  2257. self._get_padding_truncation_strategies(
  2258. padding=padding,
  2259. truncation=truncation,
  2260. max_length=max_length,
  2261. pad_to_multiple_of=pad_to_multiple_of,
  2262. verbose=verbose,
  2263. **kwargs,
  2264. )
  2265. )
  2266. return self._batch_encode_plus(
  2267. batch_text_or_text_pairs=batch_text_or_text_pairs,
  2268. add_special_tokens=add_special_tokens,
  2269. padding_strategy=padding_strategy,
  2270. truncation_strategy=truncation_strategy,
  2271. max_length=max_length,
  2272. stride=stride,
  2273. is_split_into_words=is_split_into_words,
  2274. pad_to_multiple_of=pad_to_multiple_of,
  2275. return_tensors=return_tensors,
  2276. return_position_ids=return_position_ids,
  2277. return_token_type_ids=return_token_type_ids,
  2278. return_attention_mask=return_attention_mask,
  2279. return_overflowing_tokens=return_overflowing_tokens,
  2280. return_special_tokens_mask=return_special_tokens_mask,
  2281. return_dict=return_dict,
  2282. return_offsets_mapping=return_offsets_mapping,
  2283. return_length=return_length,
  2284. verbose=verbose,
  2285. **kwargs,
  2286. )
  2287. def _batch_encode_plus(
  2288. self,
  2289. batch_text_or_text_pairs: Union[
  2290. List[TextInput],
  2291. List[TextInputPair],
  2292. List[PreTokenizedInput],
  2293. List[PreTokenizedInputPair],
  2294. List[EncodedInput],
  2295. List[EncodedInputPair],
  2296. ],
  2297. add_special_tokens: bool = True,
  2298. padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
  2299. truncation_strategy: TruncationStrategy = TruncationStrategy.DO_NOT_TRUNCATE,
  2300. max_length: Optional[int] = None,
  2301. stride: int = 0,
  2302. is_split_into_words: bool = False,
  2303. pad_to_multiple_of: Optional[int] = None,
  2304. return_position_ids: Optional[bool] = None,
  2305. return_tensors: Optional[Union[str, TensorType]] = None,
  2306. return_token_type_ids: Optional[bool] = None,
  2307. return_attention_mask: Optional[bool] = None,
  2308. return_overflowing_tokens: bool = False,
  2309. return_special_tokens_mask: bool = False,
  2310. return_dict: bool = True,
  2311. return_offsets_mapping: bool = False,
  2312. return_length: bool = False,
  2313. verbose: bool = True,
  2314. **kwargs,
  2315. ) -> BatchEncoding:
  2316. raise NotImplementedError
  2317. def pad(
  2318. self,
  2319. encoded_inputs: Union[
  2320. BatchEncoding,
  2321. List[BatchEncoding],
  2322. Dict[str, EncodedInput],
  2323. Dict[str, List[EncodedInput]],
  2324. List[Dict[str, EncodedInput]],
  2325. ],
  2326. padding: Union[bool, str, PaddingStrategy] = True,
  2327. max_length: Optional[int] = None,
  2328. pad_to_multiple_of: Optional[int] = None,
  2329. return_attention_mask: Optional[bool] = None,
  2330. return_tensors: Optional[Union[str, TensorType]] = None,
  2331. verbose: bool = True,
  2332. ) -> BatchEncoding:
  2333. """
  2334. Pad a single encoded input or a batch of encoded inputs up to predefined length or to the max sequence length
  2335. in the batch.
  2336. Padding side (left/right) padding token ids are defined at the tokenizer level (with `self.padding_side`,
  2337. `self.pad_token_id` and `self.pad_token_type_id`)
  2338. <Tip>
  2339. If the `encoded_inputs` passed are dictionary of numpy arrays, Paddle tensors, the
  2340. result will use the same type unless you provide a different tensor type with `return_tensors`.
  2341. </Tip>
  2342. Args:
  2343. encoded_inputs ([`BatchEncoding`], list of [`BatchEncoding`], `Dict[str, List[int]]`, `Dict[str, List[List[int]]` or `List[Dict[str, List[int]]]`):
  2344. Tokenized inputs. Can represent one input ([`BatchEncoding`] or `Dict[str, List[int]]`) or a batch of
  2345. tokenized inputs (list of [`BatchEncoding`], *Dict[str, List[List[int]]]* or *List[Dict[str,
  2346. List[int]]]*) so you can use this method during preprocessing as well as in a Paddle Dataloader
  2347. collate function.
  2348. Instead of `List[int]` you can have tensors (numpy arrays, Paddle tensors), see
  2349. the note above for the return type.
  2350. padding (`bool`, `str` or [`PaddingStrategy`], *optional*, defaults to `True`):
  2351. Select a strategy to pad the returned sequences (according to the model's padding side and padding
  2352. index) among:
  2353. - `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single
  2354. sequence if provided).
  2355. - `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum
  2356. acceptable input length for the model if that argument is not provided.
  2357. - `False` or `'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of different
  2358. lengths).
  2359. max_length (`int`, *optional*):
  2360. Maximum length of the returned list and optionally padding length (see above).
  2361. pad_to_multiple_of (`int`, *optional*):
  2362. If set will pad the sequence to a multiple of the provided value.
  2363. This is especially useful to enable the use of Tensor Cores on NVIDIA hardware with compute capability
  2364. >= 7.5 (Volta).
  2365. return_attention_mask (`bool`, *optional*):
  2366. Whether to return the attention mask. If left to the default, will return the attention mask according
  2367. to the specific tokenizer's default, defined by the `return_outputs` attribute.
  2368. [What are attention masks?](../glossary#attention-mask)
  2369. return_tensors (`str` or [`TensorType`], *optional*):
  2370. If set, will return tensors instead of list of python integers. Acceptable values are:
  2371. - `'pd'`: Return Paddle `paddle.Tensor` objects.
  2372. - `'np'`: Return Numpy `np.ndarray` objects.
  2373. verbose (`bool`, *optional*, defaults to `True`):
  2374. Whether or not to print more information and warnings.
  2375. """
  2376. # If we have a list of dicts, let's convert it in a dict of lists
  2377. if isinstance(encoded_inputs, (list, tuple)) and isinstance(
  2378. encoded_inputs[0], (dict, BatchEncoding)
  2379. ):
  2380. encoded_inputs = {
  2381. key: [example[key] for example in encoded_inputs]
  2382. for key in encoded_inputs[0].keys()
  2383. }
  2384. # The model's main input name, usually `input_ids`, has be passed for padding
  2385. if self.model_input_names[0] not in encoded_inputs:
  2386. raise ValueError(
  2387. "You should supply an encoding or a list of encodings to this method "
  2388. f"that includes {self.model_input_names[0]}, but you provided {list(encoded_inputs.keys())}"
  2389. )
  2390. required_input = encoded_inputs[self.model_input_names[0]]
  2391. if not required_input:
  2392. if return_attention_mask:
  2393. encoded_inputs["attention_mask"] = []
  2394. return encoded_inputs
  2395. # If we have Paddle/NumPy tensors/arrays as inputs, we cast them as python objects
  2396. # and rebuild them afterwards if no return_tensors is specified
  2397. first_element = required_input[0]
  2398. if isinstance(first_element, (list, tuple)):
  2399. # first_element might be an empty list/tuple in some edge cases so we grab the first non empty element.
  2400. for item in required_input:
  2401. if len(item) != 0:
  2402. first_element = item[0]
  2403. break
  2404. # At this state, if `first_element` is still a list/tuple, it's an empty one so there is nothing to do.
  2405. if not isinstance(first_element, (int, list, tuple)):
  2406. if isinstance(first_element, paddle.Tensor):
  2407. return_tensors = "pd" if return_tensors is None else return_tensors
  2408. else:
  2409. raise ValueError(
  2410. f"type of {first_element} unknown: {type(first_element)}. "
  2411. f"Should be either python or paddle object."
  2412. )
  2413. for key, value in encoded_inputs.items():
  2414. encoded_inputs[key] = to_py_obj(value)
  2415. # Convert padding_strategy in PaddingStrategy
  2416. padding_strategy, _, max_length, _ = self._get_padding_truncation_strategies(
  2417. padding=padding, max_length=max_length, verbose=verbose
  2418. )
  2419. required_input = encoded_inputs[self.model_input_names[0]]
  2420. if required_input and not isinstance(required_input[0], (list, tuple)):
  2421. encoded_inputs = self._pad(
  2422. encoded_inputs,
  2423. max_length=max_length,
  2424. padding_strategy=padding_strategy,
  2425. pad_to_multiple_of=pad_to_multiple_of,
  2426. return_attention_mask=return_attention_mask,
  2427. )
  2428. return BatchEncoding(encoded_inputs, tensor_type=return_tensors)
  2429. batch_size = len(required_input)
  2430. assert all(
  2431. len(v) == batch_size for v in encoded_inputs.values()
  2432. ), "Some items in the output dictionary have a different batch size than others."
  2433. if padding_strategy == PaddingStrategy.LONGEST:
  2434. max_length = max(len(inputs) for inputs in required_input)
  2435. padding_strategy = PaddingStrategy.MAX_LENGTH
  2436. batch_outputs = {}
  2437. for i in range(batch_size):
  2438. inputs = dict((k, v[i]) for k, v in encoded_inputs.items())
  2439. outputs = self._pad(
  2440. inputs,
  2441. max_length=max_length,
  2442. padding_strategy=padding_strategy,
  2443. pad_to_multiple_of=pad_to_multiple_of,
  2444. return_attention_mask=return_attention_mask,
  2445. )
  2446. for key, value in outputs.items():
  2447. if key not in batch_outputs:
  2448. batch_outputs[key] = []
  2449. batch_outputs[key].append(value)
  2450. return BatchEncoding(batch_outputs, tensor_type=return_tensors)
  2451. def create_token_type_ids_from_sequences(
  2452. self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
  2453. ) -> List[int]:
  2454. """
  2455. Create the token type IDs corresponding to the sequences passed. [What are token type
  2456. IDs?](../glossary#token-type-ids)
  2457. Should be overridden in a subclass if the model has a special way of building those.
  2458. Args:
  2459. token_ids_0 (`List[int]`): The first tokenized sequence.
  2460. token_ids_1 (`List[int]`, *optional*): The second tokenized sequence.
  2461. Returns:
  2462. `List[int]`: The token type ids.
  2463. """
  2464. if token_ids_1 is None:
  2465. return len(token_ids_0) * [0]
  2466. return [0] * len(token_ids_0) + [1] * len(token_ids_1)
  2467. def build_inputs_with_special_tokens(
  2468. self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
  2469. ) -> List[int]:
  2470. """
  2471. Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
  2472. adding special tokens.
  2473. This implementation does not add special tokens and this method should be overridden in a subclass.
  2474. Args:
  2475. token_ids_0 (`List[int]`): The first tokenized sequence.
  2476. token_ids_1 (`List[int]`, *optional*): The second tokenized sequence.
  2477. Returns:
  2478. `List[int]`: The model input with special tokens.
  2479. """
  2480. if token_ids_1 is None:
  2481. return token_ids_0
  2482. return token_ids_0 + token_ids_1
  2483. def build_offset_mapping_with_special_tokens(
  2484. self, offset_mapping_0, offset_mapping_1=None
  2485. ):
  2486. """
  2487. Build offset map from a pair of offset map by concatenating and adding offsets of special tokens.
  2488. Should be overridden in a subclass if the model has a special way of building those.
  2489. Args:
  2490. offset_mapping_0 (List[tuple]):
  2491. List of char offsets to which the special tokens will be added.
  2492. offset_mapping_1 (List[tuple], optional):
  2493. Optional second list of char offsets for offset mapping pairs.
  2494. Returns:
  2495. List[tuple]: List of char offsets with the appropriate offsets of special tokens.
  2496. """
  2497. if offset_mapping_1 is None:
  2498. return offset_mapping_0
  2499. return offset_mapping_0 + offset_mapping_1
  2500. def prepare_for_model(
  2501. self,
  2502. ids,
  2503. pair_ids=None,
  2504. padding: Union[bool, str, PaddingStrategy] = False,
  2505. truncation: Union[bool, str, TruncationStrategy] = False,
  2506. max_length: Optional[int] = None,
  2507. stride: int = 0,
  2508. pad_to_multiple_of: Optional[int] = None,
  2509. return_tensors: Optional[Union[str, TensorType]] = None,
  2510. return_position_ids=None,
  2511. return_token_type_ids: Optional[bool] = None,
  2512. return_attention_mask: Optional[bool] = None,
  2513. return_length=False,
  2514. return_overflowing_tokens=False,
  2515. return_special_tokens_mask=False,
  2516. return_offsets_mapping=False,
  2517. add_special_tokens=True,
  2518. verbose: bool = True,
  2519. prepend_batch_axis: bool = False,
  2520. **kwargs,
  2521. ):
  2522. """
  2523. Performs tokenization and uses the tokenized tokens to prepare model
  2524. inputs. It supports sequence or sequence pair as input, and batch input
  2525. is not allowed.
  2526. """
  2527. padding_strategy, truncation_strategy, max_length, kwargs = (
  2528. self._get_padding_truncation_strategies(
  2529. padding=padding,
  2530. truncation=truncation,
  2531. max_length=max_length,
  2532. pad_to_multiple_of=pad_to_multiple_of,
  2533. verbose=verbose,
  2534. **kwargs,
  2535. )
  2536. )
  2537. pair = bool(pair_ids is not None)
  2538. len_ids = len(ids)
  2539. len_pair_ids = len(pair_ids) if pair else 0
  2540. if return_token_type_ids and not add_special_tokens:
  2541. raise ValueError(
  2542. "Asking to return token_type_ids while setting add_special_tokens to False "
  2543. "results in an undefined behavior. Please set add_special_tokens to True or "
  2544. "set return_token_type_ids to None."
  2545. )
  2546. if (
  2547. return_overflowing_tokens
  2548. and truncation_strategy == TruncationStrategy.LONGEST_FIRST
  2549. and pair_ids is not None
  2550. ):
  2551. raise ValueError(
  2552. "Not possible to return overflowing tokens for pair of sequences with the "
  2553. "`longest_first`. Please select another truncation strategy than `longest_first`, "
  2554. "for instance `only_second` or `only_first`."
  2555. )
  2556. # Load from model defaults
  2557. if return_token_type_ids is None:
  2558. return_token_type_ids = "token_type_ids" in self.model_input_names
  2559. if return_attention_mask is None:
  2560. return_attention_mask = "attention_mask" in self.model_input_names
  2561. if return_position_ids is None:
  2562. return_position_ids = "position_ids" in self.model_input_names
  2563. encoded_inputs = {}
  2564. # Truncation: Handle max sequence length
  2565. total_len = (
  2566. len_ids
  2567. + len_pair_ids
  2568. + (self.num_special_tokens_to_add(pair=pair) if add_special_tokens else 0)
  2569. )
  2570. overflowing_tokens = []
  2571. if (
  2572. truncation_strategy != TruncationStrategy.DO_NOT_TRUNCATE
  2573. and max_length
  2574. and total_len > max_length
  2575. ):
  2576. ids, pair_ids, overflowing_tokens = self.truncate_sequences(
  2577. ids,
  2578. pair_ids=pair_ids,
  2579. num_tokens_to_remove=total_len - max_length,
  2580. truncation_strategy=truncation_strategy,
  2581. stride=stride,
  2582. )
  2583. if return_overflowing_tokens:
  2584. encoded_inputs["overflowing_tokens"] = overflowing_tokens
  2585. encoded_inputs["num_truncated_tokens"] = total_len - max_length
  2586. # Add special tokens
  2587. if add_special_tokens:
  2588. sequence = self.build_inputs_with_special_tokens(ids, pair_ids)
  2589. token_type_ids = self.create_token_type_ids_from_sequences(ids, pair_ids)
  2590. else:
  2591. sequence = ids + pair_ids if pair else ids
  2592. token_type_ids = [0] * len(ids) + ([0] * len(pair_ids) if pair else [])
  2593. # Build output dictionnary
  2594. encoded_inputs["input_ids"] = sequence
  2595. if return_token_type_ids:
  2596. encoded_inputs["token_type_ids"] = token_type_ids
  2597. if return_special_tokens_mask:
  2598. if add_special_tokens:
  2599. encoded_inputs["special_tokens_mask"] = self.get_special_tokens_mask(
  2600. ids, pair_ids
  2601. )
  2602. else:
  2603. encoded_inputs["special_tokens_mask"] = [0] * len(sequence)
  2604. if return_offsets_mapping and "text" in kwargs and "text_pair" in kwargs:
  2605. text = kwargs.pop("text")
  2606. text_pair = kwargs.pop("text_pair")
  2607. token_offset_mapping = self.get_offset_mapping(text)
  2608. token_pair_offset_mapping = (
  2609. self.get_offset_mapping(text_pair) if text_pair is not None else None
  2610. )
  2611. if max_length and total_len > max_length:
  2612. token_offset_mapping, token_pair_offset_mapping, _ = (
  2613. self.truncate_sequences(
  2614. token_offset_mapping,
  2615. pair_ids=token_pair_offset_mapping,
  2616. num_tokens_to_remove=total_len - max_length,
  2617. truncation_strategy=truncation_strategy,
  2618. stride=stride,
  2619. )
  2620. )
  2621. if add_special_tokens:
  2622. offset_mapping = self.build_offset_mapping_with_special_tokens(
  2623. token_offset_mapping, token_pair_offset_mapping
  2624. )
  2625. else:
  2626. offset_mapping = (
  2627. token_offset_mapping + token_pair_offset_mapping
  2628. if token_pair_offset_mapping
  2629. else token_offset_mapping
  2630. )
  2631. encoded_inputs["offset_mapping"] = offset_mapping
  2632. # Check lengths
  2633. self._eventual_warn_about_too_long_sequence(
  2634. encoded_inputs["input_ids"], max_length, verbose
  2635. )
  2636. if return_position_ids:
  2637. encoded_inputs["position_ids"] = list(
  2638. range(len(encoded_inputs["input_ids"]))
  2639. )
  2640. if padding_strategy != PaddingStrategy.DO_NOT_PAD or return_attention_mask:
  2641. encoded_inputs = self.pad(
  2642. encoded_inputs,
  2643. max_length=max_length,
  2644. padding=padding_strategy.value,
  2645. pad_to_multiple_of=pad_to_multiple_of,
  2646. return_attention_mask=return_attention_mask,
  2647. )
  2648. if return_length:
  2649. encoded_inputs["length"] = len(encoded_inputs["input_ids"])
  2650. # for compatibility
  2651. encoded_inputs["seq_len"] = encoded_inputs["length"]
  2652. batch_outputs = BatchEncoding(
  2653. encoded_inputs,
  2654. tensor_type=return_tensors,
  2655. prepend_batch_axis=prepend_batch_axis,
  2656. )
  2657. return batch_outputs
  2658. def truncate_sequences(
  2659. self,
  2660. ids: List[int],
  2661. pair_ids: Optional[List[int]] = None,
  2662. num_tokens_to_remove: int = 0,
  2663. truncation_strategy: Union[str, TruncationStrategy] = "longest_first",
  2664. stride: int = 0,
  2665. ) -> Tuple[List[int], List[int], List[int]]:
  2666. """
  2667. Truncates a sequence pair in-place following the strategy.
  2668. Args:
  2669. ids (`List[int]`):
  2670. Tokenized input ids of the first sequence. Can be obtained from a string by chaining the `tokenize` and
  2671. `convert_tokens_to_ids` methods.
  2672. pair_ids (`List[int]`, *optional*):
  2673. Tokenized input ids of the second sequence. Can be obtained from a string by chaining the `tokenize`
  2674. and `convert_tokens_to_ids` methods.
  2675. num_tokens_to_remove (`int`, *optional*, defaults to 0):
  2676. Number of tokens to remove using the truncation strategy.
  2677. truncation_strategy (`str` or [`TruncationStrategy`], *optional*, defaults to `False`):
  2678. The strategy to follow for truncation. Can be:
  2679. - `'longest_first'`: Truncate to a maximum length specified with the argument `max_length` or to the
  2680. maximum acceptable input length for the model if that argument is not provided. This will truncate
  2681. token by token, removing a token from the longest sequence in the pair if a pair of sequences (or a
  2682. batch of pairs) is provided.
  2683. - `'only_first'`: Truncate to a maximum length specified with the argument `max_length` or to the
  2684. maximum acceptable input length for the model if that argument is not provided. This will only
  2685. truncate the first sequence of a pair if a pair of sequences (or a batch of pairs) is provided.
  2686. - `'only_second'`: Truncate to a maximum length specified with the argument `max_length` or to the
  2687. maximum acceptable input length for the model if that argument is not provided. This will only
  2688. truncate the second sequence of a pair if a pair of sequences (or a batch of pairs) is provided.
  2689. - `'do_not_truncate'` (default): No truncation (i.e., can output batch with sequence lengths greater
  2690. than the model maximum admissible input size).
  2691. stride (`int`, *optional*, defaults to 0):
  2692. If set to a positive number, the overflowing tokens returned will contain some tokens from the main
  2693. sequence returned. The value of this argument defines the number of additional tokens.
  2694. Returns:
  2695. `Tuple[List[int], List[int], List[int]]`: The truncated `ids`, the truncated `pair_ids` and the list of
  2696. overflowing tokens. Note: The *longest_first* strategy returns empty list of overflowing tokens if a pair
  2697. of sequences (or a batch of pairs) is provided.
  2698. """
  2699. if num_tokens_to_remove <= 0:
  2700. return ids, pair_ids, []
  2701. if not isinstance(truncation_strategy, TruncationStrategy):
  2702. truncation_strategy = TruncationStrategy(truncation_strategy)
  2703. overflowing_tokens = []
  2704. if truncation_strategy == TruncationStrategy.ONLY_FIRST or (
  2705. truncation_strategy == TruncationStrategy.LONGEST_FIRST and pair_ids is None
  2706. ):
  2707. if len(ids) > num_tokens_to_remove:
  2708. window_len = min(len(ids), stride + num_tokens_to_remove)
  2709. if self.truncation_side == "left":
  2710. overflowing_tokens = ids[:window_len]
  2711. ids = ids[num_tokens_to_remove:]
  2712. elif self.truncation_side == "right":
  2713. overflowing_tokens = ids[-window_len:]
  2714. ids = ids[:-num_tokens_to_remove]
  2715. else:
  2716. raise ValueError(
  2717. f"invalid truncation strategy: {self.truncation_side}, use 'left' or 'right'."
  2718. )
  2719. else:
  2720. error_msg = (
  2721. f"We need to remove {num_tokens_to_remove} to truncate the input "
  2722. f"but the first sequence has a length {len(ids)}. "
  2723. )
  2724. if truncation_strategy == TruncationStrategy.ONLY_FIRST:
  2725. error_msg = (
  2726. error_msg + "Please select another truncation strategy than "
  2727. f"{truncation_strategy}, for instance 'longest_first' or 'only_second'."
  2728. )
  2729. logging.error(error_msg)
  2730. elif truncation_strategy == TruncationStrategy.LONGEST_FIRST:
  2731. warnings.warn(
  2732. f"Be aware, overflowing tokens are not returned for the setting you have chosen,"
  2733. f" i.e. sequence pairs with the '{TruncationStrategy.LONGEST_FIRST.value}' "
  2734. f"truncation strategy. So the returned list will always be empty even if some "
  2735. f"tokens have been removed."
  2736. )
  2737. for _ in range(num_tokens_to_remove):
  2738. if pair_ids is None or len(ids) > len(pair_ids):
  2739. if self.truncation_side == "right":
  2740. ids = ids[:-1]
  2741. elif self.truncation_side == "left":
  2742. ids = ids[1:]
  2743. else:
  2744. raise ValueError(
  2745. "invalid truncation strategy:" + str(self.truncation_side)
  2746. )
  2747. else:
  2748. if self.truncation_side == "right":
  2749. pair_ids = pair_ids[:-1]
  2750. elif self.truncation_side == "left":
  2751. pair_ids = pair_ids[1:]
  2752. else:
  2753. raise ValueError(
  2754. "invalid truncation strategy:" + str(self.truncation_side)
  2755. )
  2756. elif (
  2757. truncation_strategy == TruncationStrategy.ONLY_SECOND
  2758. and pair_ids is not None
  2759. ):
  2760. if len(pair_ids) > num_tokens_to_remove:
  2761. window_len = min(len(pair_ids), stride + num_tokens_to_remove)
  2762. if self.truncation_side == "right":
  2763. overflowing_tokens = pair_ids[-window_len:]
  2764. pair_ids = pair_ids[:-num_tokens_to_remove]
  2765. elif self.truncation_side == "left":
  2766. overflowing_tokens = pair_ids[:window_len]
  2767. pair_ids = pair_ids[num_tokens_to_remove:]
  2768. else:
  2769. raise ValueError(
  2770. "invalid truncation strategy:" + str(self.truncation_side)
  2771. )
  2772. else:
  2773. logging.error(
  2774. f"We need to remove {num_tokens_to_remove} to truncate the input "
  2775. f"but the second sequence has a length {len(pair_ids)}. "
  2776. f"Please select another truncation strategy than {truncation_strategy}, "
  2777. f"for instance 'longest_first' or 'only_first'."
  2778. )
  2779. return (ids, pair_ids, overflowing_tokens)
  2780. def _pad(
  2781. self,
  2782. encoded_inputs: Union[Dict[str, EncodedInput], BatchEncoding],
  2783. max_length: Optional[int] = None,
  2784. padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
  2785. pad_to_multiple_of: Optional[int] = None,
  2786. return_attention_mask: Optional[bool] = None,
  2787. ) -> dict:
  2788. """
  2789. Pad encoded inputs (on left/right and up to predefined length or max length in the batch)
  2790. Args:
  2791. encoded_inputs:
  2792. Dictionary of tokenized inputs (`List[int]`) or batch of tokenized inputs (`List[List[int]]`).
  2793. max_length: maximum length of the returned list and optionally padding length (see below).
  2794. Will truncate by taking into account the special tokens.
  2795. padding_strategy: PaddingStrategy to use for padding.
  2796. - PaddingStrategy.LONGEST Pad to the longest sequence in the batch
  2797. - PaddingStrategy.MAX_LENGTH: Pad to the max length (default)
  2798. - PaddingStrategy.DO_NOT_PAD: Do not pad
  2799. The tokenizer padding sides are defined in self.padding_side:
  2800. - 'left': pads on the left of the sequences
  2801. - 'right': pads on the right of the sequences
  2802. pad_to_multiple_of: (optional) Integer if set will pad the sequence to a multiple of the provided value.
  2803. This is especially useful to enable the use of Tensor Core on NVIDIA hardware with compute capability
  2804. >= 7.5 (Volta).
  2805. return_attention_mask:
  2806. (optional) Set to False to avoid returning attention mask (default: set to model specifics)
  2807. """
  2808. # Load from model defaults
  2809. if return_attention_mask is None:
  2810. return_attention_mask = (
  2811. "attention_mask" in self.model_input_names
  2812. or "attention_mask" in encoded_inputs
  2813. )
  2814. required_input = encoded_inputs[self.model_input_names[0]]
  2815. if padding_strategy == PaddingStrategy.LONGEST:
  2816. max_length = len(required_input)
  2817. if (
  2818. max_length is not None
  2819. and pad_to_multiple_of is not None
  2820. and (max_length % pad_to_multiple_of != 0)
  2821. ):
  2822. max_length = ((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of
  2823. needs_to_be_padded = (
  2824. padding_strategy != PaddingStrategy.DO_NOT_PAD
  2825. and len(required_input) != max_length
  2826. )
  2827. # Initialize attention mask if not present.
  2828. if return_attention_mask and "attention_mask" not in encoded_inputs:
  2829. encoded_inputs["attention_mask"] = [1] * len(required_input)
  2830. if needs_to_be_padded:
  2831. difference = max_length - len(required_input)
  2832. if self.padding_side == "right":
  2833. if return_attention_mask:
  2834. encoded_inputs["attention_mask"] = (
  2835. encoded_inputs["attention_mask"] + [0] * difference
  2836. )
  2837. if "token_type_ids" in encoded_inputs:
  2838. encoded_inputs["token_type_ids"] = (
  2839. encoded_inputs["token_type_ids"]
  2840. + [self.pad_token_type_id] * difference
  2841. )
  2842. if "special_tokens_mask" in encoded_inputs:
  2843. encoded_inputs["special_tokens_mask"] = (
  2844. encoded_inputs["special_tokens_mask"] + [1] * difference
  2845. )
  2846. if "offset_mapping" in encoded_inputs:
  2847. encoded_inputs["offset_mapping"] = (
  2848. encoded_inputs["offset_mapping"] + [(0, 0)] * difference
  2849. )
  2850. if "position_ids" in encoded_inputs:
  2851. encoded_inputs["position_ids"] = (
  2852. encoded_inputs["position_ids"] + [0] * difference
  2853. )
  2854. # NOTE: In ernie3.0-qa, the type of `*_positions` is int.
  2855. if "start_positions" in encoded_inputs and isinstance(
  2856. encoded_inputs["start_positions"], list
  2857. ):
  2858. encoded_inputs["start_positions"] = (
  2859. encoded_inputs["start_positions"] + [0] * difference
  2860. )
  2861. if "end_positions" in encoded_inputs and isinstance(
  2862. encoded_inputs["end_positions"], list
  2863. ):
  2864. encoded_inputs["end_positions"] = (
  2865. encoded_inputs["end_positions"] + [0] * difference
  2866. )
  2867. encoded_inputs[self.model_input_names[0]] = (
  2868. required_input + [self.pad_token_id] * difference
  2869. )
  2870. elif self.padding_side == "left":
  2871. if return_attention_mask:
  2872. encoded_inputs["attention_mask"] = [
  2873. 0
  2874. ] * difference + encoded_inputs["attention_mask"]
  2875. if "token_type_ids" in encoded_inputs:
  2876. encoded_inputs["token_type_ids"] = [
  2877. self.pad_token_type_id
  2878. ] * difference + encoded_inputs["token_type_ids"]
  2879. if "special_tokens_mask" in encoded_inputs:
  2880. encoded_inputs["special_tokens_mask"] = [
  2881. 1
  2882. ] * difference + encoded_inputs["special_tokens_mask"]
  2883. if "offset_mapping" in encoded_inputs:
  2884. encoded_inputs["offset_mapping"] = [
  2885. (0, 0)
  2886. ] * difference + encoded_inputs["offset_mapping"]
  2887. if "position_ids" in encoded_inputs:
  2888. encoded_inputs["position_ids"] = [0] * difference + encoded_inputs[
  2889. "position_ids"
  2890. ]
  2891. if "start_positions" in encoded_inputs and isinstance(
  2892. encoded_inputs["start_positions"], list
  2893. ):
  2894. encoded_inputs["start_positions"] = [
  2895. 0
  2896. ] * difference + encoded_inputs["start_positions"]
  2897. if "end_positions" in encoded_inputs and isinstance(
  2898. encoded_inputs["end_positions"], list
  2899. ):
  2900. encoded_inputs["end_positions"] = [0] * difference + encoded_inputs[
  2901. "end_positions"
  2902. ]
  2903. encoded_inputs[self.model_input_names[0]] = [
  2904. self.pad_token_id
  2905. ] * difference + required_input
  2906. else:
  2907. raise ValueError("Invalid padding strategy:" + str(self.padding_side))
  2908. return encoded_inputs
  2909. def convert_tokens_to_string(self, tokens: List[str]) -> str:
  2910. """
  2911. Converts a sequence of tokens in a single string. The most simple way to do it is `" ".join(tokens)` but we
  2912. often want to remove sub-word tokenization artifacts at the same time.
  2913. Args:
  2914. tokens (`List[str]`): The token to join in a string.
  2915. Returns:
  2916. `str`: The joined tokens.
  2917. """
  2918. raise NotImplementedError
  2919. def batch_decode(
  2920. self,
  2921. sequences: Union[List[int], List[List[int]], "np.ndarray", "paddle.Tensor"],
  2922. skip_special_tokens: bool = False,
  2923. clean_up_tokenization_spaces: bool = True,
  2924. **kwargs,
  2925. ) -> List[str]:
  2926. """
  2927. Convert a list of lists of token ids into a list of strings by calling decode.
  2928. Args:
  2929. sequences (`Union[List[int], List[List[int]], np.ndarray, paddle.Tensor]`):
  2930. List of tokenized input ids. Can be obtained using the `__call__` method.
  2931. skip_special_tokens (`bool`, *optional*, defaults to `False`):
  2932. Whether or not to remove special tokens in the decoding.
  2933. clean_up_tokenization_spaces (`bool`, *optional*, defaults to `True`):
  2934. Whether or not to clean up the tokenization spaces.
  2935. kwargs (additional keyword arguments, *optional*):
  2936. Will be passed to the underlying model specific decode method.
  2937. Returns:
  2938. `List[str]`: The list of decoded sentences.
  2939. """
  2940. return [
  2941. self.decode(
  2942. seq,
  2943. skip_special_tokens=skip_special_tokens,
  2944. clean_up_tokenization_spaces=clean_up_tokenization_spaces,
  2945. **kwargs,
  2946. )
  2947. for seq in sequences
  2948. ]
  2949. def decode(
  2950. self,
  2951. token_ids: Union[int, List[int], "np.ndarray", "paddle.Tensor"],
  2952. skip_special_tokens: bool = False,
  2953. clean_up_tokenization_spaces: bool = True,
  2954. **kwargs,
  2955. ) -> str:
  2956. """
  2957. Converts a sequence of ids in a string, using the tokenizer and vocabulary with options to remove special
  2958. tokens and clean up tokenization spaces.
  2959. Similar to doing `self.convert_tokens_to_string(self.convert_ids_to_tokens(token_ids))`.
  2960. Args:
  2961. token_ids (`Union[int, List[int], np.ndarray, paddle.Tensor]`):
  2962. List of tokenized input ids. Can be obtained using the `__call__` method.
  2963. skip_special_tokens (`bool`, *optional*, defaults to `False`):
  2964. Whether or not to remove special tokens in the decoding.
  2965. clean_up_tokenization_spaces (`bool`, *optional*, defaults to `True`):
  2966. Whether or not to clean up the tokenization spaces.
  2967. kwargs (additional keyword arguments, *optional*):
  2968. Will be passed to the underlying model specific decode method.
  2969. Returns:
  2970. `str`: The decoded sentence.
  2971. """
  2972. # Convert inputs to python lists
  2973. token_ids = to_py_obj(token_ids)
  2974. return self._decode(
  2975. token_ids=token_ids,
  2976. skip_special_tokens=skip_special_tokens,
  2977. clean_up_tokenization_spaces=clean_up_tokenization_spaces,
  2978. **kwargs,
  2979. )
  2980. def _decode(
  2981. self,
  2982. token_ids: Union[int, List[int]],
  2983. skip_special_tokens: bool = False,
  2984. clean_up_tokenization_spaces: bool = True,
  2985. **kwargs,
  2986. ) -> str:
  2987. raise NotImplementedError
  2988. def get_special_tokens_mask(
  2989. self,
  2990. token_ids_0: List[int],
  2991. token_ids_1: Optional[List[int]] = None,
  2992. already_has_special_tokens: bool = False,
  2993. ) -> List[int]:
  2994. """
  2995. Retrieves sequence ids from a token list that has no special tokens added. This method is called when adding
  2996. special tokens using the tokenizer `prepare_for_model` or `encode_plus` methods.
  2997. Args:
  2998. token_ids_0 (`List[int]`):
  2999. List of ids of the first sequence.
  3000. token_ids_1 (`List[int]`, *optional*):
  3001. List of ids of the second sequence.
  3002. already_has_special_tokens (`bool`, *optional*, defaults to `False`):
  3003. Whether or not the token list is already formatted with special tokens for the model.
  3004. Returns:
  3005. A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
  3006. """
  3007. assert already_has_special_tokens and token_ids_1 is None, (
  3008. "You cannot use ``already_has_special_tokens=False`` with this tokenizer. "
  3009. "Please use a slow (full python) tokenizer to activate this argument. "
  3010. "Or set `return_special_tokens_mask=True` when calling the encoding method "
  3011. "to get the special tokens mask in any tokenizer. "
  3012. )
  3013. all_special_ids = self.all_special_ids # cache the property
  3014. special_tokens_mask = [
  3015. 1 if token in all_special_ids else 0 for token in token_ids_0
  3016. ]
  3017. return special_tokens_mask
  3018. @staticmethod
  3019. def clean_up_tokenization(out_string: str) -> str:
  3020. """
  3021. Clean up a list of simple English tokenization artifacts like spaces before punctuations and abbreviated forms.
  3022. Args:
  3023. out_string (`str`): The text to clean up.
  3024. Returns:
  3025. `str`: The cleaned-up string.
  3026. """
  3027. out_string = (
  3028. out_string.replace(" .", ".")
  3029. .replace(" ?", "?")
  3030. .replace(" !", "!")
  3031. .replace(" ,", ",")
  3032. .replace(" ' ", "'")
  3033. .replace(" n't", "n't")
  3034. .replace(" 'm", "'m")
  3035. .replace(" 's", "'s")
  3036. .replace(" 've", "'ve")
  3037. .replace(" 're", "'re")
  3038. )
  3039. return out_string
  3040. def _eventual_warn_about_too_long_sequence(
  3041. self, ids: List[int], max_length: Optional[int], verbose: bool
  3042. ):
  3043. """
  3044. Depending on the input and internal state we might trigger a warning about a sequence that is too long for its
  3045. corresponding model
  3046. Args:
  3047. ids (`List[str]`): The ids produced by the tokenization
  3048. max_length (`int`, *optional*): The max_length desired (does not trigger a warning if it is set)
  3049. verbose (`bool`): Whether or not to print more information and warnings.
  3050. """
  3051. if max_length is None and len(ids) > self.model_max_length and verbose:
  3052. if not self.deprecation_warnings.get(
  3053. "sequence-length-is-longer-than-the-specified-maximum", False
  3054. ):
  3055. logging.warning(
  3056. "Token indices sequence length is longer than the specified maximum sequence length "
  3057. f"for this model ({len(ids)} > {self.model_max_length}). Running this sequence through the model "
  3058. "will result in indexing errors"
  3059. )
  3060. self.deprecation_warnings[
  3061. "sequence-length-is-longer-than-the-specified-maximum"
  3062. ] = True