|
| 1 | +# Copyright 2019 The Texar 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 | +""" |
| 15 | +Pre-trained T5 tokenizer. |
| 16 | +""" |
| 17 | + |
| 18 | +from typing import Any, Dict, Optional |
| 19 | + |
| 20 | +import os |
| 21 | +import re |
| 22 | + |
| 23 | +from texar.torch.data.tokenizers.sentencepiece_tokenizer \ |
| 24 | + import SentencePieceTokenizer |
| 25 | +from texar.torch.modules.pretrained.t5 import PretrainedT5Mixin |
| 26 | + |
| 27 | +__all__ = [ |
| 28 | + 'T5Tokenizer', |
| 29 | +] |
| 30 | + |
| 31 | + |
| 32 | +class T5Tokenizer(SentencePieceTokenizer, PretrainedT5Mixin): |
| 33 | + r"""Pre-trained T5 Tokenizer. |
| 34 | +
|
| 35 | + Args: |
| 36 | + pretrained_model_name (optional): a `str`, the name of |
| 37 | + pre-trained model (e.g., `T5-Small`). Please refer to |
| 38 | + :class:`~texar.torch.modules.PretrainedT5Mixin` for |
| 39 | + all supported models. |
| 40 | + If None, the model name in :attr:`hparams` is used. |
| 41 | + cache_dir (optional): the path to a folder in which the |
| 42 | + pre-trained models will be cached. If `None` (default), |
| 43 | + a default directory (``texar_data`` folder under user's home |
| 44 | + directory) will be used. |
| 45 | + hparams (dict or HParams, optional): Hyperparameters. Missing |
| 46 | + hyperparameters will be set to default values. See |
| 47 | + :meth:`default_hparams` for the hyperparameter structure |
| 48 | + and default values. |
| 49 | + """ |
| 50 | + |
| 51 | + _IS_PRETRAINED = True |
| 52 | + |
| 53 | + _VOCAB_FILE_NAMES = { |
| 54 | + 'vocab_file': 'sentencepiece.model' |
| 55 | + } |
| 56 | + |
| 57 | + _MAX_INPUT_SIZE = { |
| 58 | + 'T5-Small': 512, |
| 59 | + 'T5-Base': 512, |
| 60 | + 'T5-Large': 512, |
| 61 | + 'T5-3B': 512, |
| 62 | + 'T5-11B': 512 |
| 63 | + } |
| 64 | + |
| 65 | + def __init__(self, |
| 66 | + pretrained_model_name: Optional[str] = None, |
| 67 | + cache_dir: Optional[str] = None, |
| 68 | + hparams=None): |
| 69 | + |
| 70 | + self.load_pretrained_config(pretrained_model_name, cache_dir, hparams) |
| 71 | + |
| 72 | + if self.pretrained_model_dir is not None: |
| 73 | + assert self.pretrained_model_name is not None |
| 74 | + vocab_file = os.path.join(self.pretrained_model_dir, |
| 75 | + self._VOCAB_FILE_NAMES['vocab_file']) |
| 76 | + |
| 77 | + if self._MAX_INPUT_SIZE.get(self.pretrained_model_name): |
| 78 | + self.max_len = self._MAX_INPUT_SIZE[self.pretrained_model_name] |
| 79 | + setattr(self.hparams, 'vocab_file', vocab_file) |
| 80 | + else: |
| 81 | + if self.hparams.get('max_len'): |
| 82 | + self.max_len = self.hparams['max_len'] |
| 83 | + |
| 84 | + # Add extra_ids to the special token list |
| 85 | + additional_special_tokens = [] |
| 86 | + extra_ids = self.hparams['extra_ids'] |
| 87 | + if extra_ids > 0: |
| 88 | + additional_special_tokens.extend( |
| 89 | + ["<extra_id_{}>".format(i) for i in range(extra_ids)]) |
| 90 | + |
| 91 | + setattr(self.hparams, 'additional_special_tokens', |
| 92 | + additional_special_tokens) |
| 93 | + |
| 94 | + super().__init__(hparams=None) |
| 95 | + |
| 96 | + @staticmethod |
| 97 | + def default_hparams() -> Dict[str, Any]: |
| 98 | + r"""Returns a dictionary of hyperparameters with default values. |
| 99 | +
|
| 100 | + * The tokenizer is determined by the constructor argument |
| 101 | + :attr:`pretrained_model_name` if it's specified. In this case, |
| 102 | + `hparams` are ignored. |
| 103 | + * Otherwise, the tokenizer is determined by |
| 104 | + `hparams['pretrained_model_name']` if it's specified. All other |
| 105 | + configurations in `hparams` are ignored. |
| 106 | + * If the above two are `None`, the tokenizer is defined by the |
| 107 | + configurations in `hparams`. |
| 108 | +
|
| 109 | + .. code-block:: python |
| 110 | +
|
| 111 | + { |
| 112 | + "pretrained_model_name": "T5-Small", |
| 113 | + "vocab_file": None, |
| 114 | + "max_len": 512, |
| 115 | + "bos_token": None, |
| 116 | + "eos_token": "</s>", |
| 117 | + "unk_token": "<unk>", |
| 118 | + "pad_token": "<pad>", |
| 119 | + "extra_ids": 100, |
| 120 | + "additional_special_tokens": [], |
| 121 | + "name": "t5_tokenizer", |
| 122 | + } |
| 123 | +
|
| 124 | + Here: |
| 125 | +
|
| 126 | + `"pretrained_model_name"`: str or None |
| 127 | + The name of the pre-trained T5 model. |
| 128 | +
|
| 129 | + `"vocab_file"`: str or None |
| 130 | + The path to a sentencepiece vocabulary file. |
| 131 | +
|
| 132 | + `"max_len"`: int or None |
| 133 | + The maximum sequence length that this model might ever be used with. |
| 134 | +
|
| 135 | + `"bos_token"`: str or None |
| 136 | + Beginning of sentence token. Set None to disable ``bos_token``. |
| 137 | +
|
| 138 | + `"eos_token"`: str |
| 139 | + End of sentence token. Set None to disable ``eos_token``. |
| 140 | +
|
| 141 | + `"unk_token"`: str |
| 142 | + Unknown token. Set None to disable ``unk_token``. |
| 143 | +
|
| 144 | + `"pad_token"`: str |
| 145 | + Padding token. Set None to disable ``pad_token``. |
| 146 | +
|
| 147 | + `"extra_ids"`: int |
| 148 | + Add a number of extra ids added to the end of the vocabulary for |
| 149 | + use as sentinels. These tokens are accessible as `<extra_id_{%d}>` |
| 150 | + where `{%d}` is a number between 0 and extra_ids-1. Extra tokens |
| 151 | + are indexed from the end of the vocabulary up to beginning |
| 152 | + (<extra_id_0> is the last token in the vocabulary) (like in T5 |
| 153 | + preprocessing) see: |
| 154 | + `https://github.com/google-research/text-to-text-transfer-transformer/blob/9fd7b14a769417be33bc6c850f9598764913c833/t5/data/preprocessors.py#L2117` |
| 155 | +
|
| 156 | + `"additional_special_tokens"`: list |
| 157 | + A list of additional special tokens. |
| 158 | +
|
| 159 | + `"name"`: str |
| 160 | + Name of the tokenizer. |
| 161 | + """ |
| 162 | + return { |
| 163 | + 'pretrained_model_name': 'T5-Small', |
| 164 | + 'vocab_file': None, |
| 165 | + 'max_len': 512, |
| 166 | + 'bos_token': None, |
| 167 | + 'eos_token': '</s>', |
| 168 | + 'unk_token': '<unk>', |
| 169 | + 'pad_token': '<pad>', |
| 170 | + 'extra_ids': 100, |
| 171 | + 'additional_special_tokens': [], |
| 172 | + 'name': 't5_tokenizer', |
| 173 | + '@no_typecheck': ['pretrained_model_name'], |
| 174 | + } |
| 175 | + |
| 176 | + @property |
| 177 | + def vocab_size(self) -> int: |
| 178 | + return len(self.sp_model) + self.hparams['extra_ids'] |
| 179 | + |
| 180 | + def _map_token_to_id(self, token: str) -> int: |
| 181 | + if token.startswith("<extra_id_"): |
| 182 | + match = re.match(r"<extra_id_(\d+)>", token) |
| 183 | + num = int(match.group(1)) # type: ignore |
| 184 | + return self.vocab_size - num - 1 |
| 185 | + return self.sp_model.PieceToId(token) |
| 186 | + |
| 187 | + def _map_id_to_token(self, index: int) -> str: |
| 188 | + if index < self.sp_model.get_piece_size(): |
| 189 | + token = self.sp_model.IdToPiece(index) |
| 190 | + else: |
| 191 | + token = "<extra_id_{}>".format(self.vocab_size - 1 - index) |
| 192 | + return token |
0 commit comments