tokenizer.py 10.8 KB
Newer Older
1
# SPDX-License-Identifier: Apache-2.0
2
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
3

4
import contextlib
5
import copy
6
import importlib.util
7
import os
8
from functools import lru_cache
9
from pathlib import Path
10
from typing import TYPE_CHECKING, Any, TypeAlias
11

12
import huggingface_hub
13
from transformers import AutoTokenizer, PreTrainedTokenizer, PreTrainedTokenizerFast
14
from typing_extensions import assert_never
15

16
from vllm import envs
Woosuk Kwon's avatar
Woosuk Kwon committed
17
from vllm.logger import init_logger
18
19
20
21
from vllm.transformers_utils.config import (
    get_sentence_transformer_tokenizer_config,
    list_filtered_repo_files,
)
22
from vllm.transformers_utils.gguf_utils import get_gguf_file_path_from_hf
23
from vllm.transformers_utils.tokenizers import MistralTokenizer
24
25
26
27
28
29
from vllm.transformers_utils.utils import (
    check_gguf_file,
    is_gguf,
    is_remote_gguf,
    split_remote_gguf,
)
30

31
32
if TYPE_CHECKING:
    from vllm.config import ModelConfig
33
34
35
36
    from vllm.transformers_utils.tokenizer_base import TokenizerBase
else:
    ModelConfig = Any
    TokenizerBase = Any
37

38
39
logger = init_logger(__name__)

40
AnyTokenizer: TypeAlias = PreTrainedTokenizer | PreTrainedTokenizerFast | TokenizerBase
41

42

43
44
45
46
def decode_tokens(
    tokenizer: AnyTokenizer,
    token_ids: list[int],
    *,
47
    skip_special_tokens: bool | None = None,
48
49
50
) -> str:
    """
    Backend-agnostic equivalent of HF's
51
    `tokenizer.decode(token_ids, ...)`.
52

53
    `skip_special_tokens=None` means to use the backend's default
54
    settings.
55
    """
56
    if skip_special_tokens is not None:
57
        return tokenizer.decode(token_ids, skip_special_tokens=skip_special_tokens)
58

59
    return tokenizer.decode(token_ids)
60
61


62
63
64
65
def encode_tokens(
    tokenizer: AnyTokenizer,
    text: str,
    *,
66
67
68
    truncation: bool | None = None,
    max_length: int | None = None,
    add_special_tokens: bool | None = None,
69
70
71
) -> list[int]:
    """
    Backend-agnostic equivalent of HF's
72
    `tokenizer.encode(text, ...)`.
73

74
    `add_special_tokens=None` means to use the backend's default
75
    settings.
76
    """
77
78
79
80
81
82
83
84

    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

85
    if add_special_tokens is not None:
86
        kw_args["add_special_tokens"] = add_special_tokens
87

88
    return tokenizer.encode(text, **kw_args)
89
90


91
def get_cached_tokenizer(tokenizer: AnyTokenizer) -> AnyTokenizer:
92
    """
93
    By default, transformers will recompute multiple tokenizer properties
94
95
96
97
    each time they are called, leading to a significant slowdown.
    This proxy caches these properties for faster access.
    """
    cached_tokenizer = copy.copy(tokenizer)
98

99
100
    tokenizer_all_special_ids = tokenizer.all_special_ids
    tokenizer_all_special_tokens = tokenizer.all_special_tokens
101
    tokenizer_all_special_tokens_extended = tokenizer.all_special_tokens_extended
102
    tokenizer_vocab = tokenizer.get_vocab()
103
    tokenizer_len = len(tokenizer)
104

105
    max_token_id = max(tokenizer_vocab.values())
106
107
108
109
110
111
112
    # 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)
113

114
    class CachedTokenizer(tokenizer.__class__):  # type: ignore
115
        @property
116
        def all_special_ids(self) -> list[int]:
117
118
119
            return tokenizer_all_special_ids

        @property
120
        def all_special_tokens(self) -> list[str]:
121
122
123
            return tokenizer_all_special_tokens

        @property
124
        def all_special_tokens_extended(self) -> list[str]:
125
126
            return tokenizer_all_special_tokens_extended

127
        @property
128
        def max_token_id(self) -> int:
129
130
            return max_token_id

131
        def get_vocab(self) -> dict[str, int]:
132
133
            return tokenizer_vocab

134
        def __len__(self) -> int:
135
136
            return tokenizer_len

137
        def __reduce__(self):
138
            return get_cached_tokenizer, (tokenizer,)
139

140
141
    CachedTokenizer.__name__ = f"Cached{tokenizer.__class__.__name__}"

142
143
    cached_tokenizer.__class__ = CachedTokenizer
    return cached_tokenizer
144
145


146
def get_tokenizer(
147
    tokenizer_name: str | Path,
148
    *args,
149
    tokenizer_mode: str = "auto",
150
    trust_remote_code: bool = False,
151
152
    revision: str | None = None,
    download_dir: str | None = None,
153
    **kwargs,
154
) -> AnyTokenizer:
155
    """Gets a tokenizer for the given model name via HuggingFace or ModelScope."""
156
    if envs.VLLM_USE_MODELSCOPE:
157
158
159
160
161
        # 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

162
163
164
        # avoid circuit import
        from vllm.model_executor.model_loader.weight_utils import get_lock

