tokenizer.py 10.7 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
import warnings
9
from functools import lru_cache
10
from pathlib import Path
11
from typing import TYPE_CHECKING, Any
12

13
import huggingface_hub
14
from transformers import AutoTokenizer, PreTrainedTokenizerBase
15
from typing_extensions import assert_never
16

17
from vllm import envs
Woosuk Kwon's avatar
Woosuk Kwon committed
18
from vllm.logger import init_logger
19
20
21
22
23
24
from vllm.tokenizers import MistralTokenizer, TokenizerLike, TokenizerRegistry

from .config import get_sentence_transformer_tokenizer_config
from .gguf_utils import get_gguf_file_path_from_hf
from .repo_utils import list_filtered_repo_files
from .utils import check_gguf_file, is_gguf, is_remote_gguf, split_remote_gguf
25

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

29

30
31
logger = init_logger(__name__)

32
33
34
35
36
37
38
39
40
41
42
43
44
45

def __getattr__(name: str):
    if name == "AnyTokenizer":
        warnings.warn(
            "`vllm.transformers_utils.tokenizer.AnyTokenizer` has been moved to "
            "`vllm.tokenizers.TokenizerLike`. "
            "The old name will be removed in v0.13.",
            DeprecationWarning,
            stacklevel=2,
        )

        return TokenizerLike

    raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
46

47

48
def decode_tokens(
49
    tokenizer: TokenizerLike,
50
51
    token_ids: list[int],
    *,
52
    skip_special_tokens: bool | None = None,
53
54
55
) -> str:
    """
    Backend-agnostic equivalent of HF's
56
    `tokenizer.decode(token_ids, ...)`.
57

58
    `skip_special_tokens=None` means to use the backend's default
59
    settings.
60
    """
61
    if skip_special_tokens is not None:
62
        return tokenizer.decode(token_ids, skip_special_tokens=skip_special_tokens)
63

64
    return tokenizer.decode(token_ids)
65
66


67
def encode_tokens(
68
    tokenizer: TokenizerLike,
69
70
    text: str,
    *,
71
72
73
    truncation: bool | None = None,
    max_length: int | None = None,
    add_special_tokens: bool | None = None,
74
75
76
) -> list[int]:
    """
    Backend-agnostic equivalent of HF's
77
    `tokenizer.encode(text, ...)`.
78

79
    `add_special_tokens=None` means to use the backend's default
80
    settings.
81
    """
82
83
84
85
86
87
88
89

    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

90
    if add_special_tokens is not None:
91
        kw_args["add_special_tokens"] = add_special_tokens
92

93
    return tokenizer.encode(text, **kw_args)
94
95


96
def get_cached_tokenizer(tokenizer: TokenizerLike) -> TokenizerLike:
97
    """
98
    By default, transformers will recompute multiple tokenizer properties
99
100
101
102
    each time they are called, leading to a significant slowdown.
    This proxy caches these properties for faster access.
    """
    cached_tokenizer = copy.copy(tokenizer)
103

104
105
    tokenizer_all_special_ids = tokenizer.all_special_ids
    tokenizer_all_special_tokens = tokenizer.all_special_tokens
106
    tokenizer_vocab = tokenizer.get_vocab()
107
    tokenizer_len = len(tokenizer)
108

109
    max_token_id = max(tokenizer_vocab.values())
110
111
112
113
114
115
116
    # 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)
117

118
    class CachedTokenizer(tokenizer.__class__):  # type: ignore
119
        @property
120
        def all_special_ids(self) -> list[int]:
121
122
123
            return tokenizer_all_special_ids

        @property
124
        def all_special_tokens(self) -> list[str]:
125
126
127
            return tokenizer_all_special_tokens

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

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

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

281
    return tokenizer
282
283


284
285
286
287
cached_get_tokenizer = lru_cache(get_tokenizer)


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


300
def init_tokenizer_from_configs(model_config: "ModelConfig"):
301
302
303
304
305
306
307
    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)
308

309
310
311
312
313
314
315
    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,
    )