tokenization_clip.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519
  1. # coding=utf-8
  2. # Copyright 2021 The Open AI Team Authors and The HuggingFace Inc. team.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. """Tokenization classes for CLIP."""
  16. import json
  17. import os
  18. import unicodedata
  19. from functools import lru_cache
  20. from typing import Optional
  21. import regex as re
  22. from ...tokenization_utils import AddedToken, PreTrainedTokenizer, _is_control, _is_punctuation, _is_whitespace
  23. from ...utils import logging
  24. logger = logging.get_logger(__name__)
  25. VOCAB_FILES_NAMES = {
  26. "vocab_file": "vocab.json",
  27. "merges_file": "merges.txt",
  28. }
  29. @lru_cache
  30. def bytes_to_unicode():
  31. """
  32. Returns list of utf-8 byte and a mapping to unicode strings. We specifically avoids mapping to whitespace/control
  33. characters the bpe code barfs on.
  34. The reversible bpe codes work on unicode strings. This means you need a large # of unicode characters in your vocab
  35. if you want to avoid UNKs. When you're at something like a 10B token dataset you end up needing around 5K for
  36. decent coverage. This is a significant percentage of your normal, say, 32K bpe vocab. To avoid that, we want lookup
  37. tables between utf-8 bytes and unicode strings.
  38. """
  39. bs = (
  40. list(range(ord("!"), ord("~") + 1)) + list(range(ord("¡"), ord("¬") + 1)) + list(range(ord("®"), ord("ÿ") + 1))
  41. )
  42. cs = bs[:]
  43. n = 0
  44. for b in range(2**8):
  45. if b not in bs:
  46. bs.append(b)
  47. cs.append(2**8 + n)
  48. n += 1
  49. cs = [chr(n) for n in cs]
  50. return dict(zip(bs, cs))
  51. def get_pairs(word):
  52. """
  53. Return set of symbol pairs in a word.
  54. Word is represented as tuple of symbols (symbols being variable-length strings).
  55. """
  56. pairs = set()
  57. prev_char = word[0]
  58. for char in word[1:]:
  59. pairs.add((prev_char, char))
  60. prev_char = char
  61. return pairs
  62. def whitespace_clean(text):
  63. text = re.sub(r"\s+", " ", text)
  64. text = text.strip()
  65. return text
  66. # Copied from transformers.models.bert.tokenization_bert.whitespace_tokenize
  67. def whitespace_tokenize(text):
  68. """Runs basic whitespace cleaning and splitting on a piece of text."""
  69. text = text.strip()
  70. if not text:
  71. return []
  72. tokens = text.split()
  73. return tokens
  74. # Copied from transformers.models.bert.tokenization_bert.BasicTokenizer
  75. class BasicTokenizer:
  76. """
  77. Constructs a BasicTokenizer that will run basic tokenization (punctuation splitting, lower casing, etc.).
  78. Args:
  79. do_lower_case (`bool`, *optional*, defaults to `True`):
  80. Whether or not to lowercase the input when tokenizing.
  81. never_split (`Iterable`, *optional*):
  82. Collection of tokens which will never be split during tokenization. Only has an effect when
  83. `do_basic_tokenize=True`
  84. tokenize_chinese_chars (`bool`, *optional*, defaults to `True`):
  85. Whether or not to tokenize Chinese characters.
  86. This should likely be deactivated for Japanese (see this
  87. [issue](https://github.com/huggingface/transformers/issues/328)).
  88. strip_accents (`bool`, *optional*):
  89. Whether or not to strip all accents. If this option is not specified, then it will be determined by the
  90. value for `lowercase` (as in the original BERT).
  91. do_split_on_punc (`bool`, *optional*, defaults to `True`):
  92. In some instances we want to skip the basic punctuation splitting so that later tokenization can capture
  93. the full context of the words, such as contractions.
  94. """
  95. def __init__(
  96. self,
  97. do_lower_case=True,
  98. never_split=None,
  99. tokenize_chinese_chars=True,
  100. strip_accents=None,
  101. do_split_on_punc=True,
  102. ):
  103. if never_split is None:
  104. never_split = []
  105. self.do_lower_case = do_lower_case
  106. self.never_split = set(never_split)
  107. self.tokenize_chinese_chars = tokenize_chinese_chars
  108. self.strip_accents = strip_accents
  109. self.do_split_on_punc = do_split_on_punc
  110. def tokenize(self, text, never_split=None):
  111. """
  112. Basic Tokenization of a piece of text. For sub-word tokenization, see WordPieceTokenizer.
  113. Args:
  114. never_split (`List[str]`, *optional*)
  115. Kept for backward compatibility purposes. Now implemented directly at the base class level (see
  116. [`PreTrainedTokenizer.tokenize`]) List of token not to split.
  117. """
  118. # union() returns a new set by concatenating the two sets.
  119. never_split = self.never_split.union(set(never_split)) if never_split else self.never_split
  120. text = self._clean_text(text)
  121. # This was added on November 1st, 2018 for the multilingual and Chinese
  122. # models. This is also applied to the English models now, but it doesn't
  123. # matter since the English models were not trained on any Chinese data
  124. # and generally don't have any Chinese data in them (there are Chinese
  125. # characters in the vocabulary because Wikipedia does have some Chinese
  126. # words in the English Wikipedia.).
  127. if self.tokenize_chinese_chars:
  128. text = self._tokenize_chinese_chars(text)
  129. # prevents treating the same character with different unicode codepoints as different characters
  130. unicode_normalized_text = unicodedata.normalize("NFC", text)
  131. orig_tokens = whitespace_tokenize(unicode_normalized_text)
  132. split_tokens = []
  133. for token in orig_tokens:
  134. if token not in never_split:
  135. if self.do_lower_case:
  136. token = token.lower()
  137. if self.strip_accents is not False:
  138. token = self._run_strip_accents(token)
  139. elif self.strip_accents:
  140. token = self._run_strip_accents(token)
  141. split_tokens.extend(self._run_split_on_punc(token, never_split))
  142. output_tokens = whitespace_tokenize(" ".join(split_tokens))
  143. return output_tokens
  144. def _run_strip_accents(self, text):
  145. """Strips accents from a piece of text."""
  146. text = unicodedata.normalize("NFD", text)
  147. output = []
  148. for char in text:
  149. cat = unicodedata.category(char)
  150. if cat == "Mn":
  151. continue
  152. output.append(char)
  153. return "".join(output)
  154. def _run_split_on_punc(self, text, never_split=None):
  155. """Splits punctuation on a piece of text."""
  156. if not self.do_split_on_punc or (never_split is not None and text in never_split):
  157. return [text]
  158. chars = list(text)
  159. i = 0
  160. start_new_word = True
  161. output = []
  162. while i < len(chars):
  163. char = chars[i]
  164. if _is_punctuation(char):
  165. output.append([char])
  166. start_new_word = True
  167. else:
  168. if start_new_word:
  169. output.append([])
  170. start_new_word = False
  171. output[-1].append(char)
  172. i += 1
  173. return ["".join(x) for x in output]
  174. def _tokenize_chinese_chars(self, text):
  175. """Adds whitespace around any CJK character."""
  176. output = []
  177. for char in text:
  178. cp = ord(char)
  179. if self._is_chinese_char(cp):
  180. output.append(" ")
  181. output.append(char)
  182. output.append(" ")
  183. else:
  184. output.append(char)
  185. return "".join(output)
  186. def _is_chinese_char(self, cp):
  187. """Checks whether CP is the codepoint of a CJK character."""
  188. # This defines a "chinese character" as anything in the CJK Unicode block:
  189. # https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block)
  190. #
  191. # Note that the CJK Unicode block is NOT all Japanese and Korean characters,
  192. # despite its name. The modern Korean Hangul alphabet is a different block,
  193. # as is Japanese Hiragana and Katakana. Those alphabets are used to write
  194. # space-separated words, so they are not treated specially and handled
  195. # like the all of the other languages.
  196. if (
  197. (cp >= 0x4E00 and cp <= 0x9FFF)
  198. or (cp >= 0x3400 and cp <= 0x4DBF)
  199. or (cp >= 0x20000 and cp <= 0x2A6DF)
  200. or (cp >= 0x2A700 and cp <= 0x2B73F)
  201. or (cp >= 0x2B740 and cp <= 0x2B81F)
  202. or (cp >= 0x2B820 and cp <= 0x2CEAF)
  203. or (cp >= 0xF900 and cp <= 0xFAFF)
  204. or (cp >= 0x2F800 and cp <= 0x2FA1F)
  205. ):
  206. return True
  207. return False
  208. def _clean_text(self, text):
  209. """Performs invalid character removal and whitespace cleanup on text."""
  210. output = []
  211. for char in text:
  212. cp = ord(char)
  213. if cp == 0 or cp == 0xFFFD or _is_control(char):
  214. continue
  215. if _is_whitespace(char):
  216. output.append(" ")
  217. else:
  218. output.append(char)
  219. return "".join(output)
  220. class CLIPTokenizer(PreTrainedTokenizer):
  221. """
  222. Construct a CLIP tokenizer. Based on byte-level Byte-Pair-Encoding.
  223. This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
  224. this superclass for more information regarding those methods.
  225. Args:
  226. vocab_file (`str`):
  227. Path to the vocabulary file.
  228. merges_file (`str`):
  229. Path to the merges file.
  230. errors (`str`, *optional*, defaults to `"replace"`):
  231. Paradigm to follow when decoding bytes to UTF-8. See
  232. [bytes.decode](https://docs.python.org/3/library/stdtypes.html#bytes.decode) for more information.
  233. unk_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
  234. The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
  235. token instead.
  236. bos_token (`str`, *optional*, defaults to `"<|startoftext|>"`):
  237. The beginning of sequence token.
  238. eos_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
  239. The end of sequence token.
  240. pad_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
  241. The token used for padding, for example when batching sequences of different lengths.
  242. """
  243. vocab_files_names = VOCAB_FILES_NAMES
  244. model_input_names = ["input_ids", "attention_mask"]
  245. def __init__(
  246. self,
  247. vocab_file,
  248. merges_file,
  249. errors="replace",
  250. unk_token="<|endoftext|>",
  251. bos_token="<|startoftext|>",
  252. eos_token="<|endoftext|>",
  253. pad_token="<|endoftext|>", # hack to enable padding
  254. **kwargs,
  255. ):
  256. bos_token = AddedToken(bos_token, lstrip=False, rstrip=False) if isinstance(bos_token, str) else bos_token
  257. eos_token = AddedToken(eos_token, lstrip=False, rstrip=False) if isinstance(eos_token, str) else eos_token
  258. unk_token = AddedToken(unk_token, lstrip=False, rstrip=False) if isinstance(unk_token, str) else unk_token
  259. try:
  260. import ftfy
  261. self.fix_text = ftfy.fix_text
  262. except ImportError:
  263. logger.info("ftfy or spacy is not installed using custom BasicTokenizer instead of ftfy.")
  264. self.nlp = BasicTokenizer(strip_accents=False, do_split_on_punc=False)
  265. self.fix_text = None
  266. with open(vocab_file, encoding="utf-8") as vocab_handle:
  267. self.encoder = json.load(vocab_handle)
  268. self.decoder = {v: k for k, v in self.encoder.items()}
  269. self.errors = errors # how to handle errors in decoding
  270. self.byte_encoder = bytes_to_unicode()
  271. self.byte_decoder = {v: k for k, v in self.byte_encoder.items()}
  272. with open(merges_file, encoding="utf-8") as merges_handle:
  273. bpe_merges = merges_handle.read().strip().split("\n")[1 : 49152 - 256 - 2 + 1]
  274. bpe_merges = [tuple(merge.split()) for merge in bpe_merges]
  275. self.bpe_ranks = dict(zip(bpe_merges, range(len(bpe_merges))))
  276. self.cache = {"<|startoftext|>": "<|startoftext|>", "<|endoftext|>": "<|endoftext|>"}
  277. self.pat = re.compile(
  278. r"""<\|startoftext\|>|<\|endoftext\|>|'s|'t|'re|'ve|'m|'ll|'d|[\p{L}]+|[\p{N}]|[^\s\p{L}\p{N}]+""",
  279. re.IGNORECASE,
  280. )
  281. super().__init__(
  282. errors=errors,
  283. unk_token=unk_token,
  284. bos_token=bos_token,
  285. eos_token=eos_token,
  286. pad_token=pad_token,
  287. **kwargs,
  288. )
  289. @property
  290. def vocab_size(self):
  291. return len(self.encoder)
  292. def get_vocab(self):
  293. return dict(self.encoder, **self.added_tokens_encoder)
  294. def build_inputs_with_special_tokens(
  295. self, token_ids_0: list[int], token_ids_1: Optional[list[int]] = None
  296. ) -> list[int]:
  297. """
  298. Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
  299. adding special tokens. A CLIP sequence has the following format:
  300. - single sequence: `<|startoftext|> X <|endoftext|>`
  301. Pairs of sequences are not the expected use case, but they will be handled without a separator.
  302. Args:
  303. token_ids_0 (`list[int]`):
  304. List of IDs to which the special tokens will be added.
  305. token_ids_1 (`list[int]`, *optional*):
  306. Optional second list of IDs for sequence pairs.
  307. Returns:
  308. `list[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
  309. """
  310. bos_token = [self.bos_token_id]
  311. eos_token = [self.eos_token_id]
  312. if token_ids_1 is None:
  313. return bos_token + token_ids_0 + eos_token
  314. return bos_token + token_ids_0 + eos_token + eos_token + token_ids_1 + eos_token
  315. def get_special_tokens_mask(
  316. self, token_ids_0: list[int], token_ids_1: Optional[list[int]] = None, already_has_special_tokens: bool = False
  317. ) -> list[int]:
  318. """
  319. Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
  320. special tokens using the tokenizer `prepare_for_model` method.
  321. Args:
  322. token_ids_0 (`list[int]`):
  323. List of IDs.
  324. token_ids_1 (`list[int]`, *optional*):
  325. Optional second list of IDs for sequence pairs.
  326. already_has_special_tokens (`bool`, *optional*, defaults to `False`):
  327. Whether or not the token list is already formatted with special tokens for the model.
  328. Returns:
  329. `list[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
  330. """
  331. if already_has_special_tokens:
  332. return super().get_special_tokens_mask(
  333. token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
  334. )
  335. if token_ids_1 is None:
  336. return [1] + ([0] * len(token_ids_0)) + [1]
  337. return [1] + ([0] * len(token_ids_0)) + [1] + [1] + ([0] * len(token_ids_1)) + [1]
  338. def create_token_type_ids_from_sequences(
  339. self, token_ids_0: list[int], token_ids_1: Optional[list[int]] = None
  340. ) -> list[int]:
  341. """
  342. Create a mask from the two sequences passed. CLIP does not make use of token type ids, therefore a list of
  343. zeros is returned.
  344. Args:
  345. token_ids_0 (`list[int]`):
  346. List of IDs.
  347. token_ids_1 (`list[int]`, *optional*):
  348. Optional second list of IDs for sequence pairs.
  349. Returns:
  350. `list[int]`: List of zeros.
  351. """
  352. bos_token = [self.bos_token_id]
  353. eos_token = [self.eos_token_id]
  354. if token_ids_1 is None:
  355. return len(bos_token + token_ids_0 + eos_token) * [0]
  356. return len(bos_token + token_ids_0 + eos_token + eos_token + token_ids_1 + eos_token) * [0]
  357. def bpe(self, token):
  358. if token in self.cache:
  359. return self.cache[token]
  360. word = tuple(token[:-1]) + (token[-1] + "</w>",)
  361. pairs = get_pairs(word)
  362. if not pairs:
  363. return token + "</w>"
  364. while True:
  365. bigram = min(pairs, key=lambda pair: self.bpe_ranks.get(pair, float("inf")))
  366. if bigram not in self.bpe_ranks:
  367. break
  368. first, second = bigram
  369. new_word = []
  370. i = 0
  371. while i < len(word):
  372. try:
  373. j = word.index(first, i)
  374. except ValueError:
  375. new_word.extend(word[i:])
  376. break
  377. else:
  378. new_word.extend(word[i:j])
  379. i = j
  380. if word[i] == first and i < len(word) - 1 and word[i + 1] == second:
  381. new_word.append(first + second)
  382. i += 2
  383. else:
  384. new_word.append(word[i])
  385. i += 1
  386. new_word = tuple(new_word)
  387. word = new_word
  388. if len(word) == 1:
  389. break
  390. else:
  391. pairs = get_pairs(word)
  392. word = " ".join(word)
  393. self.cache[token] = word
  394. return word
  395. def _tokenize(self, text):
  396. """Tokenize a string."""
  397. bpe_tokens = []
  398. if self.fix_text is None:
  399. text = " ".join(self.nlp.tokenize(text))
  400. else:
  401. text = whitespace_clean(self.fix_text(text)).lower()
  402. for token in re.findall(self.pat, text):
  403. token = "".join(
  404. self.byte_encoder[b] for b in token.encode("utf-8")
  405. ) # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case)
  406. bpe_tokens.extend(bpe_token for bpe_token in self.bpe(token).split(" "))
  407. return bpe_tokens
  408. def _convert_token_to_id(self, token):
  409. """Converts a token (str) in an id using the vocab."""
  410. return self.encoder.get(token, self.encoder.get(self.unk_token))
  411. def _convert_id_to_token(self, index):
  412. """Converts an index (integer) in a token (str) using the vocab."""
  413. return self.decoder.get(index)
  414. def convert_tokens_to_string(self, tokens):
  415. """Converts a sequence of tokens (string) in a single string."""
  416. text = "".join(tokens)
  417. byte_array = bytearray([self.byte_decoder[c] for c in text])
  418. text = byte_array.decode("utf-8", errors=self.errors).replace("</w>", " ").strip()
  419. return text
  420. def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> tuple[str]:
  421. if not os.path.isdir(save_directory):
  422. logger.error(f"Vocabulary path ({save_directory}) should be a directory")
  423. return
  424. vocab_file = os.path.join(
  425. save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
  426. )
  427. merge_file = os.path.join(
  428. save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["merges_file"]
  429. )
  430. with open(vocab_file, "w", encoding="utf-8") as f:
  431. f.write(json.dumps(self.encoder, indent=2, sort_keys=True, ensure_ascii=False) + "\n")
  432. index = 0
  433. with open(merge_file, "w", encoding="utf-8") as writer:
  434. writer.write("#version: 0.2\n")
  435. for bpe_tokens, token_index in sorted(self.bpe_ranks.items(), key=lambda kv: kv[1]):
  436. if index != token_index:
  437. logger.warning(
  438. f"Saving vocabulary to {merge_file}: BPE merge indices are not consecutive."
  439. " Please check that the tokenizer is not corrupted!"
  440. )
  441. index = token_index
  442. writer.write(" ".join(bpe_tokens) + "\n")
  443. index += 1
  444. return vocab_file, merge_file
  445. __all__ = ["CLIPTokenizer"]