huggingface/transformers · #50663

[serve] Handle missing Hub cache and include loaded models in /v1/models

RyanMullins · merged Nov 17, 20265 files · 184 + / 72 −
docs/source/en/serve-cli/serving.md25 + / 7 −
@@ -1841,22 +1841,40 @@ The command returns the following response.  ## v1/models -The `v1/models` endpoint scans your local Hugging Face cache and returns a list of downloaded models in the OpenAI-compatible format. Third-party tools use this endpoint to discover available models.+The `v1/models` endpoint returns the models the server can serve in the OpenAI-compatible format. Third-party tools use this endpoint to discover available models. -Download a model before running `transformers serve`.+```shell+curl http://localhost:8000/v1/models+```++What it lists depends on how the server was started.++- `transformers serve` loads models on demand, so the endpoint lists the models downloaded in your local Hugging Face cache, and the models that are loaded but not in the cache, like a model served from a local path.+- `transformers serve <model>` only answers for that model, so the endpoint lists it alone.++Download a model for it to appear in the list before it is loaded.  ```bash transformers download Qwen/Qwen2.5-0.5B-Instruct ``` -Once downloaded, the model appears in `/v1/models` responses.+Each model has a `status`, which isn't part of the OpenAI format. It is `loaded` when the model is in memory, and `unloaded` when it is downloaded and loads on the first request that names it. -```shell-curl http://localhost:8000/v1/models+```json+{+  "object": "list",+  "data": [+    {+      "id": "Qwen/Qwen2.5-0.5B-Instruct",+      "object": "model",+      "created": 1776183469,+      "owned_by": "Qwen",+      "status": {"value": "unloaded"}+    }+  ]+} ``` -The endpoint returns a JSON object with available models.- ## Loading models  The `/load_model` endpoint pre-loads a model and streams progress via [Server-Sent Events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events) (SSE). The `transformers chat` CLI uses it automatically so users see download and loading progress instead of a hanging prompt. Use it to warm up a model before sending inference requests.
src/transformers/cli/serving/model_manager.py57 + / 61 −
@@ -21,17 +21,23 @@ import os import threading from collections.abc import Callable-from functools import lru_cache from typing import TYPE_CHECKING -from huggingface_hub import scan_cache_dir-from tqdm import tqdm+from huggingface_hub import CacheNotFound  import transformers from transformers import BitsAndBytesConfig, PreTrainedTokenizerBase  from ...utils import logging-from .utils import Modality, make_progress_tqdm_class, reset_torch_cache, split_model_id, split_revision+from .utils import (+    Modality,+    get_gen_models,+    make_progress_tqdm_class,+    model_owner,+    reset_torch_cache,+    split_model_id,+    split_revision,+)   if TYPE_CHECKING:@@ -489,68 +495,58 @@ def get_model_modality(         else:             raise ValueError(f"Unknown modality for: {model_classname}") -    @staticmethod-    @lru_cache-    def get_gen_models(cache_dir: str | None = None) -> list[dict]:-        """List generative models (LLMs and VLMs) available in the HuggingFace cache.+    def list_models(self, cache_dir: str | None = None) -> list[dict]:+        """List the models to show in `/v1/models`: the generative models of the HuggingFace cache, then the+        loaded models that are not in it, such as a model loaded from a local path. A server pinned to one+        model (`force_model`) lists that model alone.          Args:             cache_dir (`str`, *optional*): Path to the HuggingFace cache directory.                 Defaults to the standard cache location.          Returns:-            `list[dict]`: OpenAI-compatible model list entries with ``id``, ``object``, etc.+            `list[dict]`: OpenAI-compatible model list entries with ``id``, ``object``, etc., and a ``status``+            telling whether the model is loaded.         """-        from transformers.models.auto.modeling_auto import (-            MODEL_FOR_CAUSAL_LM_MAPPING_NAMES,-            MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES,-            MODEL_FOR_MULTIMODAL_LM_MAPPING_NAMES,-        )+        if self.force_model is not None:+            # A pinned server only answers for its model, under the name it was given: list it alone.+            repo, gguf_file = split_model_id(self.force_model)+            name = self.process_model_name(repo)+            is_loaded = (name if gguf_file is None else f"{name}:{gguf_file}") in self.loaded_models+            return [+                {+                    "owned_by": model_owner(repo),+                    "id": self.force_model,+                    "object": "model",+                    "created": 0,+                    "status": {"value": "loaded" if is_loaded else "unloaded"},+                }+            ] -        generative_models = []-        logger.warning("Scanning the cache directory for LLMs and VLMs.")--        for repo in tqdm(scan_cache_dir(cache_dir).repos):-            if repo.repo_type != "model":-                continue--            for ref, revision_info in repo.refs.items():-                author = repo.repo_id.split("/")[0] if "/" in repo.repo_id else ""--                # One quantization per file, each a separate model, so list files rather than the repo.-                gguf_files = sorted(f.file_name for f in revision_info.files if f.file_name.endswith(".gguf"))-                for gguf_file in gguf_files:-                    generative_models.append(-                        {-                            "owned_by": author,-                            "id": f"{repo.repo_id}:{gguf_file}",-                            "object": "model",-                            "created": repo.last_modified,-                        }-                    )--                config_path = next((f.file_path for f in revision_info.files if f.file_name == "config.json"), None)-                if not config_path:-                    continue--                config = json.loads(config_path.open().read())-                if not isinstance(config, dict):-                    continue--                architectures = config.get("architectures") or []-                llms = MODEL_FOR_CAUSAL_LM_MAPPING_NAMES.values()-                vlms = MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES.values()-                multimodal = MODEL_FOR_MULTIMODAL_LM_MAPPING_NAMES.values()--                if any(arch for arch in architectures if arch in [*llms, *vlms, *multimodal]):-                    repo_handle = repo.repo_id + (f"@{ref}" if ref != "main" else "")-                    generative_models.append(-                        {-                            "owned_by": author,-                            "id": repo_handle,-                            "object": "model",-                            "created": repo.last_modified,-                        }-                    )--        return generative_models+        try:+            models = list(get_gen_models(cache_dir))+        except CacheNotFound:+            # Nothing was downloaded yet, as in a fresh container.+            models = []++        loaded_models = {}+        for name in list(self.loaded_models):+            name, gguf_file = split_model_id(name)+            model_id, revision = split_revision(name)+            owned_by = model_owner(model_id)+            # Named as the cache names them: `main` is left out, a GGUF file comes after a colon.+            if revision not in (None, "main"):+                model_id = f"{model_id}@{revision}"+            if gguf_file is not None:+                model_id = f"{model_id}:{gguf_file}"+            # `created` is the date of a checkpoint, which is only known for the ones of the cache.+            loaded_models[model_id] = {"owned_by": owned_by, "id": model_id, "object": "model", "created": 0}++        listed = {model["id"] for model in models}+        models += [model for model_id, model in loaded_models.items() if model_id not in listed]++        # `status` is not an OpenAI field: it tells which of the listed models are in memory.+        for index, model in enumerate(models):+            status = "loaded" if model["id"] in loaded_models else "unloaded"+            models[index] = {**model, "status": {"value": status}}+        return models
src/transformers/cli/serving/server.py1 + / 1 −
@@ -145,7 +145,7 @@ def reset():     @app.get("/v1/models")     @app.options("/v1/models")     def list_models():-        return JSONResponse({"object": "list", "data": model_manager.get_gen_models()})+        return JSONResponse({"object": "list", "data": model_manager.list_models()})      @app.get("/health")     def health():
src/transformers/cli/serving/utils.py60 + / 0 −
@@ -25,9 +25,13 @@ from collections.abc import Callable from concurrent.futures import Future from dataclasses import dataclass+from functools import lru_cache from queue import Queue from typing import TYPE_CHECKING +from huggingface_hub import scan_cache_dir+from tqdm import tqdm+ from transformers.utils import logging from transformers.utils.chat_parsing import ResponseParser from transformers.utils.chat_template_utils import _REASONING_FIELDS@@ -82,6 +86,62 @@ def split_revision(model_id_and_revision: str) -> tuple[str, str | None]:     return model_id, revision or None  +def model_owner(model_id: str) -> str:+    """Owner of a model for `/v1/models`: `"local"` for a local path, the organization of a Hub repo."""+    if os.path.exists(model_id):+        return "local"+    return model_id.split("/")[0] if "/" in model_id else ""+++@lru_cache+def get_gen_models(cache_dir: str | None = None) -> list[dict]:+    """List generative models (LLMs and VLMs) available in the HuggingFace cache.++    Args:+        cache_dir (`str`, *optional*): Path to the HuggingFace cache directory.+            Defaults to the standard cache location.++    Returns:+        `list[dict]`: OpenAI-compatible model list entries with ``id``, ``object``, etc.+    """+    from transformers.models.auto.modeling_auto import (+        MODEL_FOR_CAUSAL_LM_MAPPING_NAMES,+        MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES,+        MODEL_FOR_MULTIMODAL_LM_MAPPING_NAMES,+    )++    generative_architectures = {+        *MODEL_FOR_CAUSAL_LM_MAPPING_NAMES.values(),+        *MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES.values(),+        *MODEL_FOR_MULTIMODAL_LM_MAPPING_NAMES.values(),+    }++    generative_models = []+    for repo in tqdm(scan_cache_dir(cache_dir).repos):+        if repo.repo_type != "model":+            continue+        owned_by = repo.repo_id.split("/")[0] if "/" in repo.repo_id else ""++        for ref, revision_info in repo.refs.items():+            # One quantization per file, each a separate model, so list files rather than the repo.+            gguf_files = sorted(f.file_name for f in revision_info.files if f.file_name.endswith(".gguf"))+            model_ids = [f"{repo.repo_id}:{gguf_file}" for gguf_file in gguf_files]++            # The repo itself is listed when its config names a generative architecture.+            config_path = next((f.file_path for f in revision_info.files if f.file_name == "config.json"), None)+            config = json.loads(config_path.read_text()) if config_path is not None else None+            architectures = (config.get("architectures") or []) if isinstance(config, dict) else []+            if any(architecture in generative_architectures for architecture in architectures):+                model_ids.append(repo.repo_id if ref == "main" else f"{repo.repo_id}@{ref}")++            for model_id in model_ids:+                generative_models.append(+                    {"owned_by": owned_by, "id": model_id, "object": "model", "created": int(repo.last_modified)}+                )++    return generative_models++ class Modality(enum.Enum):     LLM = "LLM"     VLM = "VLM"
tests/cli/test_serve.py41 + / 3 −
@@ -43,6 +43,7 @@     Modality,     ToolCall,     build_response_parser,+    get_gen_models,     get_response_template,     parse_assistant_message,     response_events_to_chunks,@@ -378,7 +379,7 @@ def test_lists_only_generative_models(self):             hf_hub_download("Qwen/Qwen2.5-0.5B-Instruct", "config.json", cache_dir=cache_dir)             hf_hub_download("google-bert/bert-base-cased", "config.json", cache_dir=cache_dir) -            result = ModelManager.get_gen_models(cache_dir)+            result = get_gen_models(cache_dir)             model_ids = {r["id"] for r in result}              self.assertIn("Qwen/Qwen2.5-0.5B-Instruct", model_ids)@@ -397,11 +398,48 @@ def test_skips_null_architectures(self):             config = Path(hf_hub_download("google-bert/bert-base-cased", "config.json", cache_dir=cache_dir)).resolve()             config.write_text(json.dumps({**json.loads(config.read_text()), "architectures": None})) -            model_ids = {r["id"] for r in ModelManager.get_gen_models(cache_dir)}+            model_ids = {r["id"] for r in get_gen_models(cache_dir)}              self.assertIn("Qwen/Qwen2.5-0.5B-Instruct", model_ids)             self.assertNotIn("google-bert/bert-base-cased", model_ids) +    def test_list_models_without_hub_cache(self):+        # A fresh machine has no Hub cache yet: nothing to list, and no error.+        with tempfile.TemporaryDirectory() as tmp_dir:+            self.assertEqual(ModelManager().list_models(cache_dir=f"{tmp_dir}/missing"), [])++    def test_list_models_shows_downloaded_and_loaded_models(self):+        # What the Hub cache holds: two downloaded models.+        downloaded = [{"owned_by": "org", "id": name, "object": "model", "created": 0} for name in ("org/a", "org/b")]+        with (+            tempfile.TemporaryDirectory() as local_path,+            patch("transformers.cli.serving.model_manager.get_gen_models", return_value=downloaded),+        ):+            model_manager = ModelManager()+            self.addCleanup(model_manager.shutdown)+            # What loading `org/a` and a local checkpoint leaves in the manager.+            for name in ("org/a@main", local_path):+                model_manager.loaded_models[name] = TimedModel(MagicMock(), timeout_seconds=-1)++            models = model_manager.list_models()+            statuses = {model["id"]: model["status"]["value"] for model in models}++        # `org/a` is both downloaded and loaded: it is listed once. The local path is not in the Hub cache.+        self.assertEqual(len(models), 3)+        self.assertEqual(statuses, {"org/a": "loaded", "org/b": "unloaded", local_path: "loaded"})++    def test_list_models_of_a_pinned_server(self):+        # A server pinned to one model lists that model alone, whatever the Hub cache holds.+        with patch.object(ModelManager, "_load_processor"), patch.object(ModelManager, "_load_model"):+            model_manager = ModelManager(force_model="org/model")+        self.addCleanup(model_manager.shutdown)++        models = model_manager.list_models()++        self.assertEqual(len(models), 1)+        self.assertEqual(models[0]["id"], "org/model")+        self.assertEqual(models[0]["status"], {"value": "loaded"})+  @require_serve class TestBuildGenerationConfig(unittest.TestCase):@@ -648,7 +686,7 @@ class TestAppRoutes(unittest.TestCase):     @classmethod     def setUpClass(cls):         cls.model_manager = MagicMock(spec=ModelManager)-        cls.model_manager.get_gen_models.return_value = [+        cls.model_manager.list_models.return_value = [             {"id": "test/model", "owned_by": "test", "object": "model", "created": 0}         ]         cls.chat_handler = MagicMock(spec=ChatCompletionHandler)