tokenizer.py 10.4 KB
Newer Older
1
2
# SPDX-License-Identifier: Apache-2.0

3
import contextlib
4
import copy
5
import os
6
import warnings
7
from functools import lru_cache
8
from pathlib import Path
9
from types import MethodType
10
from typing import TYPE_CHECKING, Any, Optional, Union
11

12
import huggingface_hub
13
from transformers import (AutoTokenizer, PreTrainedTokenizer,
14
15
                          PreTrainedTokenizerFast)

16
from vllm.envs import VLLM_USE_MODELSCOPE
Woosuk Kwon's avatar
Woosuk Kwon committed
17
from vllm.logger import init_logger
18
from vllm.lora.request import LoRARequest
19
20
from vllm.transformers_utils.tokenizer_base import (TokenizerBase,
                                                    TokenizerRegistry)
21
from vllm.transformers_utils.tokenizers import MistralTokenizer
22
from vllm.transformers_utils.utils import check_gguf_file
23
from vllm.utils import make_async
24

25
26
27
if TYPE_CHECKING:
    from vllm.config import ModelConfig

28
29
logger = init_logger(__name__)

30
AnyTokenizer = Union[PreTrainedTokenizer, PreTrainedTokenizerFast,
31
                     TokenizerBase]
32

33

34
35
36
37
def decode_tokens(
    tokenizer: AnyTokenizer,
    token_ids: list[int],
    *,
38
    skip_special_tokens: Optional[bool] = None,
39
40
41
) -> str:
    """
    Backend-agnostic equivalent of HF's
42
43
44
45
    :code:`tokenizer.decode(token_ids, ...)`.

    :code:`skip_special_tokens=None` means to use the backend's default
    settings.
46
    """
47
48
49
50
51
    if skip_special_tokens is not None:
        return tokenizer.decode(token_ids,
                                skip_special_tokens=skip_special_tokens)

    return tokenizer.decode(token_ids)
52
53


54
55
56
57
def encode_tokens(
    tokenizer: AnyTokenizer,
    text: str,
    *,
58
59
    truncation: Optional[bool] = None,
    max_length: Optional[int] = None,
60
61
62
63
    add_special_tokens: Optional[bool] = None,
) -> list[int]:
    """
    Backend-agnostic equivalent of HF's
64
65
66
67
    :code:`tokenizer.encode(text, ...)`.

    :code:`add_special_tokens=None` means to use the backend's default
    settings.
68
    """
69
70
71
72
73
74
75
76

    kw_args: dict[str, Any] = {}
    if max_length is not None:
        kw_args["max_length"] = max_length

    if truncation is not None:
        kw_args["truncation"] = truncation

77
    if add_special_tokens is not None:
78
        kw_args["add_special_tokens"] = add_special_tokens
79

80
    return tokenizer.encode(text, **kw_args)
81
82


83
def get_cached_tokenizer(tokenizer: AnyTokenizer) -> AnyTokenizer:
84
    """
85
    By default, transformers will recompute multiple tokenizer properties
86
87
88
89
    each time they are called, leading to a significant slowdown.
    This proxy caches these properties for faster access.
    """
    cached_tokenizer = copy.copy(tokenizer)
90

91
92
    tokenizer_all_special_ids = tokenizer.all_special_ids
    tokenizer_all_special_tokens = tokenizer.all_special_tokens
93
94
    tokenizer_all_special_tokens_extended = (
        tokenizer.all_special_tokens_extended)
95
    tokenizer_vocab = tokenizer.get_vocab()
96
    tokenizer_len = len(tokenizer)
97

98
    max_token_id = max(tokenizer_vocab.values())
99
100
101
102
103
104
105
    # Some tokenizers (e.g., QwenTokenizer) have special tokens that
    # are added and included in the implementation of the vocab_size
    # property, but not in get_vocab(); if there is an implementation
    # of vocab size, we should take the greater value.
    if hasattr(tokenizer, "vocab_size"):
        with contextlib.suppress(NotImplementedError):
            max_token_id = max(max_token_id, tokenizer.vocab_size)
