"requirements/rocm-test.in" did not exist on "e246ad6f0cbc4706b5d2f4ad893fbe78409c5366"
tokenizer.py 5.33 KB
Newer Older
1
import os
2
from typing import Optional, Union
3

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

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

logger = init_logger(__name__)

15

16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
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)
31
    tokenizer_len = len(tokenizer)
32

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

        @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

47
48
49
        def __len__(self):
            return tokenizer_len

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

    tokenizer.__class__ = CachedTokenizer
    return tokenizer


56
def get_tokenizer(
57
    tokenizer_name: str,
58
    *args,
59
    tokenizer_mode: str = "auto",
60
    trust_remote_code: bool = False,
61
    tokenizer_revision: Optional[str] = None,
62
    download_dir: Optional[str] = None,
63
64
    **kwargs,
) -> Union[PreTrainedTokenizer, PreTrainedTokenizerFast]:
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
    """Gets a tokenizer for the given model name via Huggingface/modelscope."""
    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,
                revision=tokenizer_revision,
                # Ignore weights - we only need the tokenizer.
                ignore_file_pattern=["*.pt", "*.safetensors", "*.bin"])
            tokenizer_name = tokenizer_path

82
83
84
85
86
87
    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

88
    try:
89
90
91
        tokenizer = AutoTokenizer.from_pretrained(
            tokenizer_name,
            *args,
92
            trust_remote_code=trust_remote_code,
93
            tokenizer_revision=tokenizer_revision,
94
95
96
97
            **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.
98
        if (not trust_remote_code and
99
100
101
102
103
            ("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 "
104
105
                "library, consider setting `trust_remote_code=True` in LLM "
                "or using the `--trust-remote-code` flag in the CLI.")
106
107
108
            raise RuntimeError(err_msg) from e
        else:
            raise e
109
110
111
112
113
114
115
116
117
118
119
120
    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,
                tokenizer_revision=tokenizer_revision,
                **kwargs)
        else:
            raise e
121
122
123
124
125

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


129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
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(
            f"No tokenizer found in {lora_request.lora_local_path}, "
            "using base model tokenizer instead. "
            f"(Exception: {str(e)})")
        tokenizer = None
    return tokenizer


get_lora_tokenizer_async = make_async(get_lora_tokenizer)