main
py 124 lines 3.38 KB
Raw
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 from os import PathLike
9 from pathlib import Path
10 from typing import Any
11
12 import vllm.envs as envs
13 from vllm.logger import init_logger
14
15 logger = init_logger(__name__)
16
17
18 def is_s3(model_or_path: str) -> bool:
19 return model_or_path.lower().startswith("s3://")
20
21
22 def is_gcs(model_or_path: str) -> bool:
23 return model_or_path.lower().startswith("gs://")
24
25
26 def is_azure(model_or_path: str) -> bool:
27 return model_or_path.lower().startswith("az://")
28
29
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 def without_trust_remote_code(kwargs: dict[str, Any]) -> dict[str, Any]:
35 """Return kwargs without trust_remote_code without modifying original dict."""
36 if "trust_remote_code" not in kwargs:
37 return kwargs
38 return {k: v for k, v in kwargs.items() if k != "trust_remote_code"}
39
40
41 def modelscope_list_repo_files(
42 repo_id: str,
43 revision: str | None = None,
44 token: str | bool | None = None,
45 ) -> list[str]:
46 """List files in a modelscope repo."""
47 from modelscope.hub.api import HubApi
48
49 api = HubApi()
50 api.login(token)
51
52 # same as huggingface_hub.list_repo_files
53 return [
54 file["Path"]
55 for file in api.get_model_files(
56 model_id=repo_id, revision=revision, recursive=True
57 )
58 ]
59
60
61 def _maybe_json_dict(path: str | PathLike) -> dict[str, str]:
62 with open(path) as f:
63 try:
64 return json.loads(f.read())
65 except Exception:
66 return dict[str, str]()
67
68
69 def _maybe_space_split_dict(path: str | PathLike) -> dict[str, str]:
70 parsed_dict = dict[str, str]()
71 with open(path) as f:
72 for line in f.readlines():
73 try:
74 model_name, redirect_name = line.strip().split()
75 parsed_dict[model_name] = redirect_name
76 except Exception:
77 pass
78 return parsed_dict
79
80
81 @cache
82 def maybe_model_redirect(model: str) -> str:
83 """Use model_redirect to redirect the model name to a local folder.
84
85 Args:
86 model: hf model name
87
88 Returns:
89 maybe redirect to a local folder
90
91 """
92 model_redirect_path = envs.VLLM_MODEL_REDIRECT_PATH
93
94 if not model_redirect_path:
95 return model
96
97 if not Path(model_redirect_path).exists():
98 return model
99
100 redirect_dict = _maybe_json_dict(model_redirect_path) or _maybe_space_split_dict(
101 model_redirect_path
102 )
103 if redirect_model := redirect_dict.get(model):
104 logger.info("model redirect: [ %s ] -> [ %s ]", model, redirect_model)
105 return redirect_model
106
107 return model
108
109
110 def parse_safetensors_file_metadata(path: str | PathLike) -> dict[str, Any]:
111 with open(path, "rb") as f:
112 length_of_metadata = struct.unpack("<Q", f.read(8))[0]
113 metadata = json.loads(f.read(length_of_metadata).decode("utf-8"))
114 return metadata
115
116
117 def convert_model_repo_to_path(model_repo: str) -> str:
118 """When VLLM_USE_MODELSCOPE is True convert a model
119 repository string to a Path str."""
120 if not envs.VLLM_USE_MODELSCOPE or Path(model_repo).exists():
121 return model_repo
122 from modelscope.utils.file_utils import get_model_cache_root
123
124 return os.path.join(get_model_cache_root(), model_repo)