tokenizer.py 5.36 KB
Newer Older
1
import os
2
from typing import Optional, Union
3

4
import huggingface_hub
5
from transformers import (AutoTokenizer, PreTrainedTokenizer,
6
7
                          PreTrainedTokenizerFast)

8
from vllm.config import VLLM_USE_MODELSCOPE
Woosuk Kwon's avatar
Woosuk Kwon committed
9
from vllm.logger import init_logger
10
from vllm.lora.request import LoRARequest
11
from vllm.transformers_utils.tokenizers import BaichuanTokenizer
12
from vllm.utils import make_async
13
14
15

logger = init_logger(__name__)

16

17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
def get_cached_tokenizer(
    tokenizer: Union[PreTrainedTokenizer, PreTrainedTokenizerFast]
) -> Union[PreTrainedTokenizer, PreTrainedTokenizerFast]:
    """Get tokenizer with cached properties.

    This will patch the tokenizer object in place.

    By default, transformers will recompute multiple tokenizer properties
    each time they are called, leading to a significant slowdown. This
    function caches these properties for faster access."""

    tokenizer_all_special_ids = set(tokenizer.all_special_ids)
    tokenizer_all_special_tokens_extended = (
        tokenizer.all_special_tokens_extended)
    tokenizer_all_special_tokens = set(tokenizer.all_special_tokens)
32
    tokenizer_len = len(tokenizer)
33

34
    class CachedTokenizer(tokenizer.__class__):  # type: ignore
35
36
37
38
39
40
41
42
43
44
45
46
47

        @property
        def all_special_ids(self):
            return tokenizer_all_special_ids

        @property
        def all_special_tokens(self):
            return tokenizer_all_special_tokens

        @property
        def all_special_tokens_extended(self):
            return tokenizer_all_special_tokens_extended

48
49
50
        def __len__(self):
            return tokenizer_len

51
52
53
54
55
56
    CachedTokenizer.__name__ = f"Cached{tokenizer.__class__.__name__}"

    tokenizer.__class__ = CachedTokenizer
    return tokenizer


57
def get_tokenizer(
58
    tokenizer_name: str,
59
    *args,
60
    tokenizer_mode: str = "auto",
61
    trust_remote_code: bool = False,
62
    revision: Optional[str] = None,
63
    download_dir: Optional[str] = None,
64
65
    **kwargs,
) -> Union[PreTrainedTokenizer, PreTrainedTokenizerFast]:
66
67
    """Gets a tokenizer for the given model name via HuggingFace or ModelScope.
    """
68
69
70
71
72
73
74
75
76
77
78
    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

        # Only set the tokenizer here, model will be downloaded on the workers.
        if not os.path.exists(tokenizer_name):
            tokenizer_path = snapshot_download(
                model_id=tokenizer_name,
                cache_dir=download_dir,
79
                revision=revision,
80
                local_files_only=huggingface_hub.constants.HF_HUB_OFFLINE,
81
82
83
84
                # Ignore weights - we only need the tokenizer.
                ignore_file_pattern=["*.pt", "*.safetensors", "*.bin"])
            tokenizer_name = tokenizer_path

85
86
87
88
89
90
    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

91
    try:
92
93
94
        tokenizer = AutoTokenizer.from_pretrained(
            tokenizer_name,
            *args,
95
            trust_remote_code=trust_remote_code,
96
            revision=revision,
97
98
99
100
            **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.
101
        if (not trust_remote_code and
102
103
104
105
106
            ("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 "
107
108
                "library, consider setting `trust_remote_code=True` in LLM "
                "or using the `--trust-remote-code` flag in the CLI.")
109
110
111
            raise RuntimeError(err_msg) from e
        else:
            raise e
112
113
114
115
116
117
118
119
    except AttributeError as e:
        if "BaichuanTokenizer" in str(e):
            # This is for the error "'BaichuanTokenizer' object has no
            # attribute 'sp_model'".
            tokenizer = BaichuanTokenizer.from_pretrained(
                tokenizer_name,
                *args,
                trust_remote_code=trust_remote_code,
120
                revision=revision,
121
122
123
                **kwargs)
        else:
            raise e
124
125
126
127
128

    if not isinstance(tokenizer, PreTrainedTokenizerFast):
        logger.warning(
            "Using a slow tokenizer. This might cause a significant "
            "slowdown. Consider using a fast tokenizer instead.")
129
    return get_cached_tokenizer(tokenizer)
130
131


132
133
134
135
136
137
138
139
140
141
142
def get_lora_tokenizer(lora_request: LoRARequest, *args,
                       **kwargs) -> Optional[PreTrainedTokenizer]:
    if lora_request is None:
        return None
    try:
        tokenizer = get_tokenizer(lora_request.lora_local_path, *args,
                                  **kwargs)
    except OSError as e:
        # No tokenizer was found in the LoRA folder,
        # use base model tokenizer
        logger.warning(
143
144
            "No tokenizer found in %s, using base model tokenizer instead. "
            "(Exception: %s)", lora_request.lora_local_path, e)
145
146
147
148
149
        tokenizer = None
    return tokenizer


get_lora_tokenizer_async = make_async(get_lora_tokenizer)