106

107
    class CachedTokenizer(tokenizer.__class__):  # type: ignore
108
109

        @property
110
        def all_special_ids(self) -> list[int]:
111
112
113
            return tokenizer_all_special_ids

        @property
114
        def all_special_tokens(self) -> list[str]:
115
116
117
            return tokenizer_all_special_tokens

        @property
118
        def all_special_tokens_extended(self) -> list[str]:
119
120
            return tokenizer_all_special_tokens_extended

121
        @property
122
        def max_token_id(self) -> int:
123
124
            return max_token_id

125
        def get_vocab(self) -> dict[str, int]:
126
127
            return tokenizer_vocab

128
        def __len__(self) -> int:
129
130
            return tokenizer_len

131
132
133
        def __reduce__(self):
            return get_cached_tokenizer, (tokenizer, )

134
135
    CachedTokenizer.__name__ = f"Cached{tokenizer.__class__.__name__}"

136
137
    cached_tokenizer.__class__ = CachedTokenizer
    return cached_tokenizer
138
139


140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
def patch_padding_side(tokenizer: PreTrainedTokenizer) -> None:
    """Patch _pad method to accept `padding_side` for older tokenizers."""
    orig_pad = tokenizer._pad

    def _pad(
        self: PreTrainedTokenizer,
        *args,
        padding_side: Optional[str] = None,
        **kwargs,
    ):
        if padding_side is not None and padding_side != self.padding_side:
            msg = ("`padding_side` argument is not supported by "
                   f"{type(tokenizer).__name__} and will be ignored.")
            warnings.warn(msg, stacklevel=2)

        return orig_pad(*args, **kwargs)

    tokenizer._pad = MethodType(_pad, tokenizer)


160
def get_tokenizer(
161
    tokenizer_name: Union[str, Path],
162
    *args,
163
    tokenizer_mode: str = "auto",
164
    trust_remote_code: bool = False,
165
    revision: Optional[str] = None,
166
    download_dir: Optional[str] = None,
167
    **kwargs,
168
) -> AnyTokenizer:
169
170
    """Gets a tokenizer for the given model name via HuggingFace or ModelScope.
    """
171
172
173
174
175
176
    if VLLM_USE_MODELSCOPE:
        # download model from ModelScope hub,
        # lazy import so that modelscope is not required for normal use.
        # pylint: disable=C.
        from modelscope.hub.snapshot_download import snapshot_download

177
178
179
        # avoid circuit import
        from vllm.model_executor.model_loader.weight_utils import get_lock

180
181
        # Only set the tokenizer here, model will be downloaded on the workers.
        if not os.path.exists(tokenizer_name):
182
183
184
185
186
187
188
189
190
191
192
            # Use file lock to prevent multiple processes from
            # downloading the same file at the same time.
            with get_lock(tokenizer_name, download_dir):
                tokenizer_path = snapshot_download(
                    model_id=tokenizer_name,
                    cache_dir=download_dir,
                    revision=revision,
                    local_files_only=huggingface_hub.constants.HF_HUB_OFFLINE,
                    # Ignore weights - we only need the tokenizer.
                    ignore_file_pattern=[".*.pt", ".*.safetensors", ".*.bin"])
                tokenizer_name = tokenizer_path
193

194
195
196
197
198
199
    if tokenizer_mode == "slow":
        if kwargs.get("use_fast", False):
            raise ValueError(
                "Cannot use the fast tokenizer in slow tokenizer mode.")
        kwargs["use_fast"] = False

200
201
202
    if "truncation_side" not in kwargs:
        kwargs["truncation_side"] = "left"

203
    # Separate model folder from file path for GGUF models
204
    is_gguf = check_gguf_file(tokenizer_name)
