tokenizer_utils_base.py 151 KB

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