165
166
        # Only set the tokenizer here, model will be downloaded on the workers.
        if not os.path.exists(tokenizer_name):
167
168
169
170
171
172
173
174
175
            # 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.
176
177
                    ignore_file_pattern=[".*.pt", ".*.safetensors", ".*.bin"],
                )
178
                tokenizer_name = tokenizer_path
179

180
181
    if tokenizer_mode == "slow":
        if kwargs.get("use_fast", False):
182
            raise ValueError("Cannot use the fast tokenizer in slow tokenizer mode.")
183
184
        kwargs["use_fast"] = False

185
186
187
    if "truncation_side" not in kwargs:
        kwargs["truncation_side"] = "left"

188
    # Separate model folder from file path for GGUF models
189
190
191
192
193
    if is_gguf(tokenizer_name):
        if check_gguf_file(tokenizer_name):
            kwargs["gguf_file"] = Path(tokenizer_name).name
            tokenizer_name = Path(tokenizer_name).parent
        elif is_remote_gguf(tokenizer_name):
194
195
196
197
198
199
200
201
            tokenizer_name, quant_type = split_remote_gguf(tokenizer_name)
            # Get the HuggingFace Hub path for the GGUF file
            gguf_file = get_gguf_file_path_from_hf(
                tokenizer_name,
                quant_type,
                revision=revision,
            )
            kwargs["gguf_file"] = gguf_file
202

203
204
205
206
207
208
209
210
211
    # if `tokenizer_mode` == "auto", check if tokenizer can be loaded via Mistral format
    # first to use official Mistral tokenizer if possible.
    mistral_common_installed = importlib.util.find_spec("mistral_common") is not None
    if tokenizer_mode == "auto" and mistral_common_installed:
        allow_patterns = ["tekken.json", "tokenizer.model.v*"]
        files_list = list_filtered_repo_files(
            model_name_or_path=str(tokenizer_name),
            allow_patterns=allow_patterns,
            revision=revision,
212
        )
213
214
        if len(files_list) > 0:
            tokenizer_mode = "mistral"
215
216

    tokenizer: AnyTokenizer
217
    if tokenizer_mode == "mistral":
218
        logger.debug_once(f"Loading MistralTokenizer from {tokenizer_name}")
219
220
221
        tokenizer = MistralTokenizer.from_pretrained(
            str(tokenizer_name), revision=revision
        )
222
    elif tokenizer_mode == "custom":
223
        from vllm.transformers_utils.tokenizer_base import TokenizerRegistry
224

225
        logger.debug_once(f"Loading CustomTokenizer from {tokenizer_name}")
226
227
228
229
230
231
232
        tokenizer = TokenizerRegistry.get_tokenizer(
            str(tokenizer_name),
            *args,
            revision=revision,
            download_dir=download_dir,
            **kwargs,
        )
233
234
    else:
        try:
235
            logger.debug_once(f"Loading AutoTokenizer from {tokenizer_name}")
236
            tokenizer = AutoTokenizer.from_pretrained(
237
238
239
                tokenizer_name,
                *args,
                trust_remote_code=trust_remote_code,
240
                revision=revision,
241
242
243
244
245
246
247
                **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 (
248
249
250
251
252
253
254
255
256
257
                "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."
                )
258
259
260
261
                raise RuntimeError(err_msg) from e
            else:
                raise e

262
263
264
        # The special_tokens in tokenizer should also be
        # controlled by do_lower_case in encoder_config
        encoder_config = get_sentence_transformer_tokenizer_config(
265
266
            tokenizer_name, revision
        )
267
        if isinstance(encoder_config, dict) and encoder_config.get(
268
269
            "do_lower_case", False
        ):
270
            special_tokens_map = {
271
                k: v.lower() for k, v in tokenizer.special_tokens_map.items()
272
273
274
            }
            tokenizer.add_special_tokens(special_tokens_map)

275
276
277
        if not isinstance(tokenizer, PreTrainedTokenizerFast):
            logger.warning(
                "Using a slow tokenizer. This might cause a significant "
278
279
                "slowdown. Consider using a fast tokenizer instead."
            )
280
        tokenizer = get_cached_tokenizer(tokenizer)
281

282
    return tokenizer
283
284


285
286
287
288
cached_get_tokenizer = lru_cache(get_tokenizer)


def cached_tokenizer_from_config(
289
    model_config: ModelConfig,
290
291
292
293
294
    **kwargs: Any,
):
    return cached_get_tokenizer(
        model_config.tokenizer,
        tokenizer_mode=model_config.tokenizer_mode,
295
        revision=model_config.tokenizer_revision,
296
297
298
299
300
        trust_remote_code=model_config.trust_remote_code,
        **kwargs,
    )


301
302
303
304
305
306
307
308
def init_tokenizer_from_configs(model_config: ModelConfig):
    runner_type = model_config.runner_type
    if runner_type == "generate" or runner_type == "draft":
        truncation_side = "left"
    elif runner_type == "pooling":
        truncation_side = "right"
    else:
        assert_never(runner_type)
309

310
311
312
313
314
315
316
    return get_tokenizer(
        model_config.tokenizer,
        tokenizer_mode=model_config.tokenizer_mode,
        trust_remote_code=model_config.trust_remote_code,
        revision=model_config.tokenizer_revision,
        truncation_side=truncation_side,
    )