tokenization_gemma.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  1. # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
  2. # This file was automatically generated from src/transformers/models/gemma/modular_gemma.py.
  3. # Do NOT edit this file manually as any edits will be overwritten by the generation of
  4. # the file from the modular. If any change should be done, please apply the change to the
  5. # modular_gemma.py file directly. One of our CI enforces this.
  6. # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
  7. # coding=utf-8
  8. # Copyright 2024 Google Inc. HuggingFace Inc. team. All rights reserved.
  9. #
  10. #
  11. # Licensed under the Apache License, Version 2.0 (the "License");
  12. # you may not use this file except in compliance with the License.
  13. # You may obtain a copy of the License at
  14. #
  15. # http://www.apache.org/licenses/LICENSE-2.0
  16. #
  17. # Unless required by applicable law or agreed to in writing, software
  18. # distributed under the License is distributed on an "AS IS" BASIS,
  19. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  20. # See the License for the specific language governing permissions and
  21. # limitations under the License.
  22. import os
  23. from shutil import copyfile
  24. from typing import TYPE_CHECKING, Any, Optional
  25. import sentencepiece as spm
  26. from ...tokenization_utils import AddedToken, PreTrainedTokenizer
  27. from ...utils import logging
  28. from ...utils.import_utils import requires
  29. if TYPE_CHECKING:
  30. from ...tokenization_utils_base import TextInput
  31. logger = logging.get_logger(__name__)
  32. VOCAB_FILES_NAMES = {"vocab_file": "tokenizer.model"}
  33. SPIECE_UNDERLINE = "▁"
  34. @requires(backends=("sentencepiece",))
  35. class GemmaTokenizer(PreTrainedTokenizer):
  36. """
  37. Construct a Gemma tokenizer. Based on byte-level Byte-Pair-Encoding. The default padding token is unset as there is
  38. no padding token in the original model.
  39. Args:
  40. vocab_file (`str`):
  41. Path to the vocabulary file.
  42. unk_token (`str` or `tokenizers.AddedToken`, *optional*, defaults to `"<unk>"`):
  43. The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
  44. token instead.
  45. bos_token (`str` or `tokenizers.AddedToken`, *optional*, defaults to `"<bos>"`):
  46. The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.
  47. eos_token (`str` or `tokenizers.AddedToken`, *optional*, defaults to `"<eos>"`):
  48. The end of sequence token.
  49. pad_token (`str` or `tokenizers.AddedToken`, *optional*, defaults to `"<pad>"`):
  50. A special token used to make arrays of tokens the same size for batching purpose. Will then be ignored by
  51. attention mechanisms or loss computation.
  52. sp_model_kwargs (`dict[str, Any]`, `Optional`, *optional*):
  53. Will be passed to the `SentencePieceProcessor.__init__()` method. The [Python wrapper for
  54. SentencePiece](https://github.com/google/sentencepiece/tree/master/python) can be used, among other things,
  55. to set:
  56. - `enable_sampling`: Enable subword regularization.
  57. - `nbest_size`: Sampling parameters for unigram. Invalid for BPE-Dropout.
  58. - `nbest_size = {0,1}`: No sampling is performed.
  59. - `nbest_size > 1`: samples from the nbest_size results.
  60. - `nbest_size < 0`: assuming that nbest_size is infinite and samples from the all hypothesis (lattice)
  61. using forward-filtering-and-backward-sampling algorithm.
  62. - `alpha`: Smoothing parameter for unigram sampling, and dropout probability of merge operations for
  63. BPE-dropout.
  64. add_bos_token (`bool`, *optional*, defaults to `True`):
  65. Whether or not to add an `bos_token` at the start of sequences.
  66. add_eos_token (`bool`, *optional*, defaults to `False`):
  67. Whether or not to add an `eos_token` at the end of sequences.
  68. clean_up_tokenization_spaces (`bool`, *optional*, defaults to `False`):
  69. Whether or not to cleanup spaces after decoding, cleanup consists in removing potential artifacts like
  70. extra spaces.
  71. use_default_system_prompt (`bool`, *optional*, defaults to `False`):
  72. Whether or not the default system prompt for Gemma should be used.
  73. spaces_between_special_tokens (`bool`, *optional*, defaults to `False`):
  74. Whether or not to add spaces between special tokens.
  75. """
  76. vocab_files_names = VOCAB_FILES_NAMES
  77. model_input_names = ["input_ids", "attention_mask"]
  78. def __init__(
  79. self,
  80. vocab_file,
  81. unk_token="<unk>",
  82. bos_token="<bos>",
  83. eos_token="<eos>",
  84. pad_token="<pad>",
  85. sp_model_kwargs: Optional[dict[str, Any]] = None,
  86. add_bos_token=True,
  87. add_eos_token=False,
  88. clean_up_tokenization_spaces=False,
  89. use_default_system_prompt=False,
  90. spaces_between_special_tokens=False,
  91. **kwargs,
  92. ):
  93. self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs
  94. bos_token = AddedToken(bos_token, normalized=False, special=True) if isinstance(bos_token, str) else bos_token
  95. eos_token = AddedToken(eos_token, normalized=False, special=True) if isinstance(eos_token, str) else eos_token
  96. unk_token = AddedToken(unk_token, normalized=False, special=True) if isinstance(unk_token, str) else unk_token
  97. pad_token = AddedToken(pad_token, normalized=False, special=True) if isinstance(pad_token, str) else pad_token
  98. self.vocab_file = vocab_file
  99. self.add_bos_token = add_bos_token
  100. self.add_eos_token = add_eos_token
  101. self.use_default_system_prompt = use_default_system_prompt
  102. self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
  103. self.sp_model.Load(vocab_file)
  104. super().__init__(
  105. bos_token=bos_token,
  106. eos_token=eos_token,
  107. unk_token=unk_token,
  108. pad_token=pad_token,
  109. add_bos_token=add_bos_token,
  110. add_eos_token=add_eos_token,
  111. sp_model_kwargs=sp_model_kwargs,
  112. clean_up_tokenization_spaces=clean_up_tokenization_spaces,
  113. use_default_system_prompt=use_default_system_prompt,
  114. spaces_between_special_tokens=spaces_between_special_tokens,
  115. **kwargs,
  116. )
  117. def __getstate__(self):
  118. state = self.__dict__.copy()
  119. state["sp_model"] = None
  120. state["sp_model_proto"] = self.sp_model.serialized_model_proto()
  121. return state
  122. def __setstate__(self, d):
  123. self.__dict__.update(d)
  124. self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
  125. self.sp_model.LoadFromSerializedProto(self.sp_model_proto)
  126. @property
  127. def vocab_size(self):
  128. """Returns vocab size"""
  129. return self.sp_model.get_piece_size()
  130. def get_vocab(self):
  131. """Returns vocab as a dict"""
  132. vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size)}
  133. vocab.update(self.added_tokens_encoder)
  134. return vocab
  135. def tokenize(self, text: "TextInput", **kwargs) -> list[str]:
  136. """
  137. Args:
  138. text: TextInput
  139. Simply calls PreTrainedTokenizer's method
  140. """
  141. return super().tokenize(text, **kwargs)
  142. def _tokenize(self, text, **kwargs):
  143. """
  144. Args:
  145. text: TextInput
  146. Returns a tokenized string. The Gemma tokenizer never adds a prefix space.
  147. """
  148. return self.sp_model.encode(text, out_type=str)
  149. def _convert_token_to_id(self, token):
  150. """Converts a token (str) in an id using the vocab."""
  151. return self.sp_model.piece_to_id(token)
  152. def _convert_id_to_token(self, index):
  153. """Converts an index (integer) in a token (str) using the vocab."""
  154. token = self.sp_model.IdToPiece(index)
  155. return token
  156. def convert_tokens_to_string(self, tokens):
  157. """Converts a sequence of tokens (string) in a single string."""
  158. current_sub_tokens = []
  159. out_string = ""
  160. for token in tokens:
  161. # make sure that special tokens are not decoded using sentencepiece model
  162. if token in self._added_tokens_encoder:
  163. out_string += self.sp_model.decode(current_sub_tokens) + token
  164. current_sub_tokens = []
  165. else:
  166. current_sub_tokens.append(token)
  167. out_string += self.sp_model.decode(current_sub_tokens)
  168. return out_string
  169. def save_vocabulary(self, save_directory, filename_prefix: Optional[str] = None) -> tuple[str]:
  170. """
  171. Save the vocabulary and special tokens file to a directory.
  172. Args:
  173. save_directory (`str`):
  174. The directory in which to save the vocabulary.
  175. Returns:
  176. `Tuple(str)`: Paths to the files saved.
  177. """
  178. if not os.path.isdir(save_directory):
  179. logger.error(f"Vocabulary path ({save_directory}) should be a directory")
  180. return
  181. out_vocab_file = os.path.join(
  182. save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
  183. )
  184. if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file) and os.path.isfile(self.vocab_file):
  185. copyfile(self.vocab_file, out_vocab_file)
  186. elif not os.path.isfile(self.vocab_file):
  187. with open(out_vocab_file, "wb") as fi:
  188. content_spiece_model = self.sp_model.serialized_model_proto()
  189. fi.write(content_spiece_model)
  190. return (out_vocab_file,)
  191. def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
  192. bos_token_id = [self.bos_token_id] if self.add_bos_token else []
  193. eos_token_id = [self.eos_token_id] if self.add_eos_token else []
  194. output = bos_token_id + token_ids_0 + eos_token_id
  195. if token_ids_1 is not None:
  196. output = output + bos_token_id + token_ids_1 + eos_token_id
  197. return output
  198. def get_special_tokens_mask(
  199. self, token_ids_0: list[int], token_ids_1: Optional[list[int]] = None, already_has_special_tokens: bool = False
  200. ) -> list[int]:
  201. """
  202. Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
  203. special tokens using the tokenizer `prepare_for_model` method.
  204. Args:
  205. token_ids_0 (`list[int]`):
  206. List of IDs.
  207. token_ids_1 (`list[int]`, *optional*):
  208. Optional second list of IDs for sequence pairs.
  209. already_has_special_tokens (`bool`, *optional*, defaults to `False`):
  210. Whether or not the token list is already formatted with special tokens for the model.
  211. Returns:
  212. `list[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
  213. """
  214. if already_has_special_tokens:
  215. return super().get_special_tokens_mask(
  216. token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
  217. )
  218. bos_token_id = [1] if self.add_bos_token else []
  219. eos_token_id = [1] if self.add_eos_token else []
  220. if token_ids_1 is None:
  221. return bos_token_id + ([0] * len(token_ids_0)) + eos_token_id
  222. return (
  223. bos_token_id
  224. + ([0] * len(token_ids_0))
  225. + eos_token_id
  226. + bos_token_id
  227. + ([0] * len(token_ids_1))
  228. + eos_token_id
  229. )
  230. def create_token_type_ids_from_sequences(
  231. self, token_ids_0: list[int], token_ids_1: Optional[list[int]] = None
  232. ) -> list[int]:
  233. """
  234. Creates a mask from the two sequences passed to be used in a sequence-pair classification task. An ALBERT
  235. sequence pair mask has the following format:
  236. ```
  237. 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
  238. | first sequence | second sequence |
  239. ```
  240. if token_ids_1 is None, only returns the first portion of the mask (0s).
  241. Args:
  242. token_ids_0 (`list[int]`):
  243. List of ids.
  244. token_ids_1 (`list[int]`, *optional*):
  245. Optional second list of IDs for sequence pairs.
  246. Returns:
  247. `list[int]`: List of [token type IDs](../glossary#token-type-ids) according to the given sequence(s).
  248. """
  249. bos_token_id = [self.bos_token_id] if self.add_bos_token else []
  250. eos_token_id = [self.eos_token_id] if self.add_eos_token else []
  251. output = [0] * len(bos_token_id + token_ids_0 + eos_token_id)
  252. if token_ids_1 is not None:
  253. output += [1] * len(bos_token_id + token_ids_1 + eos_token_id)
  254. return output
  255. def _decode(
  256. self,
  257. token_ids: list[int],
  258. skip_special_tokens: bool = False,
  259. spaces_between_special_tokens: bool = False,
  260. **kwargs,
  261. ) -> str:
  262. sub_texts = []
  263. current_sub_text = []
  264. for ids in token_ids:
  265. if skip_special_tokens and ids in self.all_special_ids:
  266. continue
  267. if ids in self._added_tokens_decoder:
  268. if current_sub_text:
  269. sub_texts.append(self.sp_model.decode(current_sub_text))
  270. sub_texts.append(self._added_tokens_decoder[ids].content)
  271. current_sub_text = []
  272. else:
  273. current_sub_text.append(ids)
  274. if current_sub_text:
  275. sub_texts.append(self.sp_model.decode(current_sub_text))
  276. if spaces_between_special_tokens:
  277. sub_texts = " ".join(sub_texts)
  278. else:
  279. sub_texts = "".join(sub_texts)
  280. return sub_texts.replace(SPIECE_UNDERLINE, " ")
  281. __all__ = ["GemmaTokenizer"]