205
206
207
208
    if is_gguf:
        kwargs["gguf_file"] = Path(tokenizer_name).name
        tokenizer_name = Path(tokenizer_name).parent

209
210
211
212
213
    # if tokenizer is from official mistral org
    is_from_mistral_org = str(tokenizer_name).split("/")[0] == "mistralai"
    if is_from_mistral_org and tokenizer_mode != "mistral":
        warnings.warn(
            'It is strongly recommended to run mistral models with '
214
            '`--tokenizer-mode "mistral"` to ensure correct '
215
216
217
            'encoding and decoding.',
            FutureWarning,
            stacklevel=2)
218
219

    tokenizer: AnyTokenizer
220
221
222
    if tokenizer_mode == "mistral":
        tokenizer = MistralTokenizer.from_pretrained(str(tokenizer_name),
                                                     revision=revision)
223
224
225
226
227
228
    elif tokenizer_mode == "custom":
        tokenizer = TokenizerRegistry.get_tokenizer(str(tokenizer_name),
                                                    *args,
                                                    revision=revision,
                                                    download_dir=download_dir,
                                                    **kwargs)
229
230
231
    else:
        try:
            tokenizer = AutoTokenizer.from_pretrained(
232
233
234
                tokenizer_name,
                *args,
                trust_remote_code=trust_remote_code,
235
                revision=revision,
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
                **kwargs,
            )
        except ValueError as e:
            # If the error pertains to the tokenizer class not existing or not
            # currently being imported,
            # suggest using the --trust-remote-code flag.
            if not trust_remote_code and (
                    "does not exist or is not currently imported." in str(e)
                    or "requires you to execute the tokenizer file" in str(e)):
                err_msg = ("Failed to load the tokenizer. If the tokenizer "
                           "is a custom tokenizer not yet available in the "
                           "HuggingFace transformers library, consider "
                           "setting `trust_remote_code=True` in LLM or using "
                           "the `--trust-remote-code` flag in the CLI.")
                raise RuntimeError(err_msg) from e
            else:
                raise e

254
255
256
257
        # NOTE: We can remove this after https://github.com/THUDM/ChatGLM3/issues/1324
        if type(tokenizer).__name__ in ("ChatGLMTokenizer",
                                        "ChatGLM4Tokenizer"):
            assert isinstance(tokenizer, PreTrainedTokenizer)
258
            patch_padding_side(tokenizer)
259

260
261
262
263
264
        if not isinstance(tokenizer, PreTrainedTokenizerFast):
            logger.warning(
                "Using a slow tokenizer. This might cause a significant "
                "slowdown. Consider using a fast tokenizer instead.")
        tokenizer = get_cached_tokenizer(tokenizer)
265

266
    return tokenizer
267
268


269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
cached_get_tokenizer = lru_cache(get_tokenizer)


def cached_tokenizer_from_config(
    model_config: "ModelConfig",
    **kwargs: Any,
):
    return cached_get_tokenizer(
        model_config.tokenizer,
        tokenizer_mode=model_config.tokenizer_mode,
        tokenizer_revision=model_config.tokenizer_revision,
        trust_remote_code=model_config.trust_remote_code,
        **kwargs,
    )


285
def get_lora_tokenizer(lora_request: LoRARequest, *args,
286
                       **kwargs) -> Optional[AnyTokenizer]:
287
288
289
    if lora_request is None:
        return None
    try:
290
        tokenizer = get_tokenizer(lora_request.lora_path, *args, **kwargs)
291
    except Exception as e:
292
293
294
        # No tokenizer was found in the LoRA folder,
        # use base model tokenizer
        logger.warning(
295
            "No tokenizer found in %s, using base model tokenizer instead. "
296
            "(Exception: %s)", lora_request.lora_path, e)
297
298
299
300
301
        tokenizer = None
    return tokenizer


get_lora_tokenizer_async = make_async(get_lora_tokenizer)