clip_tokenizer.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606
  1. # copyright (c) 2024 PaddlePaddle Authors. All Rights Reserve.
  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 json
  15. import os
  16. import shutil
  17. import logging
  18. import unicodedata
  19. from functools import lru_cache
  20. from typing import List, Optional
  21. from paddle.utils import try_import
  22. from .tokenizer_utils_base import AddedToken
  23. from .tokenizer_utils import PretrainedTokenizer
  24. from .tokenizer_utils import _is_control, _is_punctuation, _is_whitespace
  25. __all__ = ["CLIPTokenizer"]
  26. @lru_cache()
  27. def bytes_to_unicode():
  28. """
  29. Returns list of utf-8 byte and a mapping to unicode strings. We specifically avoids mapping to whitespace/control
  30. characters the bpe code barfs on.
  31. The reversible bpe codes work on unicode strings. This means you need a large # of unicode characters in your vocab
  32. if you want to avoid UNKs. When you're at something like a 10B token dataset you end up needing around 5K for
  33. decent coverage. This is a significant percentage of your normal, say, 32K bpe vocab. To avoid that, we want lookup
  34. tables between utf-8 bytes and unicode strings.
  35. """
  36. bs = (
  37. list(range(ord("!"), ord("~") + 1))
  38. + list(range(ord("¡"), ord("¬") + 1))
  39. + list(range(ord("®"), ord("ÿ") + 1))
  40. )
  41. cs = bs[:]
  42. n = 0
  43. for b in range(2**8):
  44. if b not in bs:
  45. bs.append(b)
  46. cs.append(2**8 + n)
  47. n += 1
  48. cs = [chr(n) for n in cs]
  49. return dict(zip(bs, cs))
  50. def get_pairs(word):
  51. """
  52. Return set of symbol pairs in a word.
  53. Word is represented as tuple of symbols (symbols being variable-length strings).
  54. """
  55. pairs = set()
  56. prev_char = word[0]
  57. for char in word[1:]:
  58. pairs.add((prev_char, char))
  59. prev_char = char
  60. return pairs
  61. def whitespace_clean(text, re):
  62. text = re.sub(r"\s+", " ", text)
  63. text = text.strip()
  64. return text
  65. def whitespace_tokenize(text):
  66. """Runs basic whitespace cleaning and splitting on a piece of text."""
  67. text = text.strip()
  68. if not text:
  69. return []
  70. tokens = text.split()
  71. return tokens
  72. # Copied from transformers.models.bert.tokenization_bert.BasicTokenizer
  73. class BasicTokenizer(object):
  74. """
  75. Constructs a BasicTokenizer that will run basic tokenization (punctuation splitting, lower casing, etc.).
  76. Args:
  77. do_lower_case (`bool`, *optional*, defaults to `True`):
  78. Whether or not to lowercase the input when tokenizing.
  79. never_split (`Iterable`, *optional*):
  80. Collection of tokens which will never be split during tokenization. Only has an effect when
  81. `do_basic_tokenize=True`
  82. tokenize_chinese_chars (`bool`, *optional*, defaults to `True`):
  83. Whether or not to tokenize Chinese characters.
  84. This should likely be deactivated for Japanese (see this
  85. [issue](https://github.com/huggingface/transformers/issues/328)).
  86. strip_accents (`bool`, *optional*):
  87. Whether or not to strip all accents. If this option is not specified, then it will be determined by the
  88. value for `lowercase` (as in the original BERT).
  89. do_split_on_punc (`bool`, *optional*, defaults to `True`):
  90. In some instances we want to skip the basic punctuation splitting so that later tokenization can capture
  91. the full context of the words, such as contractions.
  92. """
  93. def __init__(
  94. self,
  95. do_lower_case=True,
  96. never_split=None,
  97. tokenize_chinese_chars=True,
  98. strip_accents=None,
  99. do_split_on_punc=True,
  100. ):
  101. if never_split is None:
  102. never_split = []
  103. self.do_lower_case = do_lower_case
  104. self.never_split = set(never_split)
  105. self.tokenize_chinese_chars = tokenize_chinese_chars
  106. self.strip_accents = strip_accents
  107. self.do_split_on_punc = do_split_on_punc
  108. def tokenize(self, text, never_split=None):
  109. """
  110. Basic Tokenization of a piece of text. For sub-word tokenization, see WordPieceTokenizer.
  111. Args:
  112. never_split (`List[str]`, *optional*)
  113. Kept for backward compatibility purposes. Now implemented directly at the base class level (see
  114. [`PreTrainedTokenizer.tokenize`]) List of token not to split.
  115. """
  116. # union() returns a new set by concatenating the two sets.
  117. never_split = (
  118. self.never_split.union(set(never_split))
  119. if never_split
  120. else self.never_split
  121. )
  122. text = self._clean_text(text)
  123. # This was added on November 1st, 2018 for the multilingual and Chinese
  124. # models. This is also applied to the English models now, but it doesn't
  125. # matter since the English models were not trained on any Chinese data
  126. # and generally don't have any Chinese data in them (there are Chinese
  127. # characters in the vocabulary because Wikipedia does have some Chinese
  128. # words in the English Wikipedia.).
  129. if self.tokenize_chinese_chars:
  130. text = self._tokenize_chinese_chars(text)
  131. # prevents treating the same character with different unicode codepoints as different characters
  132. unicode_normalized_text = unicodedata.normalize("NFC", text)
  133. orig_tokens = whitespace_tokenize(unicode_normalized_text)
  134. split_tokens = []
  135. for token in orig_tokens:
  136. if token not in never_split:
  137. if self.do_lower_case:
  138. token = token.lower()
  139. if self.strip_accents is not False:
  140. token = self._run_strip_accents(token)
  141. elif self.strip_accents:
  142. token = self._run_strip_accents(token)
  143. split_tokens.extend(self._run_split_on_punc(token, never_split))
  144. output_tokens = whitespace_tokenize(" ".join(split_tokens))
  145. return output_tokens
  146. def _run_strip_accents(self, text):
  147. """Strips accents from a piece of text."""
  148. text = unicodedata.normalize("NFD", text)
  149. output = []
  150. for char in text:
  151. cat = unicodedata.category(char)
  152. if cat == "Mn":
  153. continue
  154. output.append(char)
  155. return "".join(output)
  156. def _run_split_on_punc(self, text, never_split=None):
  157. """Splits punctuation on a piece of text."""
  158. if not self.do_split_on_punc or (
  159. never_split is not None and text in never_split
  160. ):
  161. return [text]
  162. chars = list(text)
  163. i = 0
  164. start_new_word = True
  165. output = []
  166. while i < len(chars):
  167. char = chars[i]
  168. if _is_punctuation(char):
  169. output.append([char])
  170. start_new_word = True
  171. else:
  172. if start_new_word:
  173. output.append([])
  174. start_new_word = False
  175. output[-1].append(char)
  176. i += 1
  177. return ["".join(x) for x in output]
  178. def _tokenize_chinese_chars(self, text):
  179. """Adds whitespace around any CJK character."""
  180. output = []
  181. for char in text:
  182. cp = ord(char)
  183. if self._is_chinese_char(cp):
  184. output.append(" ")
  185. output.append(char)
  186. output.append(" ")
  187. else:
  188. output.append(char)
  189. return "".join(output)
  190. def _is_chinese_char(self, cp):
  191. """Checks whether CP is the codepoint of a CJK character."""
  192. # This defines a "chinese character" as anything in the CJK Unicode block:
  193. # https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block)
  194. #
  195. # Note that the CJK Unicode block is NOT all Japanese and Korean characters,
  196. # despite its name. The modern Korean Hangul alphabet is a different block,
  197. # as is Japanese Hiragana and Katakana. Those alphabets are used to write
  198. # space-separated words, so they are not treated specially and handled
  199. # like the all of the other languages.
  200. if (
  201. (cp >= 0x4E00 and cp <= 0x9FFF)
  202. or (cp >= 0x3400 and cp <= 0x4DBF) #
  203. or (cp >= 0x20000 and cp <= 0x2A6DF) #
  204. or (cp >= 0x2A700 and cp <= 0x2B73F) #
  205. or (cp >= 0x2B740 and cp <= 0x2B81F) #
  206. or (cp >= 0x2B820 and cp <= 0x2CEAF) #
  207. or (cp >= 0xF900 and cp <= 0xFAFF)
  208. or (cp >= 0x2F800 and cp <= 0x2FA1F) #
  209. ): #
  210. return True
  211. return False
  212. def _clean_text(self, text):
  213. """Performs invalid character removal and whitespace cleanup on text."""
  214. output = []
  215. for char in text:
  216. cp = ord(char)
  217. if cp == 0 or cp == 0xFFFD or _is_control(char):
  218. continue
  219. if _is_whitespace(char):
  220. output.append(" ")
  221. else:
  222. output.append(char)
  223. return "".join(output)
  224. class CLIPTokenizer(PretrainedTokenizer):
  225. r"""
  226. Construct a CLIP tokenizer based on byte-level Byte-Pair-Encoding.
  227. This tokenizer inherits from :class:`~paddlenlp.transformers.gpt.tokenizer.GPTTokenizer`.
  228. For more information regarding those methods, please refer to this superclass.
  229. Args:
  230. vocab_file (str):
  231. Path to the vocabulary file.
  232. The vocab file contains a mapping from vocabulary strings to indices.
  233. merges_file (str):
  234. Path to the merge file.
  235. The merge file is used to split the input sentence into "subword" units.
  236. The vocab file is then used to encode those units as intices.
  237. errors (str):
  238. Paradigm to follow when decoding bytes to UTF-8.
  239. Defaults to `'replace'`.
  240. max_len (int, optional):
  241. The maximum value of the input sequence length.
  242. Defaults to `77`.
  243. bos_token (str, optional):
  244. The beginning of sequence token that was used during pretraining. Can be
  245. used a sequence classifier token.
  246. Defaults to `"<|startoftext|>"`.
  247. eos_token (str, optional):
  248. A special token representing the end of a sequence that was used during pretraining.
  249. Defaults to `"<|endoftext|>"`.
  250. unk_token (str, optional):
  251. A special token representing the *unknown (out-of-vocabulary)* token.
  252. An unknown token is set to be `unk_token` inorder to be converted to an ID.
  253. Defaults to `"<|endoftext|>"`.
  254. pad_token (str, optional):
  255. A special token used to make arrays of tokens the same size for batching purposes.
  256. Defaults to `"<|endoftext|>"`.
  257. Examples:
  258. .. code-block::
  259. from paddlenlp.transformers import AutoTokenizer
  260. tokenizer = AutoTokenizer.from_pretrained('openai/clip-vit-base-patch32')
  261. print(tokenizer('He was a puppeteer'))
  262. '''
  263. {'input_ids': [49406, 797, 739, 320, 7116, 38820, 528, 49407]}
  264. '''
  265. """
  266. # merges and vocab same as GPT2
  267. resource_files_names = {"vocab_file": "vocab.json", "merges_file": "merges.txt"}
  268. pretrained_resource_files_map = {"vocab_file": {}, "merges_file": {}}
  269. pretrained_init_configuration = {}
  270. model_input_names = [
  271. "input_ids",
  272. "attention_mask",
  273. ]
  274. def __init__(
  275. self,
  276. vocab_file,
  277. merges_file,
  278. errors="replace",
  279. max_len=77,
  280. bos_token="<|startoftext|>",
  281. eos_token="<|endoftext|>",
  282. unk_token="<|endoftext|>",
  283. pad_token="<|endoftext|>",
  284. **kwargs
  285. ):
  286. bos_token = (
  287. AddedToken(bos_token, lstrip=False, rstrip=False)
  288. if isinstance(bos_token, str)
  289. else bos_token
  290. )
  291. eos_token = (
  292. AddedToken(eos_token, lstrip=False, rstrip=False)
  293. if isinstance(eos_token, str)
  294. else eos_token
  295. )
  296. unk_token = (
  297. AddedToken(unk_token, lstrip=False, rstrip=False)
  298. if isinstance(unk_token, str)
  299. else unk_token
  300. )
  301. pad_token = (
  302. AddedToken(pad_token, lstrip=False, rstrip=False)
  303. if isinstance(pad_token, str)
  304. else pad_token
  305. )
  306. self._build_special_tokens_map_extended(
  307. bos_token=bos_token,
  308. eos_token=eos_token,
  309. unk_token=unk_token,
  310. pad_token=pad_token,
  311. )
  312. try:
  313. import ftfy
  314. self.fix_text = ftfy.fix_text
  315. except ImportError:
  316. logging.info(
  317. "ftfy or spacy is not installed using custom BasicTokenizer instead of ftfy."
  318. )
  319. self.nlp = BasicTokenizer(
  320. strip_accents=False, do_split_on_punc=False, do_lower_case=True
  321. )
  322. self.fix_text = None
  323. self.re = try_import("regex")
  324. self._vocab_file = vocab_file
  325. self._merges_file = merges_file
  326. self.max_len = max_len if max_len is not None else int(1e12)
  327. with open(vocab_file, encoding="utf-8") as vocab_handle:
  328. self.encoder = json.load(vocab_handle)
  329. self.decoder = {v: k for k, v in self.encoder.items()}
  330. self.errors = errors # how to handle errors in decoding
  331. self.byte_encoder = bytes_to_unicode()
  332. self.byte_decoder = {v: k for k, v in self.byte_encoder.items()}
  333. with open(merges_file, encoding="utf-8") as merges_handle:
  334. bpe_merges = (
  335. merges_handle.read().strip().split("\n")[1 : 49152 - 256 - 2 + 1]
  336. )
  337. bpe_merges = [tuple(merge.split()) for merge in bpe_merges]
  338. self.bpe_ranks = dict(zip(bpe_merges, range(len(bpe_merges))))
  339. self.cache = {
  340. "<|startoftext|>": "<|startoftext|>",
  341. "<|endoftext|>": "<|endoftext|>",
  342. }
  343. self.pat = self.re.compile(
  344. r"""<\|startoftext\|>|<\|endoftext\|>|'s|'t|'re|'ve|'m|'ll|'d|[\p{L}]+|[\p{N}]|[^\s\p{L}\p{N}]+""",
  345. self.re.IGNORECASE,
  346. )
  347. @property
  348. def vocab_size(self):
  349. """
  350. Returns the size of vocabulary.
  351. Returns:
  352. int: The sum of size of vocabulary and the size of speical tokens.
  353. """
  354. return len(self.encoder)
  355. def get_vocab(self):
  356. return dict(self.encoder, **self.added_tokens_encoder)
  357. def build_inputs_with_special_tokens(
  358. self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
  359. ) -> List[int]:
  360. """
  361. Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
  362. adding special tokens. A CLIP sequence has the following format:
  363. - single sequence: `<|startoftext|> X <|endoftext|>`
  364. Pairs of sequences are not the expected use case, but they will be handled without a separator.
  365. Args:
  366. token_ids_0 (`List[int]`):
  367. List of IDs to which the special tokens will be added.
  368. token_ids_1 (`List[int]`, *optional*):
  369. Optional second list of IDs for sequence pairs.
  370. Returns:
  371. `List[int]`: List of input IDs with the appropriate special tokens.
  372. """
  373. bos_token = [self.bos_token_id]
  374. eos_token = [self.eos_token_id]
  375. if token_ids_1 is None:
  376. return bos_token + token_ids_0 + eos_token
  377. return bos_token + token_ids_0 + eos_token + eos_token + token_ids_1 + eos_token
  378. def build_offset_mapping_with_special_tokens(
  379. self, offset_mapping_0, offset_mapping_1=None
  380. ):
  381. """
  382. Build offset map from a pair of offset map by concatenating and adding offsets of special tokens.
  383. Should be overridden in a subclass if the model has a special way of building those.
  384. Args:
  385. offset_mapping_0 (List[tuple]):
  386. List of char offsets to which the special tokens will be added.
  387. offset_mapping_1 (List[tuple], optional):
  388. Optional second list of char offsets for offset mapping pairs.
  389. Returns:
  390. List[tuple]: List of char offsets with the appropriate offsets of special tokens.
  391. """
  392. if offset_mapping_1 is None:
  393. return [(0, 0)] + offset_mapping_0 + [(0, 0)]
  394. return (
  395. [(0, 0)] + offset_mapping_0 + [(0, 0), (0, 0)] + offset_mapping_1 + [(0, 0)]
  396. )
  397. def get_special_tokens_mask(
  398. self, token_ids_0, token_ids_1=None, already_has_special_tokens=False
  399. ):
  400. """
  401. Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
  402. special tokens using the tokenizer `prepare_for_model` method.
  403. Args:
  404. token_ids_0 (`List[int]`):
  405. List of IDs.
  406. token_ids_1 (`List[int]`, *optional*):
  407. Optional second list of IDs for sequence pairs.
  408. already_has_special_tokens (`bool`, *optional*, defaults to `False`):
  409. Whether or not the token list is already formatted with special tokens for the model.
  410. Returns:
  411. `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
  412. """
  413. if already_has_special_tokens:
  414. return super().get_special_tokens_mask(
  415. token_ids_0=token_ids_0,
  416. token_ids_1=token_ids_1,
  417. already_has_special_tokens=True,
  418. )
  419. if token_ids_1 is None:
  420. return [1] + ([0] * len(token_ids_0)) + [1]
  421. return (
  422. [1] + ([0] * len(token_ids_0)) + [1] + [1] + ([0] * len(token_ids_1)) + [1]
  423. )
  424. def create_token_type_ids_from_sequences(
  425. self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
  426. ) -> List[int]:
  427. """
  428. Create a mask from the two sequences passed. CLIP does not make use of token type ids, therefore a list of
  429. zeros is returned.
  430. Args:
  431. token_ids_0 (`List[int]`):
  432. List of IDs.
  433. token_ids_1 (`List[int]`, *optional*):
  434. Optional second list of IDs for sequence pairs.
  435. Returns:
  436. `List[int]`: List of zeros.
  437. """
  438. bos_token = [self.bos_token_id]
  439. eos_token = [self.eos_token_id]
  440. if token_ids_1 is None:
  441. return len(bos_token + token_ids_0 + eos_token) * [0]
  442. return len(
  443. bos_token + token_ids_0 + eos_token + eos_token + token_ids_1 + eos_token
  444. ) * [0]
  445. def bpe(self, token):
  446. if token in self.cache:
  447. return self.cache[token]
  448. word = tuple(token[:-1]) + (token[-1] + "</w>",)
  449. pairs = get_pairs(word)
  450. if not pairs:
  451. return token + "</w>"
  452. while True:
  453. bigram = min(pairs, key=lambda pair: self.bpe_ranks.get(pair, float("inf")))
  454. if bigram not in self.bpe_ranks:
  455. break
  456. first, second = bigram
  457. new_word = []
  458. i = 0
  459. while i < len(word):
  460. try:
  461. j = word.index(first, i)
  462. except ValueError:
  463. new_word.extend(word[i:])
  464. break
  465. else:
  466. new_word.extend(word[i:j])
  467. i = j
  468. if word[i] == first and i < len(word) - 1 and word[i + 1] == second:
  469. new_word.append(first + second)
  470. i += 2
  471. else:
  472. new_word.append(word[i])
  473. i += 1
  474. new_word = tuple(new_word)
  475. word = new_word
  476. if len(word) == 1:
  477. break
  478. else:
  479. pairs = get_pairs(word)
  480. word = " ".join(word)
  481. self.cache[token] = word
  482. return word
  483. def _tokenize(self, text):
  484. """Tokenize a string."""
  485. bpe_tokens = []
  486. if self.fix_text is None:
  487. text = " ".join(self.nlp.tokenize(text))
  488. else:
  489. text = whitespace_clean(self.fix_text(text), self.re).lower()
  490. for token in self.re.findall(self.pat, text):
  491. token = "".join(
  492. self.byte_encoder[b] for b in token.encode("utf-8")
  493. ) # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case)
  494. bpe_tokens.extend(bpe_token for bpe_token in self.bpe(token).split(" "))
  495. return bpe_tokens
  496. def _convert_token_to_id(self, token):
  497. """Converts a token (str) in an id using the vocab."""
  498. return self.encoder.get(token, self.encoder.get(self.unk_token))
  499. def _convert_id_to_token(self, index):
  500. """Converts an index (integer) in a token (str) using the vocab."""
  501. return self.decoder.get(index)
  502. def convert_tokens_to_string(self, tokens):
  503. """Converts a sequence of tokens (string) in a single string."""
  504. text = "".join(tokens)
  505. byte_array = bytearray([self.byte_decoder[c] for c in text])
  506. text = (
  507. byte_array.decode("utf-8", errors=self.errors).replace("</w>", " ").strip()
  508. )
  509. return text
  510. def save_resources(self, save_directory):
  511. """
  512. Saves `SentencePiece <https://github.com/google/sentencepiece>`__ file
  513. (ends with '.spm') under `save_directory`.
  514. Args:
  515. save_directory (str): Directory to save files into.
  516. """
  517. for name, file_name in self.resource_files_names.items():
  518. source_path = getattr(self, "_%s" % name)
  519. save_path = os.path.join(save_directory, file_name)
  520. if os.path.abspath(source_path) != os.path.abspath(save_path):
  521. shutil.copyfile(source_path, save_path)