tokenizer_utils.py 83 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144
  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 bisect
  15. import functools
  16. import inspect
  17. import io
  18. import itertools
  19. import json
  20. import os
  21. import re
  22. import unicodedata
  23. from collections import OrderedDict
  24. from dataclasses import asdict, dataclass
  25. from functools import lru_cache
  26. from typing import Any, Dict, List, Optional, Tuple, Union
  27. import numpy as np
  28. from .....utils import logging
  29. from .....utils.deps import class_requires_deps, is_dep_available
  30. from .tokenizer_utils_base import (
  31. CHAT_TEMPLATE_CONFIG_NAME,
  32. AddedToken,
  33. BatchEncoding,
  34. EncodedInput,
  35. EncodedInputPair,
  36. PaddingStrategy,
  37. PreTokenizedInput,
  38. PreTokenizedInputPair,
  39. PretrainedTokenizerBase,
  40. TensorType,
  41. TextInput,
  42. TextInputPair,
  43. TruncationStrategy,
  44. )
  45. from .utils import convert_to_dict_message, fn_args_to_dict
  46. from .vocab import Vocab
  47. if is_dep_available("Jinja2"):
  48. from jinja2 import Template
  49. from jinja2.exceptions import TemplateError, TemplateSyntaxError
  50. from jinja2.sandbox import ImmutableSandboxedEnvironment
  51. __all__ = [
  52. "ChatTemplate",
  53. "Trie",
  54. "ChatTemplateMixin",
  55. "PretrainedTokenizer",
  56. "InitTrackerMeta",
  57. ]
  58. @class_requires_deps("Jinja2")
  59. @dataclass
  60. class ChatTemplate:
  61. conversation: Union[List[str], None] = None
  62. system: Union[str, None] = None
  63. query: str = None
  64. @staticmethod
  65. @lru_cache()
  66. def _compile_jinja_template(chat_template) -> "Template":
  67. def raise_exception(message):
  68. raise TemplateError(message)
  69. jinja_env = ImmutableSandboxedEnvironment(
  70. trim_blocks=True, lstrip_blocks=True, keep_trailing_newline=True
  71. )
  72. jinja_env.globals["raise_exception"] = raise_exception
  73. return jinja_env.from_string(chat_template)
  74. def render_conversation(
  75. self,
  76. conversation_data: Union[List[str], Dict[str, str]],
  77. index: int = 0,
  78. context_data: Dict[str, Any] = {},
  79. ) -> List[str]:
  80. """
  81. Args:
  82. conversation_data (list[str]): the conversation data which must be two parts
  83. index (int): the index of current conversation
  84. Returns:
  85. list[str]: the rendered conversation data
  86. """
  87. if self.conversation is None:
  88. raise ValueError(
  89. "The template for multi-turns is invalid, please check `conversation` filed in your chat-template."
  90. )
  91. if isinstance(conversation_data, (list, tuple)):
  92. assert (
  93. len(conversation_data) == 2
  94. ), "Each round/turn of conversation must be two participants, eg: [user-query, bot-query]"
  95. conversation_data = {
  96. "user": conversation_data[0],
  97. "bot": conversation_data[1],
  98. "index": index,
  99. }
  100. conversation_data.update(context_data)
  101. one_turn_conversation = []
  102. for conversation in self.conversation:
  103. template = self._compile_jinja_template(conversation)
  104. result = template.render(conversation_data)
  105. one_turn_conversation.append(result)
  106. return one_turn_conversation
  107. def render_query(
  108. self, query: str, index: int = 0, context_data: Dict[str, Union[int, str]] = {}
  109. ):
  110. if self.query is None:
  111. return query
  112. template = self._compile_jinja_template(self.query)
  113. return template.render(query=query, index=index, **context_data)
  114. def _init_context_data(
  115. self, context_data: Dict[str, Union[int, str]] = {}
  116. ) -> Dict[str, Union[int, str]]:
  117. """init the context data for chat-template"""
  118. context_data["is_training"] = context_data.get("is_training", False)
  119. return context_data
  120. def render_system(self, context_data: Dict[str, Union[int, str]] = {}) -> str:
  121. if self.system is None:
  122. return ""
  123. template = self._compile_jinja_template(self.system)
  124. return template.render(**context_data)
  125. def __call__(
  126. self,
  127. conversations: Union[List[List[str]], str],
  128. context_data: Dict[str, Union[int, str]] = {},
  129. ) -> str:
  130. """render the conversations by chat-template
  131. Args:
  132. conversations (list[list[str]]): the conversations of use and bot
  133. Returns:
  134. str: the result of conversation
  135. """
  136. if isinstance(conversations, str):
  137. conversations = [[conversations]]
  138. # [1 ... n-1] conversation
  139. final_query = self.render_system(context_data=context_data)
  140. context_data["length"] = len(conversations)
  141. for index, conversation in enumerate(conversations[:-1]):
  142. context_data["is_first"] = index == 0
  143. context_data["is_last"] = False
  144. final_query += "".join(
  145. self.render_conversation(
  146. conversation, index=index, context_data=context_data
  147. )
  148. )
  149. if not isinstance(conversations[-1], list) and not len(conversations[-1]) != 1:
  150. raise ValueError(
  151. "The length of last conversation must be one, eg: [[user-query, bot-answer], [user-query, bot-answer], ..., [user-query]]"
  152. )
  153. if len(conversations[-1]) > 1:
  154. logging.warning(
  155. f"The last conversation is not a single-round, chat-template will skip the conversation: {conversations[-1][1:]}"
  156. )
  157. final_query += self.render_query(
  158. conversations[-1][0],
  159. index=len(conversations) - 1,
  160. context_data=context_data,
  161. )
  162. return final_query
  163. @classmethod
  164. def from_dict(cls, config: Dict):
  165. return cls(**config)
  166. @classmethod
  167. def from_file(cls, file: str):
  168. with open(file, "r", encoding="utf-8") as f:
  169. config = json.load(f)
  170. return cls.from_dict(config)
  171. def adapt_stale_fwd_patch(self, name, value):
  172. """
  173. Since there are some monkey patches for forward of PretrainedModel, such as
  174. model compression, we make these patches compatible with the latest forward
  175. method.
  176. """
  177. if name == "forward":
  178. # NOTE(guosheng): In dygraph to static, `layer.forward` would be patched
  179. # by an instance of `StaticFunction`. And use string compare to avoid to
  180. # import fluid.
  181. if type(value).__name__.endswith(
  182. "StaticFunction"
  183. ) or self.forward.__class__.__name__.endswith("StaticFunction"):
  184. return value
  185. (
  186. patch_spec_args,
  187. patch_spec_varargs,
  188. patch_spec_varkw,
  189. patch_spec_defaults,
  190. _,
  191. _,
  192. _,
  193. ) = inspect.getfullargspec(value)
  194. (spec_args, spec_varargs, spec_varkw, spec_defaults, _, _, _) = (
  195. inspect.getfullargspec(self.forward)
  196. )
  197. new_args = [
  198. arg
  199. for arg in ("output_hidden_states", "output_attentions", "return_dict")
  200. if arg not in patch_spec_args and arg in spec_args
  201. ]
  202. if new_args:
  203. import paddle
  204. if self.__module__.startswith("paddlenlp"):
  205. logging.warning(
  206. f"The `forward` method of {self.__class__ if isinstance(self, paddle.nn.Layer) else self} is patched and the patch "
  207. "might be based on an old oversion which missing some "
  208. f"arguments compared with the latest, such as {new_args}. "
  209. "We automatically add compatibility on the patch for "
  210. "these arguemnts, and maybe the patch should be updated."
  211. )
  212. else:
  213. logging.warning(
  214. f"The `forward` method of {self.__class__ if isinstance(self, paddle.nn.Layer) else self} "
  215. "is patched and the patch might be conflict with patches made "
  216. f"by paddlenlp which seems have more arguments such as {new_args}. "
  217. "We automatically add compatibility on the patch for "
  218. "these arguemnts, and maybe the patch should be updated."
  219. )
  220. if isinstance(self, paddle.nn.Layer) and inspect.isfunction(value):
  221. @functools.wraps(value)
  222. def wrap_fwd(*args, **kwargs):
  223. for arg in new_args:
  224. kwargs.pop(arg, None)
  225. return value(self, *args, **kwargs)
  226. else:
  227. @functools.wraps(value)
  228. def wrap_fwd(*args, **kwargs):
  229. for arg in new_args:
  230. kwargs.pop(arg, None)
  231. return value(*args, **kwargs)
  232. return wrap_fwd
  233. return value
  234. # NOTE:
  235. # Modification:
  236. # class InitTrackerMeta(type(paddle.nn.Layer)) -> class InitTrackerMeta(type)
  237. # Context:
  238. # 1. In paddle 3.0rc, type(paddle.nn.Layer) == type
  239. # 2. Solve the conflict between ultra-infer and paddle
  240. class InitTrackerMeta(type):
  241. """
  242. This metaclass wraps the `__init__` method of a class to add `init_config`
  243. attribute for instances of that class, and `init_config` use a dict to track
  244. the initial configuration. If the class has `_pre_init` or `_post_init`
  245. method, it would be hooked before or after `__init__` and called as
  246. `_pre_init(self, init_fn, init_args)` or `_post_init(self, init_fn, init_args)`.
  247. Since InitTrackerMeta would be used as metaclass for pretrained model classes,
  248. which always are Layer and `type(Layer)` is not `type`, thus use `type(Layer)`
  249. rather than `type` as base class for it to avoid inheritance metaclass
  250. conflicts.
  251. """
  252. def __init__(cls, name, bases, attrs):
  253. init_func = cls.__init__
  254. # If attrs has `__init__`, wrap it using accessable `_pre_init, _post_init`.
  255. # Otherwise, no need to wrap again since the super cls has been wraped.
  256. # TODO: remove reduplicated tracker if using super cls `__init__`
  257. pre_init_func = getattr(cls, "_pre_init", None) if "__init__" in attrs else None
  258. post_init_func = (
  259. getattr(cls, "_post_init", None) if "__init__" in attrs else None
  260. )
  261. cls.__init__ = InitTrackerMeta.init_and_track_conf(
  262. init_func, pre_init_func, post_init_func
  263. )
  264. super(InitTrackerMeta, cls).__init__(name, bases, attrs)
  265. @staticmethod
  266. def init_and_track_conf(init_func, pre_init_func=None, post_init_func=None):
  267. """
  268. wraps `init_func` which is `__init__` method of a class to add `init_config`
  269. attribute for instances of that class.
  270. Args:
  271. init_func (callable): It should be the `__init__` method of a class.
  272. warning: `self` always is the class type of down-stream model, eg: BertForTokenClassification
  273. pre_init_func (callable, optional): If provided, it would be hooked after
  274. `init_func` and called as `pre_init_func(self, init_func, *init_args, **init_args)`.
  275. Default None.
  276. post_init_func (callable, optional): If provided, it would be hooked after
  277. `init_func` and called as `post_init_func(self, init_func, *init_args, **init_args)`.
  278. Default None.
  279. Returns:
  280. function: the wrapped function
  281. """
  282. @functools.wraps(init_func)
  283. def __impl__(self, *args, **kwargs):
  284. # registed helper by `pre_init_func`
  285. if pre_init_func:
  286. pre_init_func(self, init_func, *args, **kwargs)
  287. # keep full configuration
  288. init_func(self, *args, **kwargs)
  289. # registed helper by `post_init_func`
  290. if post_init_func:
  291. post_init_func(self, init_func, *args, **kwargs)
  292. self.init_config = kwargs
  293. if args:
  294. kwargs["init_args"] = args
  295. kwargs["init_class"] = self.__class__.__name__
  296. return __impl__
  297. def __setattr__(self, name, value):
  298. value = adapt_stale_fwd_patch(self, name, value)
  299. return super(InitTrackerMeta, self).__setattr__(name, value)
  300. class Trie:
  301. """
  302. Trie in Python. Creates a Trie out of a list of words. The trie is used to split on `added_tokens` in one pass
  303. Loose reference https://en.wikipedia.org/wiki/Trie
  304. """
  305. def __init__(self):
  306. self.data = {}
  307. def add(self, word: str):
  308. """
  309. Passes over every char (utf-8 char) on word and recursively adds it to the internal `data` trie representation.
  310. The special key `""` is used to represent termination.
  311. This function is idempotent, adding twice the same word will leave the trie unchanged
  312. Example:
  313. ```python
  314. >>> trie = Trie()
  315. >>> trie.add("Hello 友達")
  316. >>> trie.data
  317. {"H": {"e": {"l": {"l": {"o": {" ": {"友": {"達": {"": 1}}}}}}}}}
  318. >>> trie.add("Hello")
  319. >>> trie.data
  320. {"H": {"e": {"l": {"l": {"o": {"": 1, " ": {"友": {"達": {"": 1}}}}}}}}}
  321. ```
  322. """
  323. if not word:
  324. # Prevent empty string
  325. return
  326. ref = self.data
  327. for char in word:
  328. ref[char] = char in ref and ref[char] or {}
  329. ref = ref[char]
  330. ref[""] = 1
  331. def split(self, text: str) -> List[str]:
  332. """
  333. Will look for the words added to the trie within `text`. Output is the original string splitted along the
  334. boundaries of the words found.
  335. This trie will match the longest possible word first !
  336. Example:
  337. ```python
  338. >>> trie = Trie()
  339. >>> trie.split("[CLS] This is a extra_id_100")
  340. ["[CLS] This is a extra_id_100"]
  341. >>> trie.add("[CLS]")
  342. >>> trie.add("extra_id_1")
  343. >>> trie.add("extra_id_100")
  344. >>> trie.split("[CLS] This is a extra_id_100")
  345. ["[CLS]", " This is a ", "extra_id_100"]
  346. ```
  347. """
  348. # indexes are counted left of the chars index.
  349. # "hello", index 0, is left of h, index 1 is between h and e.
  350. # index 5 is right of the "o".
  351. # States are going to capture every possible start (indexes as above)
  352. # as keys, and have as values, a pointer to the position in the trie
  353. # where we're at. This is a partial match for now.
  354. # This enables to keep track of multiple matches while we're iterating
  355. # the string
  356. # If the trie contains, "blowing", and "lower" and we encounter the
  357. # string "blower", we need to split into ["b", "lower"].
  358. # This is where we need to keep track of multiple possible starts.
  359. states = OrderedDict()
  360. # This will contain every indices where we need
  361. # to cut.
  362. # We force to cut at offset 0 and len(text) (added later)
  363. offsets = [0]
  364. # This is used by the lookahead which needs to skip over
  365. # some text where the full match exceeded the place in the initial
  366. # for loop
  367. skip = 0
  368. # Main loop, Giving this algorithm O(n) complexity
  369. for current, current_char in enumerate(text):
  370. if skip and current < skip:
  371. # Prevents the lookahead for matching twice
  372. # like extra_id_100 and id_100
  373. continue
  374. # This will track every state
  375. # that stop matching, we need to stop tracking them.
  376. # If we look at "lowball", we're going to match "l" (add it to states), "o", "w", then
  377. # fail on "b", we need to remove 0 from the valid states.
  378. to_remove = set()
  379. # Whenever we found a match, we need to drop everything
  380. # this is a greedy algorithm, it will match on the first found token
  381. reset = False
  382. # In this case, we already have partial matches (But unfinished)
  383. for start, trie_pointer in states.items():
  384. if "" in trie_pointer:
  385. # This is a final match, we need to reset and
  386. # store the results in `offsets`.
  387. # Lookahead to match longest first
  388. # Important in case of extra_id_1 vs extra_id_100
  389. # Here we are also actively looking for other earlier partial
  390. # matches
  391. # "[CLS]", "L", we need to match CLS even if L is special
  392. for lookstart, looktrie_pointer in states.items():
  393. if lookstart > start:
  394. # This partial match is later, we can stop looking
  395. break
  396. elif lookstart < start:
  397. # This partial match is earlier, the trie pointer
  398. # was already updated, so index is + 1
  399. lookahead_index = current + 1
  400. end = current + 1
  401. else:
  402. # Here lookstart == start and
  403. # looktrie_pointer == trie_pointer
  404. # It wasn't updated yet so indices are current ones
  405. lookahead_index = current
  406. end = current
  407. next_char = (
  408. text[lookahead_index]
  409. if lookahead_index < len(text)
  410. else None
  411. )
  412. if "" in looktrie_pointer:
  413. start = lookstart
  414. end = lookahead_index
  415. skip = lookahead_index
  416. while next_char in looktrie_pointer:
  417. looktrie_pointer = looktrie_pointer[next_char]
  418. lookahead_index += 1
  419. if "" in looktrie_pointer:
  420. start = lookstart
  421. end = lookahead_index
  422. skip = lookahead_index
  423. if lookahead_index == len(text):
  424. # End of string
  425. break
  426. next_char = text[lookahead_index]
  427. # End lookahead
  428. # Storing and resetting
  429. offsets.append(start)
  430. offsets.append(end)
  431. reset = True
  432. break
  433. elif current_char in trie_pointer:
  434. # The current character being looked at has a match within the trie
  435. # update the pointer (it will be stored back into states later).
  436. trie_pointer = trie_pointer[current_char]
  437. # Storing back the new pointer into the states.
  438. # Partial matches got longer by one.
  439. states[start] = trie_pointer
  440. else:
  441. # The new character has not match in the trie, we need
  442. # to stop keeping track of this partial match.
  443. # We can't do it directly within the loop because of how
  444. # python iteration works
  445. to_remove.add(start)
  446. # Either clearing the full start (we found a real match)
  447. # Or clearing only the partial matches that didn't work.
  448. if reset:
  449. states = {}
  450. else:
  451. for start in to_remove:
  452. del states[start]
  453. # If this character is a starting character within the trie
  454. # start keeping track of this partial match.
  455. if current >= skip and current_char in self.data:
  456. states[current] = self.data[current_char]
  457. # We have a cut at the end with states.
  458. for start, trie_pointer in states.items():
  459. if "" in trie_pointer:
  460. # This is a final match, we need to reset and
  461. # store the results in `offsets`.
  462. end = len(text)
  463. offsets.append(start)
  464. offsets.append(end)
  465. # Longest cut is always the one with lower start so the first
  466. # item so we need to break.
  467. break
  468. return self.cut_text(text, offsets)
  469. def cut_text(self, text, offsets):
  470. # We have all the offsets now, we just need to do the actual splitting.
  471. # We need to eventually add the first part of the string and the eventual
  472. # last part.
  473. offsets.append(len(text))
  474. tokens = []
  475. start = 0
  476. for end in offsets:
  477. if start > end:
  478. logging.error(
  479. "There was a bug in Trie algorithm in tokenization. Attempting to recover. Please report it anyway."
  480. )
  481. continue
  482. elif start == end:
  483. # This might happen if there's a match at index 0
  484. # we're also preventing zero-width cuts in case of two
  485. # consecutive matches
  486. continue
  487. tokens.append(text[start:end])
  488. start = end
  489. return tokens
  490. def _insert_one_token_to_ordered_list(token_list: List[str], new_token: str):
  491. """
  492. Inserts one token to an ordered list if it does not already exist. Note: token_list must be sorted.
  493. """
  494. insertion_idx = bisect.bisect_left(token_list, new_token)
  495. # Checks if new_token is already in the ordered token_list
  496. if insertion_idx < len(token_list) and token_list[insertion_idx] == new_token:
  497. # new_token is in token_list, don't add
  498. return
  499. else:
  500. token_list.insert(insertion_idx, new_token)
  501. def _is_control(char):
  502. """Checks whether `chars` is a control character."""
  503. # These are technically control characters but we count them as whitespace
  504. # characters.
  505. if char == "\t" or char == "\n" or char == "\r":
  506. return False
  507. cat = unicodedata.category(char)
  508. if cat.startswith("C"):
  509. return True
  510. return False
  511. def _is_nonnormalized_char(char):
  512. """Check whther `chars` is a non-normalized character."""
  513. cp = ord(char)
  514. if (
  515. (0xFF00 <= cp <= 0xFFEF)
  516. or (0xFE50 <= cp <= 0xFE6B) # Halfwidth and Fullwidth Forms
  517. or (0x3358 <= cp <= 0x33FF) # Small Form Variants
  518. or (0x249C <= cp <= 0x24E9) # CJK Compatibility
  519. or (0x3200 <= cp <= 0x32FF) # Enclosed Alphanumerics: Ⓛ ⒰
  520. ): # Enclosed CJK Letters and Months
  521. return True
  522. return False
  523. def _is_nonnormalized_numeric(char):
  524. """Check whether `chars` is a non-normalized numeric character."""
  525. cp = ord(char)
  526. if (
  527. (0x2460 <= cp <= 0x249B)
  528. or (0x24EA <= cp <= 0x24FF) #
  529. or (0x2776 <= cp <= 0x2793) #
  530. or (0x2160 <= cp <= 0x217F) # Enclosed Alphanumerics
  531. ): # Number Forms
  532. return True
  533. return False
  534. def normalize_chars(text):
  535. """
  536. Normalize the text for multiligual and chinese models. Unicode range:
  537. https://www.ling.upenn.edu/courses/Spring_2003/ling538/UnicodeRanges.html
  538. """
  539. output = []
  540. for char in text:
  541. if _is_nonnormalized_char(char):
  542. for c in unicodedata.normalize("NFKC", char):
  543. output.append(c)
  544. elif _is_nonnormalized_numeric(char):
  545. output.append(" ")
  546. for c in str(int(unicodedata.numeric(char))):
  547. output.append(c)
  548. output.append(" ")
  549. elif ord(char) == 0xF979: # https://www.zhihu.com/question/20697984
  550. output.append("凉")
  551. else:
  552. output.append(char)
  553. return "".join(output)
  554. class ChatTemplateMixin:
  555. chat_template: Optional[ChatTemplate] = None
  556. def apply_chat_template(
  557. self,
  558. conversation: Union[Dict[str, str], str],
  559. tokenize: bool = True,
  560. context_data: Dict[str, Any] = {},
  561. **tokenizer_kwargs,
  562. ):
  563. """apply chat_template rules to conversation which should not be batched data
  564. Args:
  565. conversation (List[List[str, str]] | str): the conversation messages between user and bot
  566. context_data (Dict[str, Any]): the context data for chat_template.json
  567. tokenize (bool, optional): whether do tokenization. Defaults to True.
  568. Returns:
  569. str | dict[str, Union[numpy.ndarray, paddle.Tensor]]: return the result of applied data
  570. """
  571. if not self.chat_template:
  572. raise ValueError(
  573. "chat_template is not set, please set chat_template first."
  574. )
  575. elif isinstance(self.chat_template, Template):
  576. add_generation_prompt = tokenizer_kwargs.pop("add_generation_prompt", True)
  577. query = self._apply_chat_template(
  578. conversation, add_generation_prompt=add_generation_prompt
  579. )
  580. elif isinstance(self.chat_template, ChatTemplate):
  581. query = self._apply_chat_template_paddle(conversation, context_data)
  582. if not tokenize:
  583. return query
  584. # chat_template should not add special tokens
  585. tokenizer_kwargs["add_special_tokens"] = False
  586. return self(query, **tokenizer_kwargs)
  587. def _apply_chat_template_paddle(
  588. self,
  589. conversation: Union[List[Dict[str, str]], str],
  590. context_data: Dict[str, Any] = {},
  591. ):
  592. context_data = self.chat_template._init_context_data(context_data)
  593. if isinstance(conversation, str):
  594. conversation = [[conversation]]
  595. elif isinstance(conversation, list) and isinstance(conversation[0], str):
  596. raise ValueError(
  597. "apply_chat_template do not support appling batch conversations, "
  598. "so you should apply the conversation one by one."
  599. )
  600. query = self.chat_template(conversation, context_data=context_data)
  601. return query
  602. def _apply_chat_template(
  603. self,
  604. conversation: Union[Dict[str, str], str],
  605. add_generation_prompt=True,
  606. ):
  607. if isinstance(conversation, str):
  608. conversations = [{"role": "user", "content": conversation}]
  609. elif isinstance(conversation, list):
  610. assert len(conversation) > 0, "empty conversation is not allowed"
  611. if isinstance(conversation[0], list):
  612. conversations = convert_to_dict_message(conversation)
  613. elif isinstance(conversation[0], dict):
  614. conversations = conversation
  615. else:
  616. raise ValueError(
  617. "apply_chat_template do not support appling batch conversations, "
  618. "so you should apply the conversation one by one."
  619. )
  620. query = self.chat_template.render(
  621. messages=conversations,
  622. **self.special_tokens_map,
  623. add_generation_prompt=add_generation_prompt,
  624. )
  625. return query
  626. def encode_chat_inputs(
  627. self,
  628. conversations: List[Dict[str, str]],
  629. context_data: Dict[str, Any] = {},
  630. **kwargs,
  631. ):
  632. """Encodes conversation to pairs of token ids.
  633. Turn 0: bos + system + sep + user bot + eos
  634. Turn t: sep + bot + query bot + eos
  635. Args:
  636. conversation (List[Dict[str, str]]): the conversation of data
  637. context_data (Dict[str, Any]): the context data of conversation
  638. Returns:
  639. List[list[int], list[int]]: the pair of input_ids and target_ids
  640. """
  641. if not self.chat_template:
  642. raise ValueError(
  643. "chat_template is not set, please set chat_template first."
  644. )
  645. elif isinstance(self.chat_template, Template):
  646. add_generation_prompt = kwargs.pop("add_generation_prompt", True)
  647. query = self._encode_chat_inputs(
  648. conversations, context_data, add_generation_prompt=add_generation_prompt
  649. )
  650. elif isinstance(self.chat_template, ChatTemplate):
  651. query = self._encode_chat_inputs_paddle(conversations, context_data)
  652. return query
  653. def _encode_chat_inputs_paddle(
  654. self, conversations: List[Dict[str, str]], context_data: Dict[str, Any] = {}
  655. ):
  656. context_data = self.chat_template._init_context_data(context_data)
  657. # encode system
  658. result = {}
  659. if self.chat_template.system:
  660. system = self.chat_template.render_system(context_data)
  661. result["system"] = self.encode(system, add_special_tokens=False)[
  662. "input_ids"
  663. ]
  664. # encode conversation
  665. conversation_ids = []
  666. for index, conversation in enumerate(conversations):
  667. # give more control to chat_template
  668. context_data["is_first"] = index == 0
  669. context_data["is_last"] = index == len(conversations) - 1
  670. user_input, bot_output = self.chat_template.render_conversation(
  671. conversation, index=index, context_data=context_data
  672. )
  673. user_ids = self.encode(user_input, add_special_tokens=False)["input_ids"]
  674. bot_ids = self.encode(bot_output, add_special_tokens=False)["input_ids"]
  675. conversation_ids.append([user_ids, bot_ids])
  676. result["conversations"] = conversation_ids
  677. return result
  678. def _encode_chat_inputs(
  679. self,
  680. conversations: List[Dict[str, str]],
  681. context_data: Dict[str, Any] = {},
  682. system: str = None,
  683. add_generation_prompt=True,
  684. ):
  685. result = {}
  686. # Some template do not support system msg, so we need to check it first.
  687. if system:
  688. try:
  689. self.chat_template.render(
  690. messages={"role": "system", "content": system}
  691. )
  692. except Exception as e:
  693. raise ValueError("System is not supported in this tokenizer.", e)
  694. # convert list msg to role dict msg
  695. conversation_dict = []
  696. origin_msg = []
  697. for round in conversations:
  698. round_role = [
  699. {"role": "user", "content": round[0]},
  700. {"role": "assistant", "content": round[1]},
  701. ]
  702. origin_msg.extend(round_role)
  703. conversation_dict.append(round_role)
  704. ans = []
  705. # get answer in single round, then compile the chat entirely and split by single round ans
  706. # attention: answer should include end token!
  707. for conv in conversation_dict:
  708. roundi = [system] + conv if system else conv
  709. roundi_str = self.chat_template.render(
  710. messages=roundi, add_generation_prompt=False, **self.special_tokens_map
  711. )
  712. roundi_no_ans = [system] + [conv[0]] if system else [conv[0]]
  713. roundi_no_ans_str = self.chat_template.render(
  714. messages=roundi_no_ans,
  715. add_generation_prompt=add_generation_prompt,
  716. **self.special_tokens_map,
  717. )
  718. ans_roundi = roundi_str[len(roundi_no_ans_str) :]
  719. ans.append(ans_roundi)
  720. non_learnable_parts = self._extract_non_learnable_parts(origin_msg, ans)
  721. assert len(non_learnable_parts) == len(ans)
  722. conversation_ids = []
  723. for i in range(len(non_learnable_parts)):
  724. conversation_ids.append(
  725. self.batch_encode(
  726. [non_learnable_parts[i], ans[i]],
  727. add_special_tokens=False,
  728. padding=False,
  729. )["input_ids"]
  730. )
  731. result["conversations"] = conversation_ids
  732. return result
  733. def _extract_non_learnable_parts(
  734. self, origin_msg: List[Dict[str, str]], split_s: List[str]
  735. ):
  736. """Split the entire chat by specified words. Extract the non-learnable parts."""
  737. # distingish and replace the special words in original string to an uncompiled form: Like | -> \|
  738. regex_pattern = "|".join(map(re.escape, split_s))
  739. # splited by replaced specified words
  740. non_learnable_parts = re.split(
  741. r"(?:%s)" % regex_pattern,
  742. self.chat_template.render(
  743. messages=origin_msg,
  744. add_generation_prompt=False,
  745. **self.special_tokens_map,
  746. ),
  747. )
  748. if non_learnable_parts[-1] == "":
  749. non_learnable_parts.pop()
  750. return non_learnable_parts
  751. @classmethod
  752. def from_pretrained(cls, pretrained_model_name_or_path, *args, **kwargs):
  753. cache_dir = kwargs.pop("cache_dir", None)
  754. from_hf_hub = kwargs.pop("from_hf_hub", False)
  755. from_aistudio = kwargs.pop("from_aistudio", False)
  756. subfolder = kwargs.pop("subfolder", "")
  757. if subfolder is None:
  758. subfolder = ""
  759. kwargs["subfolder"] = subfolder
  760. kwargs["cache_dir"] = cache_dir
  761. kwargs["from_hf_hub"] = from_hf_hub
  762. kwargs["from_aistudio"] = from_aistudio
  763. kwargs["return_tokenizer_file_dir"] = True
  764. tokenizer, tokenizer_config_file_dir = super().from_pretrained(
  765. pretrained_model_name_or_path, *args, **kwargs
  766. )
  767. # load chat-template
  768. chat_template_file = os.path.join(
  769. tokenizer_config_file_dir, CHAT_TEMPLATE_CONFIG_NAME
  770. )
  771. if not os.path.exists(chat_template_file):
  772. return tokenizer
  773. if tokenizer.chat_template is not None:
  774. logging.warning(
  775. "Chat-template already exists in config file, it will be overwritten by chat_template.json file."
  776. )
  777. logging.warning(
  778. "`chat_template.json` will be deprecated in the future! Please set it in `tokenizer_config.json`."
  779. )
  780. tokenizer.init_chat_template(chat_template_file)
  781. return tokenizer
  782. def init_chat_template(self, chat_template: Union[str, Dict]):
  783. """init chat_tempalte by file_path or template dict data
  784. Args:
  785. chat_template (str | dict): file_path or template dict data
  786. """
  787. if isinstance(chat_template, str):
  788. if not os.path.exists(chat_template):
  789. try:
  790. self.chat_template: Template = ChatTemplate._compile_jinja_template(
  791. chat_template
  792. )
  793. except TemplateSyntaxError:
  794. # It is neither jinjia string nor path string
  795. raise TemplateSyntaxError(
  796. "The chat-template in json is not valid jinja string: {}".format(
  797. chat_template
  798. ),
  799. lineno=0, # fake lineno, useless required msg
  800. )
  801. else:
  802. self.chat_template = ChatTemplate.from_file(chat_template)
  803. elif isinstance(chat_template, dict):
  804. self.chat_template = ChatTemplate.from_dict(chat_template)
  805. elif isinstance(chat_template, ChatTemplate):
  806. self.chat_template = chat_template
  807. else:
  808. raise ValueError("Receive error chat_template data: ", chat_template)
  809. def save_resources(self, save_directory):
  810. super().save_resources(save_directory)
  811. if isinstance(
  812. self.chat_template, ChatTemplate
  813. ): # Future remove if ChatTemplate is deprecated
  814. chat_template_file = os.path.join(save_directory, CHAT_TEMPLATE_CONFIG_NAME)
  815. with open(chat_template_file, "w", encoding="utf-8") as f:
  816. json.dump(asdict(self.chat_template), f, ensure_ascii=False, indent=4)
  817. logging.info("Chat-template config file saved in " + chat_template_file)
  818. class PretrainedTokenizer(
  819. ChatTemplateMixin, PretrainedTokenizerBase, metaclass=InitTrackerMeta
  820. ):
  821. """
  822. Base class for all tokenizers.
  823. Inherits from [`~tokenizer_utils_base.PretrainedTokenizerBase`].
  824. Handle all the shared methods for tokenization and special tokens as well as methods downloading/caching/loading
  825. pretrained tokenizers as well as adding tokens to the vocabulary.
  826. This class also contain the added tokens in a unified way on top of all tokenizers so we don't have to handle the
  827. specific vocabulary augmentation methods of the various underlying dictionary structures (BPE, sentencepiece...).
  828. - **resource_files_names** (`Dict[str, str]`) -- A dictionary with, as keys, the `__init__` keyword name of each
  829. vocabulary file required by the model, and as associated values, the filename for saving the associated file
  830. (string).
  831. - **pretrained_resource_files_map** (`Dict[str, Dict[str, str]]`) -- A dictionary of dictionaries, with the
  832. high-level keys being the `__init__` keyword name of each vocabulary file required by the model, the
  833. low-level being the `short-cut-names` of the pretrained models with, as associated values, the `url` to the
  834. associated pretrained vocabulary file.
  835. - **max_model_input_sizes** (`Dict[str, Optional[int]]`) -- A dictionary with, as keys, the `short-cut-names`
  836. of the pretrained models, and as associated values, the maximum length of the sequence inputs of this model,
  837. or `None` if the model has no maximum input size.
  838. - **pretrained_init_configuration** (`Dict[str, Dict[str, Any]]`) -- A dictionary with, as keys, the
  839. `short-cut-names` of the pretrained models, and as associated values, a dictionary of specific arguments to
  840. pass to the `__init__` method of the tokenizer class for this pretrained model when loading the tokenizer
  841. with the [`~tokenizer_utils_base.PretrainedTokenizerBase.from_pretrained`] method.
  842. - **model_input_names** (`List[str]`) -- A list of inputs expected in the forward pass of the model.
  843. - **padding_side** (`str`) -- The default value for the side on which the model should have padding applied.
  844. Should be `'right'` or `'left'`.
  845. - **truncation_side** (`str`) -- The default value for the side on which the model should have truncation
  846. applied. Should be `'right'` or `'left'`.
  847. Moreover, methods common to tokenizers for tokenization, token/id conversion
  848. and encoding as model inputs are also provided here.
  849. Besides, metaclass `InitTrackerMeta` is used to create `PretrainedTokenizer`,
  850. by which subclasses can track arguments for initialization automatically
  851. and expose special tokens initialization used as attributes.
  852. """
  853. added_tokens_encoder: Dict[str, int] = {}
  854. added_tokens_decoder: Dict[int, str] = {}
  855. unique_no_split_tokens: List[str] = []
  856. tokens_trie = Trie()
  857. _decode_use_source_tokenizer = False
  858. def _pre_init(self, original_init, *args, **kwargs):
  859. """
  860. It would be hooked before `__init__` to add specials tokens (arguments of
  861. `__init__` whose name ends with `_token`) as attributes of the tokenizer
  862. instance.
  863. """
  864. init_dict = fn_args_to_dict(original_init, *((self,) + args), **kwargs)
  865. init_dict.pop("self", None)
  866. super(PretrainedTokenizer, self).__init__(**init_dict)
  867. self.added_tokens_encoder: Dict[str, int] = {}
  868. self.added_tokens_decoder: Dict[int, str] = {}
  869. self.unique_no_split_tokens: List[str] = []
  870. self.tokens_trie = Trie()
  871. self._decode_use_source_tokenizer = False
  872. def _build_special_tokens_map_extended(self, **kwargs):
  873. for key, value in kwargs.items():
  874. if value is None:
  875. continue
  876. if key in self.SPECIAL_TOKENS_ATTRIBUTES:
  877. if key == "additional_special_tokens":
  878. assert isinstance(
  879. value, (list, tuple)
  880. ), f"Value {value} is not a list or tuple"
  881. assert all(
  882. isinstance(t, (str, AddedToken)) for t in value
  883. ), "One of the tokens is not a string or an AddedToken"
  884. setattr(self, key, value)
  885. elif isinstance(value, (str, AddedToken)):
  886. setattr(self, key, value)
  887. else:
  888. raise TypeError(
  889. f"special token {key} has to be either str or AddedToken but got: {type(value)}"
  890. )
  891. @property
  892. def vocab_size(self) -> int:
  893. """
  894. `int`: Size of the base vocabulary (without the added tokens).
  895. """
  896. raise NotImplementedError
  897. @property
  898. def is_fast(self) -> bool:
  899. return False
  900. def get_added_vocab(self) -> Dict[str, int]:
  901. """
  902. Returns the added tokens in the vocabulary as a dictionary of token to index.
  903. Returns:
  904. `Dict[str, int]`: The added tokens.
  905. """
  906. return self.added_tokens_encoder
  907. def __len__(self):
  908. """
  909. Size of the full vocabulary with the added tokens.
  910. """
  911. return self.vocab_size + len(self.added_tokens_encoder)
  912. def _add_tokens(
  913. self,
  914. new_tokens: Union[List[str], List[AddedToken]],
  915. special_tokens: bool = False,
  916. ) -> int:
  917. """
  918. Add a list of new tokens to the tokenizer class. If the new tokens are not in the vocabulary, they are added to
  919. it with indices starting from length of the current vocabulary.
  920. Args:
  921. new_tokens (`List[str]`or `List[AddedToken]`):
  922. Token(s) to add in vocabulary. A token is only added if it's not already in the vocabulary (tested by
  923. checking if the tokenizer assign the index of the `unk_token` to them).
  924. special_tokens (`bool`, *optional*, defaults to `False`):
  925. Whether or not the tokens should be added as special tokens.
  926. Returns:
  927. `int`: The number of tokens actually added to the vocabulary.
  928. Examples:
  929. ```python
  930. # Let's see how to increase the vocabulary of Bert model and tokenizer
  931. tokenizer = BertTokenizer.from_pretrained("bert-base-uncased")
  932. model = BertModel.from_pretrained("bert-base-uncased")
  933. num_added_toks = tokenizer.add_tokens(["new_tok1", "my_new-tok2"])
  934. print("We have added", num_added_toks, "tokens")
  935. ```"""
  936. new_tokens = [str(tok) for tok in new_tokens]
  937. tokens_to_add = []
  938. for token in new_tokens:
  939. if not isinstance(token, str):
  940. raise TypeError(f"Token {token} is not a string but a {type(token)}.")
  941. if (
  942. not special_tokens
  943. and hasattr(self, "do_lower_case")
  944. and self.do_lower_case
  945. ):
  946. token = token.lower()
  947. if (
  948. token != self.unk_token
  949. and self.convert_tokens_to_ids(token)
  950. == self.convert_tokens_to_ids(self.unk_token)
  951. and token not in tokens_to_add
  952. ):
  953. tokens_to_add.append(token)
  954. if self.verbose:
  955. logging.info(f"Adding {token} to the vocabulary")
  956. added_tok_encoder = dict(
  957. (tok, len(self) + i) for i, tok in enumerate(tokens_to_add)
  958. )
  959. added_tok_decoder = {v: k for k, v in added_tok_encoder.items()}
  960. self.added_tokens_encoder.update(added_tok_encoder)
  961. self.added_tokens_decoder.update(added_tok_decoder)
  962. # Make sure we don't split on any special tokens (even they were already in the vocab before e.g. for Albert)
  963. if special_tokens:
  964. if len(new_tokens) == 1:
  965. _insert_one_token_to_ordered_list(
  966. self.unique_no_split_tokens, new_tokens[0]
  967. )
  968. else:
  969. self.unique_no_split_tokens = sorted(
  970. set(self.unique_no_split_tokens).union(set(new_tokens))
  971. )
  972. else:
  973. # Or on the newly added tokens
  974. if len(tokens_to_add) == 1:
  975. _insert_one_token_to_ordered_list(
  976. self.unique_no_split_tokens, tokens_to_add[0]
  977. )
  978. else:
  979. self.unique_no_split_tokens = sorted(
  980. set(self.unique_no_split_tokens).union(set(tokens_to_add))
  981. )
  982. self._create_trie(self.unique_no_split_tokens)
  983. return len(tokens_to_add)
  984. def _create_trie(self, unique_no_split_tokens):
  985. trie = Trie()
  986. for token in unique_no_split_tokens:
  987. if (
  988. hasattr(self, "do_lower_case")
  989. and self.do_lower_case
  990. and token not in self.all_special_tokens
  991. ):
  992. trie.add(token.lower())
  993. else:
  994. trie.add(token)
  995. self.tokens_trie = trie
  996. def prepare_for_tokenization(self, text, is_split_into_words=False, **kwargs):
  997. """
  998. Performs any necessary transformations before tokenization.
  999. This method should pop the arguments from kwargs and return the remaining `kwargs` as well. We test the
  1000. `kwargs` at the end of the encoding process to be sure all the arguments have been used.
  1001. Args:
  1002. text (`str`):
  1003. The text to prepare.
  1004. is_split_into_words (`bool`, *optional*, defaults to `False`):
  1005. Whether or not the input is already pre-tokenized (e.g., split into words). If set to `True`, the
  1006. tokenizer assumes the input is already split into words (for instance, by splitting it on whitespace)
  1007. which it will tokenize. This is useful for NER or token classification.
  1008. kwargs:
  1009. Keyword arguments to use for the tokenization.
  1010. Returns:
  1011. `Tuple[str, Dict[str, Any]]`: The prepared text and the unused kwargs.
  1012. """
  1013. return (text, kwargs)
  1014. def tokenize(self, text: TextInput, **kwargs) -> List[str]:
  1015. """
  1016. Converts a string in a sequence of tokens, using the tokenizer.
  1017. Split in words for word-based vocabulary or sub-words for sub-word-based vocabularies
  1018. (BPE/SentencePieces/WordPieces). Takes care of added tokens.
  1019. Args:
  1020. text (`str`):
  1021. The sequence to be encoded.
  1022. **kwargs (additional keyword arguments):
  1023. Passed along to the model-specific `prepare_for_tokenization` preprocessing method.
  1024. Returns:
  1025. `List[str]`: The list of tokens.
  1026. """
  1027. # Simple mapping string => AddedToken for special tokens with specific tokenization behaviors
  1028. all_special_tokens_extended = dict(
  1029. (str(t), t)
  1030. for t in self.all_special_tokens_extended
  1031. if isinstance(t, AddedToken)
  1032. )
  1033. text, kwargs = self.prepare_for_tokenization(text, **kwargs)
  1034. # TODO: should this be in the base class?
  1035. if hasattr(self, "do_lower_case") and self.do_lower_case:
  1036. # convert non-special tokens to lowercase
  1037. escaped_special_toks = [
  1038. re.escape(s_tok)
  1039. for s_tok in (self.unique_no_split_tokens + self.all_special_tokens)
  1040. ]
  1041. pattern = r"(" + r"|".join(escaped_special_toks) + r")|" + r"(.+?)"
  1042. text = re.sub(
  1043. pattern, lambda m: m.groups()[0] or m.groups()[1].lower(), text
  1044. )
  1045. no_split_token = set(self.unique_no_split_tokens)
  1046. tokens = self.tokens_trie.split(text)
  1047. # ["This is something", "<special_token_1>", " else"]
  1048. for i, token in enumerate(tokens):
  1049. if token in no_split_token:
  1050. tok_extended = all_special_tokens_extended.get(token, None)
  1051. left = tokens[i - 1] if i > 0 else None
  1052. right = tokens[i + 1] if i < len(tokens) - 1 else None
  1053. if isinstance(tok_extended, AddedToken):
  1054. if tok_extended.rstrip and right:
  1055. # A bit counter-intuitive but we strip the left of the string
  1056. # since tok_extended.rstrip means the special token is eating all white spaces on its right
  1057. tokens[i + 1] = right.lstrip()
  1058. # Strip white spaces on the left
  1059. if tok_extended.lstrip and left:
  1060. tokens[i - 1] = left.rstrip() # Opposite here
  1061. else:
  1062. # We strip left and right by default
  1063. if right:
  1064. tokens[i + 1] = right.lstrip()
  1065. if left:
  1066. tokens[i - 1] = left.rstrip()
  1067. # ["This is something", "<special_token_1>", "else"]
  1068. tokenized_text = []
  1069. for token in tokens:
  1070. # Need to skip eventual empty (fully stripped) tokens
  1071. if not token:
  1072. continue
  1073. if token in no_split_token:
  1074. tokenized_text.append(token)
  1075. else:
  1076. tokenized_text.extend(self._tokenize(token))
  1077. # ["This", " is", " something", "<special_token_1>", "else"]
  1078. return tokenized_text
  1079. def _tokenize(self, text, **kwargs):
  1080. """
  1081. Converts a string in a sequence of tokens (string), using the tokenizer. Split in words for word-based
  1082. vocabulary or sub-words for sub-word-based vocabularies (BPE/SentencePieces/WordPieces).
  1083. Do NOT take care of added tokens.
  1084. """
  1085. raise NotImplementedError
  1086. def convert_tokens_to_ids(self, tokens):
  1087. if tokens is None:
  1088. return None
  1089. if isinstance(tokens, str):
  1090. return self._convert_token_to_id_with_added_voc(tokens)
  1091. ids = []
  1092. for token in tokens:
  1093. ids.append(self._convert_token_to_id_with_added_voc(token))
  1094. return ids
  1095. def _convert_token_to_id_with_added_voc(self, token):
  1096. if token is None:
  1097. return None
  1098. if token in self.added_tokens_encoder:
  1099. return self.added_tokens_encoder[token]
  1100. return self._convert_token_to_id(token)
  1101. def _convert_token_to_id(self, token):
  1102. return self.vocab.to_indices(token)
  1103. def convert_tokens_to_string(self, tokens):
  1104. """
  1105. Converts a sequence of tokens (list of string) to a single string by
  1106. using ``' '.join(tokens)`` .
  1107. Args:
  1108. tokens (list[str]): A sequence of tokens.
  1109. Returns:
  1110. str: Converted string.
  1111. """
  1112. return " ".join(tokens)
  1113. def convert_ids_to_tokens(self, ids, skip_special_tokens=False):
  1114. if isinstance(ids, int):
  1115. if ids in self.added_tokens_decoder:
  1116. return self.added_tokens_decoder[ids]
  1117. else:
  1118. return self._convert_id_to_token(ids)
  1119. tokens = []
  1120. for index in ids:
  1121. index = int(index)
  1122. if skip_special_tokens and index in self.all_special_ids:
  1123. continue
  1124. if index in self.added_tokens_decoder:
  1125. tokens.append(self.added_tokens_decoder[index])
  1126. else:
  1127. tokens.append(self._convert_id_to_token(index))
  1128. return tokens
  1129. def _convert_id_to_token(self, index):
  1130. return self.vocab.to_tokens(index)
  1131. @staticmethod
  1132. def load_vocabulary(
  1133. filepath,
  1134. unk_token=None,
  1135. pad_token=None,
  1136. bos_token=None,
  1137. eos_token=None,
  1138. **kwargs,
  1139. ):
  1140. """
  1141. Instantiate an instance of `Vocab` from a file reserving all tokens
  1142. by using `Vocab.from_dict`. The file contains a token per line, and the
  1143. line number would be the index of corresponding token.
  1144. Args:
  1145. filepath (str): path of file to construct vocabulary.
  1146. unk_token (str): special token for unknown token. If no need, it also
  1147. could be `None`. Defaults to `None`.
  1148. pad_token (str): special token for padding token. If no need, it also
  1149. could be `None`. Defaults to `None`.
  1150. bos_token (str): special token for bos token. If no need, it also
  1151. could be `None`. Defaults to `None`.
  1152. eos_token (str): special token for eos token. If no need, it also
  1153. could be `None`. Defaults to `None`.
  1154. **kwargs (dict): keyword arguments for `Vocab.from_dict`.
  1155. Returns:
  1156. Vocab: An instance of `Vocab`.
  1157. """
  1158. token_to_idx = {}
  1159. with io.open(filepath, "r", encoding="utf-8") as f:
  1160. for index, line in enumerate(f):
  1161. token = line.rstrip("\n")
  1162. token_to_idx[token] = int(index)
  1163. vocab = Vocab.from_dict(
  1164. token_to_idx,
  1165. unk_token=unk_token,
  1166. pad_token=pad_token,
  1167. bos_token=bos_token,
  1168. eos_token=eos_token,
  1169. **kwargs,
  1170. )
  1171. return vocab
  1172. @staticmethod
  1173. def save_vocabulary(filepath, vocab):
  1174. """
  1175. Save all tokens to a vocabulary file. The file contains a token per line,
  1176. and the line number would be the index of corresponding token.
  1177. Args:
  1178. filepath (str): File path to be saved to.
  1179. vocab (Vocab|dict): The `Vocab` or `dict` instance to be saved.
  1180. """
  1181. if isinstance(vocab, Vocab):
  1182. tokens = vocab.idx_to_token
  1183. else:
  1184. tokens = sorted(vocab.keys(), key=lambda token: vocab[token])
  1185. with io.open(filepath, "w", encoding="utf-8") as f:
  1186. for token in tokens:
  1187. f.write(token + "\n")
  1188. def get_special_tokens_mask(
  1189. self, token_ids_0, token_ids_1=None, already_has_special_tokens=False
  1190. ):
  1191. """
  1192. Retrieves sequence ids from a token list that has no special tokens added. This method is called when adding
  1193. special tokens using the tokenizer ``encode`` methods.
  1194. Args:
  1195. token_ids_0 (List[int]): List of ids of the first sequence.
  1196. token_ids_1 (List[int], optional): List of ids of the second sequence.
  1197. already_has_special_tokens (bool, optional): Whether or not the token list is already
  1198. formatted with special tokens for the model. Defaults to None.
  1199. Returns:
  1200. results (List[int]): The list of integers in the range [0, 1]:
  1201. 1 for a special token, 0 for a sequence token.
  1202. """
  1203. if already_has_special_tokens:
  1204. if token_ids_1 is not None:
  1205. raise ValueError(
  1206. "You should not supply a second sequence if the provided sequence of "
  1207. "ids is already formatted with special tokens for the model."
  1208. )
  1209. return super().get_special_tokens_mask(
  1210. token_ids_0=token_ids_0,
  1211. token_ids_1=token_ids_1,
  1212. already_has_special_tokens=True,
  1213. )
  1214. return [0] * ((len(token_ids_1) if token_ids_1 else 0) + len(token_ids_0))
  1215. def num_special_tokens_to_add(self, pair):
  1216. """
  1217. Returns the number of added tokens when encoding a sequence with special tokens.
  1218. Args:
  1219. pair (bool, optional):
  1220. Whether the number of added tokens should be computed in the case of a sequence pair or a single
  1221. sequence. Defaults to `False`.
  1222. Returns:
  1223. int: Number of special tokens added to sequences.
  1224. """
  1225. token_ids_0 = []
  1226. token_ids_1 = []
  1227. return len(
  1228. self.build_inputs_with_special_tokens(
  1229. token_ids_0, token_ids_1 if pair else None
  1230. )
  1231. )
  1232. def _encode_plus(
  1233. self,
  1234. text: Union[TextInput, PreTokenizedInput, EncodedInput],
  1235. text_pair: Optional[Union[TextInput, PreTokenizedInput, EncodedInput]] = None,
  1236. add_special_tokens: bool = True,
  1237. padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
  1238. truncation_strategy: TruncationStrategy = TruncationStrategy.DO_NOT_TRUNCATE,
  1239. max_length: Optional[int] = None,
  1240. stride: int = 0,
  1241. is_split_into_words: bool = False,
  1242. pad_to_multiple_of: Optional[int] = None,
  1243. return_tensors: Optional[Union[str, TensorType]] = None,
  1244. return_position_ids: Optional[bool] = None,
  1245. return_token_type_ids: Optional[bool] = None,
  1246. return_attention_mask: Optional[bool] = None,
  1247. return_overflowing_tokens: bool = False,
  1248. return_special_tokens_mask: bool = False,
  1249. return_offsets_mapping: bool = False,
  1250. return_length: bool = False,
  1251. verbose: bool = True,
  1252. **kwargs,
  1253. ) -> BatchEncoding:
  1254. def get_input_ids(text):
  1255. if isinstance(text, str):
  1256. tokens = self.tokenize(text, **kwargs)
  1257. return self.convert_tokens_to_ids(tokens)
  1258. elif (
  1259. isinstance(text, (list, tuple))
  1260. and len(text) > 0
  1261. and isinstance(text[0], str)
  1262. ):
  1263. if is_split_into_words:
  1264. tokens = list(
  1265. itertools.chain(
  1266. *(
  1267. self.tokenize(t, is_split_into_words=True, **kwargs)
  1268. for t in text
  1269. )
  1270. )
  1271. )
  1272. return self.convert_tokens_to_ids(tokens)
  1273. else:
  1274. return self.convert_tokens_to_ids(text)
  1275. elif (
  1276. isinstance(text, (list, tuple))
  1277. and len(text) > 0
  1278. and isinstance(text[0], int)
  1279. ):
  1280. return text
  1281. else:
  1282. if is_split_into_words:
  1283. raise ValueError(
  1284. f"Input {text} is not valid. Should be a string or a list/tuple of strings when `is_split_into_words=True`."
  1285. )
  1286. else:
  1287. raise ValueError(
  1288. f"Input {text} is not valid. Should be a string, a list/tuple of strings or a list/tuple of integers."
  1289. )
  1290. first_ids = get_input_ids(text)
  1291. second_ids = get_input_ids(text_pair) if text_pair is not None else None
  1292. if return_offsets_mapping:
  1293. kwargs["text"] = text
  1294. kwargs["text_pair"] = text_pair
  1295. return self.prepare_for_model(
  1296. first_ids,
  1297. pair_ids=second_ids,
  1298. add_special_tokens=add_special_tokens,
  1299. padding=padding_strategy.value,
  1300. truncation=truncation_strategy.value,
  1301. max_length=max_length,
  1302. stride=stride,
  1303. pad_to_multiple_of=pad_to_multiple_of,
  1304. return_tensors=return_tensors,
  1305. prepend_batch_axis=True,
  1306. return_position_ids=return_position_ids,
  1307. return_attention_mask=return_attention_mask,
  1308. return_token_type_ids=return_token_type_ids,
  1309. return_overflowing_tokens=return_overflowing_tokens,
  1310. return_special_tokens_mask=return_special_tokens_mask,
  1311. return_offsets_mapping=return_offsets_mapping,
  1312. return_length=return_length,
  1313. verbose=verbose,
  1314. **kwargs,
  1315. )
  1316. def _batch_encode_plus(
  1317. self,
  1318. batch_text_or_text_pairs: Union[
  1319. List[TextInput],
  1320. List[TextInputPair],
  1321. List[PreTokenizedInput],
  1322. List[PreTokenizedInputPair],
  1323. List[EncodedInput],
  1324. List[EncodedInputPair],
  1325. ],
  1326. add_special_tokens: bool = True,
  1327. padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
  1328. truncation_strategy: TruncationStrategy = TruncationStrategy.DO_NOT_TRUNCATE,
  1329. max_length: Optional[int] = None,
  1330. stride: int = 0,
  1331. is_split_into_words: bool = False,
  1332. pad_to_multiple_of: Optional[int] = None,
  1333. return_position_ids: Optional[bool] = None,
  1334. return_tensors: Optional[Union[str, TensorType]] = None,
  1335. return_token_type_ids: Optional[bool] = None,
  1336. return_attention_mask: Optional[bool] = None,
  1337. return_overflowing_tokens: bool = False,
  1338. return_special_tokens_mask: bool = False,
  1339. return_dict: bool = True,
  1340. return_offsets_mapping: bool = False,
  1341. return_length: bool = False,
  1342. verbose: bool = True,
  1343. **kwargs,
  1344. ) -> BatchEncoding:
  1345. def get_input_ids(text):
  1346. if isinstance(text, str):
  1347. tokens = self.tokenize(text, **kwargs)
  1348. return self.convert_tokens_to_ids(tokens)
  1349. elif (
  1350. isinstance(text, (list, tuple))
  1351. and len(text) > 0
  1352. and isinstance(text[0], str)
  1353. ):
  1354. if is_split_into_words:
  1355. tokens = list(
  1356. itertools.chain(
  1357. *(
  1358. self.tokenize(t, is_split_into_words=True, **kwargs)
  1359. for t in text
  1360. )
  1361. )
  1362. )
  1363. return self.convert_tokens_to_ids(tokens)
  1364. else:
  1365. return self.convert_tokens_to_ids(text)
  1366. elif (
  1367. isinstance(text, (list, tuple))
  1368. and len(text) > 0
  1369. and isinstance(text[0], int)
  1370. ):
  1371. return text
  1372. else:
  1373. raise ValueError(
  1374. "Input is not valid. Should be a string, a list/tuple of strings or a list/tuple of integers."
  1375. )
  1376. input_ids = []
  1377. for ids_or_pair_ids in batch_text_or_text_pairs:
  1378. if not isinstance(ids_or_pair_ids, (list, tuple)):
  1379. ids, pair_ids = ids_or_pair_ids, None
  1380. elif is_split_into_words and not isinstance(
  1381. ids_or_pair_ids[0], (list, tuple)
  1382. ):
  1383. ids, pair_ids = ids_or_pair_ids, None
  1384. else:
  1385. ids, pair_ids = ids_or_pair_ids
  1386. first_ids = get_input_ids(ids)
  1387. second_ids = get_input_ids(pair_ids) if pair_ids is not None else None
  1388. input_ids.append((first_ids, second_ids))
  1389. if stride > 0 and second_ids is not None:
  1390. kwargs["batch_text_or_text_pairs"] = batch_text_or_text_pairs
  1391. else:
  1392. if return_offsets_mapping:
  1393. has_pair = False
  1394. if len(batch_text_or_text_pairs) > 0:
  1395. if isinstance(batch_text_or_text_pairs[0], (list, tuple)):
  1396. has_pair = True
  1397. kwargs["texts"] = None
  1398. kwargs["text_pairs"] = None
  1399. if has_pair:
  1400. kwargs["texts"] = [text[0] for text in batch_text_or_text_pairs]
  1401. kwargs["text_pairs"] = [
  1402. text[1] for text in batch_text_or_text_pairs
  1403. ]
  1404. else:
  1405. kwargs["texts"] = [text for text in batch_text_or_text_pairs]
  1406. batch_outputs = self._batch_prepare_for_model(
  1407. input_ids,
  1408. add_special_tokens=add_special_tokens,
  1409. padding_strategy=padding_strategy,
  1410. truncation_strategy=truncation_strategy,
  1411. max_length=max_length,
  1412. stride=stride,
  1413. pad_to_multiple_of=pad_to_multiple_of,
  1414. return_position_ids=return_position_ids,
  1415. return_attention_mask=return_attention_mask,
  1416. return_token_type_ids=return_token_type_ids,
  1417. return_overflowing_tokens=return_overflowing_tokens,
  1418. return_special_tokens_mask=return_special_tokens_mask,
  1419. return_dict=return_dict,
  1420. return_offsets_mapping=return_offsets_mapping,
  1421. return_length=return_length,
  1422. return_tensors=return_tensors,
  1423. verbose=verbose,
  1424. **kwargs,
  1425. )
  1426. return batch_outputs
  1427. def _batch_prepare_for_model(
  1428. self,
  1429. batch_ids_pairs: List[Union[PreTokenizedInputPair, Tuple[List[int], None]]],
  1430. add_special_tokens: bool = True,
  1431. padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
  1432. truncation_strategy: TruncationStrategy = TruncationStrategy.DO_NOT_TRUNCATE,
  1433. max_length: Optional[int] = None,
  1434. stride: int = 0,
  1435. pad_to_multiple_of: Optional[int] = None,
  1436. return_position_ids: Optional[bool] = None,
  1437. return_tensors: Optional[str] = None,
  1438. return_token_type_ids: Optional[bool] = None,
  1439. return_attention_mask: Optional[bool] = None,
  1440. return_overflowing_tokens: bool = False,
  1441. return_special_tokens_mask: bool = False,
  1442. return_dict: bool = True,
  1443. return_offsets_mapping: bool = False,
  1444. return_length: bool = False,
  1445. verbose: bool = True,
  1446. **kwargs,
  1447. ) -> BatchEncoding:
  1448. """
  1449. Prepares a sequence of input id, or a pair of sequences of inputs ids so that it can be used by the model. It
  1450. adds special tokens, truncates sequences if overflowing while taking into account the special tokens and
  1451. manages a moving window (with user defined stride) for overflowing tokens
  1452. Args:
  1453. batch_ids_pairs: list of tokenized input ids or input ids pairs
  1454. """
  1455. if return_token_type_ids and not add_special_tokens:
  1456. raise ValueError(
  1457. "Asking to return token_type_ids while setting add_special_tokens to False "
  1458. "results in an undefined behavior. Please set add_special_tokens to True or "
  1459. "set return_token_type_ids to None."
  1460. )
  1461. batch_outputs = {}
  1462. batch_outputs_list = []
  1463. for example_id, (first_ids, second_ids) in enumerate(batch_ids_pairs):
  1464. if stride > 0 and second_ids is not None:
  1465. if return_token_type_ids is None:
  1466. return_token_type_ids = "token_type_ids" in self.model_input_names
  1467. if return_attention_mask is None:
  1468. return_attention_mask = "attention_mask" in self.model_input_names
  1469. max_len_for_pair = (
  1470. max_length
  1471. - len(first_ids)
  1472. - (
  1473. self.num_special_tokens_to_add(pair=True)
  1474. if add_special_tokens
  1475. else 0
  1476. )
  1477. )
  1478. text, text_pair = kwargs["batch_text_or_text_pairs"][example_id]
  1479. token_offset_mapping = self.get_offset_mapping(text)
  1480. token_pair_offset_mapping = self.get_offset_mapping(text_pair)
  1481. offset = 0
  1482. while offset < len(second_ids):
  1483. encoded_inputs = {}
  1484. length = len(second_ids) - offset
  1485. if length > max_len_for_pair:
  1486. length = max_len_for_pair
  1487. ids = first_ids
  1488. pair_ids = second_ids[offset : offset + length]
  1489. pair = bool(pair_ids is not None)
  1490. mapping = token_offset_mapping
  1491. pair_mapping = token_pair_offset_mapping[offset : offset + length]
  1492. if add_special_tokens:
  1493. offset_mapping = self.build_offset_mapping_with_special_tokens(
  1494. mapping, pair_mapping
  1495. )
  1496. sequence = self.build_inputs_with_special_tokens(ids, pair_ids)
  1497. token_type_ids = self.create_token_type_ids_from_sequences(
  1498. ids, pair_ids
  1499. )
  1500. else:
  1501. offset_mapping = mapping + pair_mapping
  1502. sequence = ids + pair_ids if pair else ids
  1503. token_type_ids = [0] * len(ids) + (
  1504. [0] * len(pair_ids) if pair else []
  1505. )
  1506. encoded_inputs["offset_mapping"] = offset_mapping
  1507. # Build output dictionnary
  1508. encoded_inputs["input_ids"] = sequence
  1509. if return_token_type_ids:
  1510. encoded_inputs["token_type_ids"] = token_type_ids
  1511. if return_special_tokens_mask:
  1512. if add_special_tokens:
  1513. encoded_inputs["special_tokens_mask"] = (
  1514. self.get_special_tokens_mask(ids, pair_ids)
  1515. )
  1516. else:
  1517. encoded_inputs["special_tokens_mask"] = [0] * len(sequence)
  1518. # Check lengths
  1519. self._eventual_warn_about_too_long_sequence(
  1520. encoded_inputs["input_ids"], max_length, verbose
  1521. )
  1522. if return_position_ids:
  1523. encoded_inputs["position_ids"] = list(
  1524. range(len(encoded_inputs["input_ids"]))
  1525. )
  1526. if return_length:
  1527. encoded_inputs["length"] = len(encoded_inputs["input_ids"])
  1528. encoded_inputs["seq_len"] = encoded_inputs["length"]
  1529. encoded_inputs["overflow_to_sample"] = example_id
  1530. for key, value in encoded_inputs.items():
  1531. if key not in batch_outputs:
  1532. batch_outputs[key] = []
  1533. batch_outputs[key].append(value)
  1534. if offset + length == len(second_ids):
  1535. break
  1536. offset += min(length, stride)
  1537. else:
  1538. if return_offsets_mapping:
  1539. kwargs["text"] = kwargs["texts"][example_id]
  1540. kwargs["text_pair"] = None
  1541. if kwargs["text_pairs"] is not None:
  1542. kwargs["text_pair"] = kwargs["text_pairs"][example_id]
  1543. encoded_inputs = self.prepare_for_model(
  1544. first_ids,
  1545. second_ids,
  1546. add_special_tokens=add_special_tokens,
  1547. padding=PaddingStrategy.DO_NOT_PAD.value, # we pad in batch afterward
  1548. truncation=truncation_strategy.value,
  1549. max_length=max_length,
  1550. stride=stride,
  1551. pad_to_multiple_of=None, # we pad in batch afterward
  1552. return_position_ids=return_position_ids, # we pad in batch afterward
  1553. return_attention_mask=False, # we pad in batch afterward
  1554. return_token_type_ids=return_token_type_ids,
  1555. return_overflowing_tokens=return_overflowing_tokens,
  1556. return_special_tokens_mask=return_special_tokens_mask,
  1557. return_offsets_mapping=return_offsets_mapping,
  1558. return_length=return_length,
  1559. return_tensors=None, # We convert the whole batch to tensors at the end
  1560. prepend_batch_axis=False,
  1561. verbose=verbose,
  1562. **kwargs,
  1563. )
  1564. for key, value in encoded_inputs.items():
  1565. if key not in batch_outputs:
  1566. batch_outputs[key] = []
  1567. batch_outputs[key].append(value)
  1568. batch_outputs = self.pad(
  1569. batch_outputs,
  1570. padding=padding_strategy.value,
  1571. max_length=max_length,
  1572. pad_to_multiple_of=pad_to_multiple_of,
  1573. return_attention_mask=return_attention_mask,
  1574. )
  1575. if return_dict:
  1576. batch_outputs = BatchEncoding(batch_outputs, tensor_type=return_tensors)
  1577. return batch_outputs
  1578. else:
  1579. for k, v in batch_outputs.items():
  1580. for i in range(len(v)):
  1581. if i >= len(batch_outputs_list):
  1582. batch_outputs_list.append({k: v[i]})
  1583. else:
  1584. batch_outputs_list[i][k] = v[i]
  1585. return batch_outputs_list
  1586. def _get_bert_like_offset_mapping(self, text: str):
  1587. """
  1588. Returns the map of tokens and the start and end index of their start and end character.
  1589. Modified from https://github.com/bojone/bert4keras/blob/master/bert4keras/tokenizers.py#L372
  1590. Args:
  1591. text (str):
  1592. Input text.
  1593. Returns:
  1594. list: The offset map of input text.
  1595. """
  1596. if text is None:
  1597. return None
  1598. split_tokens = self.tokenize(text)
  1599. normalized_text, char_mapping = "", []
  1600. for i, ch in enumerate(text):
  1601. if hasattr(self, "do_lower_case") and self.do_lower_case:
  1602. ch = ch.lower()
  1603. if self.basic_tokenizer.strip_accents is not False:
  1604. ch = unicodedata.normalize("NFD", ch)
  1605. ch = "".join([c for c in ch if unicodedata.category(c) != "Mn"])
  1606. elif self.basic_tokenizer.strip_accents:
  1607. ch = unicodedata.normalize("NFD", ch)
  1608. ch = "".join([c for c in ch if unicodedata.category(c) != "Mn"])
  1609. ch = "".join(
  1610. [
  1611. c
  1612. for c in ch
  1613. if not (ord(c) == 0 or ord(c) == 0xFFFD or _is_control(c))
  1614. ]
  1615. )
  1616. normalized_text += ch
  1617. char_mapping.extend([i] * len(ch))
  1618. text, token_mapping, offset = normalized_text, [], 0
  1619. char_mapping_indexes = []
  1620. for index, token in enumerate(split_tokens):
  1621. if token[:2] == "##":
  1622. token = token[2:]
  1623. if token in self.all_special_tokens:
  1624. token = (
  1625. token.lower()
  1626. if hasattr(self, "do_lower_case") and self.do_lower_case
  1627. else token
  1628. )
  1629. # The greek letter "sigma" has 2 forms of lowercase, σ and ς respectively.
  1630. # When used as a final letter of a word, the final form (ς) is used. Otherwise, the form (σ) is used.
  1631. # https://latin.stackexchange.com/questions/6168/how-and-when-did-we-get-two-forms-of-sigma
  1632. if "σ" in token or "ς" in token:
  1633. start = (
  1634. text[offset:].replace("ς", "σ").index(token.replace("ς", "σ"))
  1635. + offset
  1636. )
  1637. else:
  1638. # try to fix: https://github.com/PaddlePaddle/PaddleNLP/issues/3985
  1639. if token not in text[offset:]:
  1640. # check whether there are consecutive UNK tokens, eg: ['好', '[UNK]', '[UNK]', 'good']
  1641. if (
  1642. index < len(split_tokens) - 1
  1643. and split_tokens[index + 1] in self.all_special_tokens
  1644. ):
  1645. start = offset
  1646. token = " " # only contains one char
  1647. else:
  1648. start = -1
  1649. else:
  1650. start = text[offset:].index(token) + offset
  1651. end = start + len(token)
  1652. char_mapping_indexes.append([start, end])
  1653. if start != -1:
  1654. offset = end
  1655. token_mapping = []
  1656. for index, (start, end) in enumerate(char_mapping_indexes):
  1657. if start == -1:
  1658. # init start
  1659. if index == 0:
  1660. start = 0
  1661. else:
  1662. start = char_mapping_indexes[index - 1][1]
  1663. # init end
  1664. if index == len(char_mapping_indexes) - 1:
  1665. end = len(char_mapping)
  1666. else:
  1667. # next start
  1668. end = char_mapping_indexes[index + 1][0]
  1669. token_mapping.append((char_mapping[start], char_mapping[end - 1] + 1))
  1670. return token_mapping
  1671. def get_offset_mapping(self, text: str, split_tokens: Optional[List[str]] = None):
  1672. """
  1673. Returns the map of tokens and the start and end index of their start and end character.
  1674. Modified from https://github.com/bojone/bert4keras/blob/master/bert4keras/tokenizers.py#L372
  1675. Args:
  1676. text (str):
  1677. Input text.
  1678. split_tokens (Optional[List[str]]):
  1679. the tokens which has been split which can accelerate the operation.
  1680. Returns:
  1681. list: The offset map of input text.
  1682. """
  1683. if text is None:
  1684. return None
  1685. split_tokens = self.tokenize(text)
  1686. # bert-like tokenizer use the old-school code block
  1687. if hasattr(self, "basic_tokenizer") or hasattr(self, "wordpiece_tokenizer"):
  1688. return self._get_bert_like_offset_mapping(text)
  1689. if not split_tokens:
  1690. split_tokens = self.tokenize(text)
  1691. normalized_text, char_mapping = "", []
  1692. for i, ch in enumerate(text):
  1693. normalized_text += normalize_chars(ch)
  1694. char_mapping.extend([i] * len(ch))
  1695. text, token_mapping, offset = normalized_text, [], 0
  1696. do_lower_case = getattr(self, "do_lower_case", False)
  1697. # lower the text if the token is lower-cased
  1698. # keep align with token
  1699. if do_lower_case:
  1700. text = text.lower()
  1701. char_mapping_indexes = []
  1702. for token in split_tokens:
  1703. # convert tokens into original string
  1704. token: str = self.convert_tokens_to_string(token).strip()
  1705. if token in self.all_special_tokens:
  1706. if do_lower_case:
  1707. token = token.lower()
  1708. # The greek letter "sigma" has 2 forms of lowercase, σ and ς respectively.
  1709. # When used as a final letter of a word, the final form (ς) is used. Otherwise, the form (σ) is used.
  1710. # https://latin.stackexchange.com/questions/6168/how-and-when-did-we-get-two-forms-of-sigma
  1711. if "σ" in token or "ς" in token:
  1712. start = (
  1713. text[offset:].replace("ς", "σ").index(token.replace("ς", "σ"))
  1714. + offset
  1715. )
  1716. else:
  1717. # try to fix: https://github.com/PaddlePaddle/PaddleNLP/issues/3985
  1718. if token not in text[offset:]:
  1719. start = -1
  1720. else:
  1721. start = text[offset:].index(token) + offset
  1722. end = start + len(token)
  1723. char_mapping_indexes.append([start, end])
  1724. if start != -1:
  1725. offset = end
  1726. token_mapping = []
  1727. for index, (start, end) in enumerate(char_mapping_indexes):
  1728. if start == -1:
  1729. # init start
  1730. if index == 0:
  1731. start = 0
  1732. else:
  1733. start = char_mapping_indexes[index - 1][1]
  1734. # init end
  1735. if index == len(char_mapping_indexes) - 1:
  1736. end = len(char_mapping)
  1737. else:
  1738. # next start
  1739. end = char_mapping_indexes[index + 1][0]
  1740. token_mapping.append((char_mapping[start], char_mapping[end - 1] + 1))
  1741. return token_mapping
  1742. def _decode(
  1743. self,
  1744. token_ids: List[int],
  1745. skip_special_tokens: bool = False,
  1746. clean_up_tokenization_spaces: bool = True,
  1747. spaces_between_special_tokens: bool = True,
  1748. **kwargs,
  1749. ) -> str:
  1750. if isinstance(token_ids, np.ndarray):
  1751. token_ids = token_ids.tolist()
  1752. self._decode_use_source_tokenizer = kwargs.pop("use_source_tokenizer", False)
  1753. filtered_tokens = self.convert_ids_to_tokens(
  1754. token_ids, skip_special_tokens=skip_special_tokens
  1755. )
  1756. # To avoid mixing byte-level and unicode for byte-level BPT
  1757. # we need to build string separately for added tokens and byte-level tokens
  1758. # cf. https://github.com/huggingface/transformers/issues/1133
  1759. sub_texts = []
  1760. current_sub_text = []
  1761. for token in filtered_tokens:
  1762. if skip_special_tokens and token in self.all_special_ids:
  1763. continue
  1764. if token in self.added_tokens_encoder:
  1765. if current_sub_text:
  1766. sub_texts.append(self.convert_tokens_to_string(current_sub_text))
  1767. current_sub_text = []
  1768. sub_texts.append(token)
  1769. else:
  1770. current_sub_text.append(token)
  1771. if current_sub_text:
  1772. sub_texts.append(self.convert_tokens_to_string(current_sub_text))
  1773. if spaces_between_special_tokens:
  1774. text = " ".join(sub_texts)
  1775. else:
  1776. text = "".join(sub_texts)
  1777. if clean_up_tokenization_spaces:
  1778. clean_text = self.clean_up_tokenization(text)
  1779. return clean_text
  1780. else:
  1781. return text
  1782. def decode_token(
  1783. self,
  1784. all_input_ids: List[int],
  1785. prefix_offset: int = 0,
  1786. read_offset: int = 0,
  1787. ) -> Tuple[str, int, int]:
  1788. """tokenizer decoding for the streaming generation use case. This method can be overrided for tokenizer that doesn't follow this API"""
  1789. # The prefix text is necessary only to defeat cleanup algorithms in the decode
  1790. # which decide to add a space or not depending on the surrounding ids.
  1791. prefix_text = self.decode(
  1792. all_input_ids[prefix_offset:read_offset], skip_special_tokens=False
  1793. )
  1794. new_text = self.decode(all_input_ids[prefix_offset:], skip_special_tokens=False)
  1795. if len(new_text) > len(prefix_text) and not new_text.endswith("�"):
  1796. # utf-8 char at the end means it's a potential unfinished byte sequence
  1797. # from byte fallback tokenization.
  1798. # If it's in the middle, it's probably a real invalid id generated
  1799. # by the model
  1800. prefix_index = new_text.index(prefix_text)
  1801. new_text = new_text[prefix_index + len(prefix_text) :]
  1802. return new_text, read_offset, len(all_input_ids)
  1803. else:
  1804. return "", prefix_offset, read_offset
  1805. def _is_control(char):
  1806. """Checks whether `chars` is a control character."""
  1807. # These are technically control characters but we count them as whitespace
  1808. # characters.
  1809. if char == "\t" or char == "\n" or char == "\r":
  1810. return False
  1811. cat = unicodedata.category(char)
  1812. if cat.startswith("C"):
  1813. return True
  1814. return False
  1815. def _is_punctuation(char):
  1816. """Checks whether `chars` is a punctuation character."""
  1817. cp = ord(char)
  1818. # We treat all non-letter/number ASCII as punctuation.
  1819. # Characters such as "^", "$", and "`" are not in the Unicode
  1820. # Punctuation class but we treat them as punctuation anyways, for
  1821. # consistency.
  1822. if (
  1823. (cp >= 33 and cp <= 47)
  1824. or (cp >= 58 and cp <= 64)
  1825. or (cp >= 91 and cp <= 96)
  1826. or (cp >= 123 and cp <= 126)
  1827. ):
  1828. return True
  1829. cat = unicodedata.category(char)
  1830. if cat.startswith("P"):
  1831. return True
  1832. return False
  1833. def _is_symbol(char):
  1834. """Check whether CP is the codepoint of a Symbol character."""
  1835. cp = ord(char)
  1836. if unicodedata.category(char).startswith("S") or (
  1837. cp in [0x00AD, 0x00B2, 0x00BA, 0x3007, 0x00B5, 0x00D8, 0x014B, 0x01B1]
  1838. ):
  1839. return True
  1840. return False
  1841. def _is_whitespace(char):
  1842. """
  1843. Checks whether `chars` is a whitespace character.
  1844. """
  1845. # \t, \n, and \r are technically contorl characters but we treat them
  1846. # as whitespace since they are generally considered as such.
  1847. if char == " " or char == "\t" or char == "\n" or char == "\r":
  1848. return True
  1849. cat = unicodedata.category(char)
  1850. if cat == "Zs":
  1851. return True
  1852. return False
  1853. def convert_to_unicode(text):
  1854. """
  1855. Converts `text` to Unicode (if it's not already), assuming utf-8 input.
  1856. Args:
  1857. text (str|bytes): Text to be converted to unicode.
  1858. Returns:
  1859. str: converted text.
  1860. """
  1861. if isinstance(text, str):
  1862. return text
  1863. elif isinstance(text, bytes):
  1864. return text.decode("utf-8", "ignore")
  1865. else:
  1866. raise ValueError("Unsupported string type: %s" % (type(text)))
  1867. def whitespace_tokenize(text):
  1868. """
  1869. Runs basic whitespace cleaning and splitting on a peice of text.
  1870. Args:
  1871. text (str): Text to be tokenized.
  1872. Returns:
  1873. list(str): Token list.
  1874. """
  1875. text = text.strip()
  1876. if not text:
  1877. return []
  1878. tokens = text.split()
  1879. return tokens