tokenizer_utils_base.py 160 KB

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