tokenization_cpm.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  1. # Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
  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. """Tokenization classes."""
  15. import os
  16. import unicodedata
  17. from shutil import copyfile
  18. from typing import Any
  19. import sentencepiece as spm
  20. from ...tokenization_python import AddedToken, PreTrainedTokenizer
  21. from ...utils import SPIECE_UNDERLINE, logging
  22. from ...utils.import_utils import requires
  23. logger = logging.get_logger(__name__)
  24. VOCAB_FILES_NAMES = {"vocab_file": "spiece.model"}
  25. @requires(backends=("sentencepiece",))
  26. class CpmTokenizer(PreTrainedTokenizer):
  27. """Runs pre-tokenization with Jieba-RS segmentation tool. It is used in CPM models."""
  28. vocab_files_names = VOCAB_FILES_NAMES
  29. def __init__(
  30. self,
  31. vocab_file,
  32. do_lower_case=False,
  33. remove_space=True,
  34. keep_accents=False,
  35. bos_token="<s>",
  36. eos_token="</s>",
  37. unk_token="<unk>",
  38. sep_token="<sep>",
  39. pad_token="<pad>",
  40. cls_token="<cls>",
  41. mask_token="<mask>",
  42. additional_special_tokens=["<eop>", "<eod>"],
  43. sp_model_kwargs: dict[str, Any] | None = None,
  44. **kwargs,
  45. ) -> None:
  46. """
  47. Construct a CPM tokenizer. Based on [Jieba-RS](https://pypi.org/project/rjieba/) and
  48. [SentencePiece](https://github.com/google/sentencepiece).
  49. This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should
  50. refer to this superclass for more information regarding those methods.
  51. Args:
  52. vocab_file (`str`):
  53. [SentencePiece](https://github.com/google/sentencepiece) file (generally has a .spm extension) that
  54. contains the vocabulary necessary to instantiate a tokenizer.
  55. do_lower_case (`bool`, *optional*, defaults to `True`):
  56. Whether to lowercase the input when tokenizing.
  57. remove_space (`bool`, *optional*, defaults to `True`):
  58. Whether to strip the text when tokenizing (removing excess spaces before and after the string).
  59. keep_accents (`bool`, *optional*, defaults to `False`):
  60. Whether to keep accents when tokenizing.
  61. bos_token (`str`, *optional*, defaults to `"<s>"`):
  62. The beginning of sequence token that was used during pretraining. Can be used a sequence classifier
  63. token.
  64. <Tip>
  65. When building a sequence using special tokens, this is not the token that is used for the beginning of
  66. sequence. The token used is the `cls_token`.
  67. </Tip>
  68. eos_token (`str`, *optional*, defaults to `"</s>"`):
  69. The end of sequence token.
  70. <Tip>
  71. When building a sequence using special tokens, this is not the token that is used for the end of
  72. sequence. The token used is the `sep_token`.
  73. </Tip>
  74. unk_token (`str`, *optional*, defaults to `"<unk>"`):
  75. The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be
  76. this token instead.
  77. sep_token (`str`, *optional*, defaults to `"<sep>"`):
  78. The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences
  79. for sequence classification or for a text and a question for question answering. It is also used as the
  80. last token of a sequence built with special tokens.
  81. pad_token (`str`, *optional*, defaults to `"<pad>"`):
  82. The token used for padding, for example when batching sequences of different lengths.
  83. cls_token (`str`, *optional*, defaults to `"<cls>"`):
  84. The classifier token which is used when doing sequence classification (classification of the whole
  85. sequence instead of per-token classification). It is the first token of the sequence when built with
  86. special tokens.
  87. mask_token (`str`, *optional*, defaults to `"<mask>"`):
  88. The token used for masking values. This is the token used when training this model with masked language
  89. modeling. This is the token which the model will try to predict.
  90. additional_special_tokens (`list[str]`, *optional*, defaults to `["<eop>", "<eod>"]`):
  91. Additional special tokens used by the tokenizer.
  92. Attributes:
  93. sp_model (`SentencePieceProcessor`):
  94. The *SentencePiece* processor that is used for every conversion (string, tokens and IDs).
  95. """
  96. # Mask token behave like a normal word, i.e. include the space before it
  97. mask_token = AddedToken(mask_token, lstrip=True, rstrip=False) if isinstance(mask_token, str) else mask_token
  98. self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs
  99. self.do_lower_case = do_lower_case
  100. self.remove_space = remove_space
  101. self.keep_accents = keep_accents
  102. self.vocab_file = vocab_file
  103. self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
  104. self.sp_model.Load(vocab_file)
  105. try:
  106. import rjieba
  107. except ModuleNotFoundError as error:
  108. raise error.__class__(
  109. "You need to install rjieba to use CpmTokenizer or CpmTokenizerFast. "
  110. "See https://pypi.org/project/rjieba/ for installation."
  111. )
  112. self.jieba = rjieba
  113. self.translator = str.maketrans(" \n", "\u2582\u2583")
  114. super().__init__(
  115. do_lower_case=do_lower_case,
  116. remove_space=remove_space,
  117. keep_accents=keep_accents,
  118. bos_token=bos_token,
  119. eos_token=eos_token,
  120. unk_token=unk_token,
  121. sep_token=sep_token,
  122. pad_token=pad_token,
  123. cls_token=cls_token,
  124. mask_token=mask_token,
  125. additional_special_tokens=additional_special_tokens,
  126. sp_model_kwargs=self.sp_model_kwargs,
  127. **kwargs,
  128. )
  129. self._pad_token_type_id = 3
  130. @property
  131. def vocab_size(self):
  132. return len(self.sp_model)
  133. def get_vocab(self):
  134. vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size)}
  135. vocab.update(self.added_tokens_encoder)
  136. return vocab
  137. def __getstate__(self):
  138. state = self.__dict__.copy()
  139. state["sp_model"] = None
  140. return state
  141. def __setstate__(self, d):
  142. self.__dict__ = d
  143. # for backward compatibility
  144. if not hasattr(self, "sp_model_kwargs"):
  145. self.sp_model_kwargs = {}
  146. self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
  147. self.sp_model.Load(self.vocab_file)
  148. def preprocess_text(self, inputs):
  149. if self.remove_space:
  150. outputs = " ".join(inputs.strip().split())
  151. else:
  152. outputs = inputs
  153. outputs = outputs.replace("``", '"').replace("''", '"')
  154. if not self.keep_accents:
  155. outputs = unicodedata.normalize("NFKD", outputs)
  156. outputs = "".join([c for c in outputs if not unicodedata.combining(c)])
  157. if self.do_lower_case:
  158. outputs = outputs.lower()
  159. return outputs
  160. def _tokenize(self, text: str) -> list[str]:
  161. """Tokenize a string."""
  162. text = self.preprocess_text(text)
  163. pieces = self.sp_model.encode(text, out_type=str)
  164. new_pieces = []
  165. for piece in pieces:
  166. if len(piece) > 1 and piece[-1] == "," and piece[-2].isdigit():
  167. cur_pieces = self.sp_model.EncodeAsPieces(piece[:-1].replace(SPIECE_UNDERLINE, ""))
  168. if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE:
  169. if len(cur_pieces[0]) == 1:
  170. cur_pieces = cur_pieces[1:]
  171. else:
  172. cur_pieces[0] = cur_pieces[0][1:]
  173. cur_pieces.append(piece[-1])
  174. new_pieces.extend(cur_pieces)
  175. else:
  176. new_pieces.append(piece)
  177. return new_pieces
  178. def _convert_token_to_id(self, token):
  179. """Converts a token (str) in an id using the vocab."""
  180. return self.sp_model.PieceToId(token)
  181. def _convert_id_to_token(self, index):
  182. """Converts an index (integer) in a token (str) using the vocab."""
  183. return self.sp_model.IdToPiece(index)
  184. def convert_tokens_to_string(self, tokens):
  185. """Converts a sequence of tokens (strings for sub-words) in a single string."""
  186. out_string = "".join(tokens).replace(SPIECE_UNDERLINE, " ").strip()
  187. return out_string
  188. def build_inputs_with_special_tokens(
  189. self, token_ids_0: list[int], token_ids_1: list[int] | None = None
  190. ) -> list[int]:
  191. """
  192. Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
  193. adding special tokens. An XLNet sequence has the following format:
  194. - single sequence: `X <sep> <cls>`
  195. - pair of sequences: `A <sep> B <sep> <cls>`
  196. Args:
  197. token_ids_0 (`list[int]`):
  198. List of IDs to which the special tokens will be added.
  199. token_ids_1 (`list[int]`, *optional*):
  200. Optional second list of IDs for sequence pairs.
  201. Returns:
  202. `list[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
  203. """
  204. sep = [self.sep_token_id]
  205. cls = [self.cls_token_id]
  206. if token_ids_1 is None:
  207. return token_ids_0 + sep + cls
  208. return token_ids_0 + sep + token_ids_1 + sep + cls
  209. def get_special_tokens_mask(
  210. self, token_ids_0: list[int], token_ids_1: list[int] | None = None, already_has_special_tokens: bool = False
  211. ) -> list[int]:
  212. """
  213. Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
  214. special tokens using the tokenizer `prepare_for_model` method.
  215. Args:
  216. token_ids_0 (`list[int]`):
  217. List of IDs.
  218. token_ids_1 (`list[int]`, *optional*):
  219. Optional second list of IDs for sequence pairs.
  220. already_has_special_tokens (`bool`, *optional*, defaults to `False`):
  221. Whether or not the token list is already formatted with special tokens for the model.
  222. Returns:
  223. `list[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
  224. """
  225. if already_has_special_tokens:
  226. return super().get_special_tokens_mask(
  227. token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
  228. )
  229. if token_ids_1 is not None:
  230. return ([0] * len(token_ids_0)) + [1] + ([0] * len(token_ids_1)) + [1, 1]
  231. return ([0] * len(token_ids_0)) + [1, 1]
  232. def create_token_type_ids_from_sequences(
  233. self, token_ids_0: list[int], token_ids_1: list[int] | None = None
  234. ) -> list[int]:
  235. """
  236. Create a mask from the two sequences passed to be used in a sequence-pair classification task. An XLNet
  237. sequence pair mask has the following format:
  238. ```
  239. 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
  240. | first sequence | second sequence |
  241. ```
  242. If `token_ids_1` is `None`, this method only returns the first portion of the mask (0s).
  243. Args:
  244. token_ids_0 (`list[int]`):
  245. List of IDs.
  246. token_ids_1 (`list[int]`, *optional*):
  247. Optional second list of IDs for sequence pairs.
  248. Returns:
  249. `list[int]`: List of [token type IDs](../glossary#token-type-ids) according to the given sequence(s).
  250. """
  251. sep = [self.sep_token_id]
  252. cls_segment_id = [2]
  253. if token_ids_1 is None:
  254. return len(token_ids_0 + sep) * [0] + cls_segment_id
  255. return len(token_ids_0 + sep) * [0] + len(token_ids_1 + sep) * [1] + cls_segment_id
  256. def save_vocabulary(self, save_directory: str, filename_prefix: str | None = None) -> tuple[str]:
  257. if not os.path.isdir(save_directory):
  258. logger.error(f"Vocabulary path ({save_directory}) should be a directory")
  259. return
  260. out_vocab_file = os.path.join(
  261. save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
  262. )
  263. if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file) and os.path.isfile(self.vocab_file):
  264. copyfile(self.vocab_file, out_vocab_file)
  265. elif not os.path.isfile(self.vocab_file):
  266. with open(out_vocab_file, "wb") as fi:
  267. content_spiece_model = self.sp_model.serialized_model_proto()
  268. fi.write(content_spiece_model)
  269. return (out_vocab_file,)
  270. def _decode(self, *args, **kwargs):
  271. text = super()._decode(*args, **kwargs)
  272. text = text.replace(" ", "").replace("\u2582", " ").replace("\u2583", "\n")
  273. return text
  274. __all__ = ["CpmTokenizer"]