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

4
import json
5
import os
6
import struct
7
from functools import cache
8
9
from os import PathLike
from pathlib import Path
10
from typing import Any
11

12
import vllm.envs as envs
13
14
15
16
from vllm.logger import init_logger

logger = init_logger(__name__)

17

18
def is_s3(model_or_path: str) -> bool:
19
    return model_or_path.lower().startswith("s3://")
20
21


22
23
24
25
def is_gcs(model_or_path: str) -> bool:
    return model_or_path.lower().startswith("gs://")


26
27
28
29
def is_azure(model_or_path: str) -> bool:
    return model_or_path.lower().startswith("az://")


30
def is_cloud_storage(model_or_path: str) -> bool:
31
    return is_s3(model_or_path) or is_gcs(model_or_path) or is_azure(model_or_path)
32
33


34
35
36
37
38
39
40
def without_trust_remote_code(kwargs: dict[str, Any]) -> dict[str, Any]:
    """Return kwargs without trust_remote_code without modifying original dict."""
    if "trust_remote_code" not in kwargs:
        return kwargs
    return {k: v for k, v in kwargs.items() if k != "trust_remote_code"}


41
42
def modelscope_list_repo_files(
    repo_id: str,
43
44
    revision: str | None = None,
    token: str | bool | None = None,
45
) -> list[str]:
46
47
    """List files in a modelscope repo."""
    from modelscope.hub.api import HubApi
48

49
    api = HubApi()
50
    api.login(token)
51
52
    # same as huggingface_hub.list_repo_files
    files = [
53
54
55
56
57
        file["Path"]
        for file in api.get_model_files(
            model_id=repo_id, revision=revision, recursive=True
        )
        if file["Type"] == "blob"
58
59
    ]
    return files
60
61


62
def _maybe_json_dict(path: str | PathLike) -> dict[str, str]:
63
64
65
66
67
68
69
    with open(path) as f:
        try:
            return json.loads(f.read())
        except Exception:
            return dict[str, str]()


70
def _maybe_space_split_dict(path: str | PathLike) -> dict[str, str]:
71
72
73
74
75
76
77
78
79
80
81
    parsed_dict = dict[str, str]()
    with open(path) as f:
        for line in f.readlines():
            try:
                model_name, redirect_name = line.strip().split()
                parsed_dict[model_name] = redirect_name
            except Exception:
                pass
    return parsed_dict


82
83
84
85
86
87
88
89
90
@cache
def maybe_model_redirect(model: str) -> str:
    """
    Use model_redirect to redirect the model name to a local folder.

    :param model: hf model name
    :return: maybe redirect to a local folder
    """

91
    model_redirect_path = envs.VLLM_MODEL_REDIRECT_PATH
92
93
94
95
96
97
98

    if not model_redirect_path:
        return model

    if not Path(model_redirect_path).exists():
        return model

99
100
101
102
    redirect_dict = _maybe_json_dict(model_redirect_path) or _maybe_space_split_dict(
        model_redirect_path
    )
    if redirect_model := redirect_dict.get(model):
103
104
        logger.info("model redirect: [ %s ] -> [ %s ]", model, redirect_model)
        return redirect_model
105
106

    return model
107
108


109
def parse_safetensors_file_metadata(path: str | PathLike) -> dict[str, Any]:
110
    with open(path, "rb") as f:
111
112
        length_of_metadata = struct.unpack("<Q", f.read(8))[0]
        metadata = json.loads(f.read(length_of_metadata).decode("utf-8"))
113
        return metadata
114
115
116
117
118
119
120
121
122
123


def convert_model_repo_to_path(model_repo: str) -> str:
    """When VLLM_USE_MODELSCOPE is True convert a model
    repository string to a Path str."""
    if not envs.VLLM_USE_MODELSCOPE or Path(model_repo).exists():
        return model_repo
    from modelscope.utils.file_utils import get_model_cache_root

    return os.path.join(get_model_cache_root(), model_repo)