utils.py 2.88 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 struct
6
from functools import cache
7
8
from os import PathLike
from pathlib import Path
9
from typing import Any
10

11
12
13
14
15
from vllm.envs import VLLM_MODEL_REDIRECT_PATH
from vllm.logger import init_logger

logger = init_logger(__name__)

16

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


21
def check_gguf_file(model: str | PathLike) -> bool:
22
23
24
25
26
27
28
    """Check if the file is a GGUF model."""
    model = Path(model)
    if not model.is_file():
        return False
    elif model.suffix == ".gguf":
        return True

Reid's avatar
Reid committed
29
30
31
32
33
34
35
36
    try:
        with model.open("rb") as f:
            header = f.read(4)

        return header == b"GGUF"
    except Exception as e:
        logger.debug("Error reading file %s: %s", model, e)
        return False
37
38
39
40


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

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


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


68
def _maybe_space_split_dict(path: str | PathLike) -> dict[str, str]:
69
70
71
72
73
74
75
76
77
78
79
    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


80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
@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
    """

    model_redirect_path = VLLM_MODEL_REDIRECT_PATH

    if not model_redirect_path:
        return model

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

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

    return model
105
106


107
def parse_safetensors_file_metadata(path: str | PathLike) -> dict[str, Any]:
108
    with open(path, "rb") as f:
109
110
        length_of_metadata = struct.unpack("<Q", f.read(8))[0]
        metadata = json.loads(f.read(length_of_metadata).decode("utf-8"))
111
        return metadata