Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio cached models: keep parsed README front matter per unchanged file (#17034)
Daniel Han46029e830675
diff --git a/studio/backend/hub/services/models/cache_inventory.py b/studio/backend/hub/services/models/cache_inventory.pyindex 2f2edb1523a..9f46aa91687 100644--- a/studio/backend/hub/services/models/cache_inventory.py+++ b/studio/backend/hub/services/models/cache_inventory.py@@ -7,6 +7,7 @@ from __future__ import annotationsimport json+import osimport asyncioimport contextvarsimport functools@@ -1137,6 +1138,64 @@ def _ships_custom_code(snapshot: Path) -> bool:return True+# Snapshot READMEs are immutable blobs and yaml.safe_load is pure Python (ms per card), so the+# listing keeps the fields it reads per stat key. A file within the settle window is not kept: a+# coarse filesystem clock can give a rewrite identical timestamps (same rule as #16320).+_CARD_FIELDS: "OrderedDict[str, tuple[tuple, tuple]]" = OrderedDict()+_CARD_FIELDS_MAX = 4096+_CARD_FIELDS_SETTLE_NS = 2_000_000_000+_CARD_FIELDS_LOCK = threading.Lock()+++def _stat_key(path: Path) -> Optional[tuple]:+ try:+ st = os.stat(path)+ except (OSError, ValueError):+ return None+ return (st.st_dev, st.st_ino, st.st_size, st.st_mtime_ns, st.st_ctime_ns)+++def _clean_card_fields(card: dict) -> tuple:+ fields = []+ for name in ("pipeline_tag", "library_name"):+ value = card.get(name)+ if isinstance(value, str) and value.strip():+ fields.append((name, value.strip()))+ tags = card.get("tags")+ if isinstance(tags, list):+ clean_tags = [tag.strip() for tag in tags if isinstance(tag, str) and tag.strip()]+ if clean_tags:+ fields.append(("tags", tuple(clean_tags)))+ return tuple(fields)+++def _model_card_fields(path: Path) -> dict:+ key = _stat_key(path)+ cache_id = str(path)+ if key is not None:+ with _CARD_FIELDS_LOCK:+ entry = _CARD_FIELDS.get(cache_id)+ if entry is not None and entry[0] == key:+ _CARD_FIELDS.move_to_end(cache_id)+ return _fields_dict(entry[1])+ fields = _clean_card_fields(_read_model_card_frontmatter(path))+ if (+ key is not None+ and time.time_ns() - max(key[3], key[4]) > _CARD_FIELDS_SETTLE_NS+ and _stat_key(path) == key+ ):+ with _CARD_FIELDS_LOCK:+ _CARD_FIELDS[cache_id] = (key, fields)+ _CARD_FIELDS.move_to_end(cache_id)+ while len(_CARD_FIELDS) > _CARD_FIELDS_MAX:+ _CARD_FIELDS.popitem(last = False)+ return _fields_dict(fields)+++def _fields_dict(fields: tuple) -> dict:+ return {name: list(value) if name == "tags" else value for name, value in fields}++def _read_model_card_frontmatter(path: Path) -> dict:try:text = path.read_text(encoding = "utf-8")@@ -1184,18 +1243,7 @@ def _cached_model_local_metadata(repo_path: Path, snapshot: Optional[Path] = Nonif isinstance(quant_method, str) and quant_method.strip():result["quant_method"] = quant_method.strip()- card = _read_model_card_frontmatter(snapshot / "README.md")- pipeline_tag = card.get("pipeline_tag")- if isinstance(pipeline_tag, str) and pipeline_tag.strip():- result["pipeline_tag"] = pipeline_tag.strip()- library_name = card.get("library_name")- if isinstance(library_name, str) and library_name.strip():- result["library_name"] = library_name.strip()- tags = card.get("tags")- if isinstance(tags, list):- clean_tags = [tag.strip() for tag in tags if isinstance(tag, str) and tag.strip()]- if clean_tags:- result["tags"] = clean_tags+ result.update(_model_card_fields(snapshot / "README.md"))return resultdiff --git a/studio/backend/hub/tests/test_model_card_frontmatter_memo.py b/studio/backend/hub/tests/test_model_card_frontmatter_memo.pynew file mode 100644index 00000000000..d643d3f80c9--- /dev/null+++ b/studio/backend/hub/tests/test_model_card_frontmatter_memo.py@@ -0,0 +1,75 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""The cached-models listing parses each README's front matter once per unchanged file."""++from collections import OrderedDict++import yaml++from hub.services.models import cache_inventory++CARD = "---\npipeline_tag: text-generation\nlibrary_name: transformers\ntags:\n- a\n- ' b '\n- 3\nmodel-index: [{name: x}]\n---\n# Model\n"+FIELDS = {"pipeline_tag": "text-generation", "library_name": "transformers", "tags": ["a", "b"]}+++def _counting_yaml(monkeypatch, settle_ns = -1):+ calls = []+ original = yaml.safe_load+ monkeypatch.setattr(yaml, "safe_load", lambda text: (calls.append(1), original(text))[1])+ monkeypatch.setattr(cache_inventory, "_CARD_FIELDS", OrderedDict(), raising = False)+ # Files the test writes are inside the settle window; most tests treat them as settled.+ monkeypatch.setattr(cache_inventory, "_CARD_FIELDS_SETTLE_NS", settle_ns, raising = False)+ return calls+++def test_an_unchanged_card_is_parsed_once_and_returned_as_a_copy(tmp_path, monkeypatch):+ calls = _counting_yaml(monkeypatch)+ card = tmp_path / "README.md"+ card.write_text(CARD, encoding = "utf-8")+ first = cache_inventory._model_card_fields(card)+ assert first == FIELDS+ first["tags"].append("mutated")+ for _ in range(3):+ assert cache_inventory._model_card_fields(card) == FIELDS+ assert len(calls) == 1+++def test_listing_metadata_carries_the_card_fields(tmp_path, monkeypatch):+ _counting_yaml(monkeypatch)+ (tmp_path / "README.md").write_text(CARD, encoding = "utf-8")+ for _ in range(2):+ meta = cache_inventory._cached_model_local_metadata(tmp_path, snapshot = tmp_path)+ assert {k: meta[k] for k in FIELDS} == FIELDS+ assert list(meta)[-3:] == ["pipeline_tag", "library_name", "tags"]+++def test_a_changed_card_is_parsed_again(tmp_path, monkeypatch):+ calls = _counting_yaml(monkeypatch)+ card = tmp_path / "README.md"+ card.write_text(CARD, encoding = "utf-8")+ assert cache_inventory._model_card_fields(card)["pipeline_tag"] == "text-generation"+ card.write_text(+ CARD.replace("text-generation", "image-text-to-text") + "more\n", encoding = "utf-8"+ )+ for _ in range(2):+ assert cache_inventory._model_card_fields(card)["pipeline_tag"] == "image-text-to-text"+ assert len(calls) == 2+++def test_a_card_inside_the_settle_window_is_parsed_every_time(tmp_path, monkeypatch):+ calls = _counting_yaml(monkeypatch, settle_ns = 3600 * 10**9)+ card = tmp_path / "README.md"+ card.write_text(CARD, encoding = "utf-8")+ for _ in range(2):+ assert cache_inventory._model_card_fields(card) == FIELDS+ assert len(calls) == 2+++def test_missing_and_plain_cards_give_no_fields(tmp_path, monkeypatch):+ _counting_yaml(monkeypatch)+ assert cache_inventory._model_card_fields(tmp_path / "missing.md") == {}+ plain = tmp_path / "README.md"+ plain.write_text("# no front matter\n", encoding = "utf-8")+ for _ in range(2):+ assert cache_inventory._model_card_fields(plain) == {}