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
Handle invalid Krea2 model indexes clearly (#9760)
alkinunffd91ac66e37
diff --git a/studio/backend/core/inference/diffusion_krea2.py b/studio/backend/core/inference/diffusion_krea2.pyindex bb11e9ea046..e3f9f3cc2f8 100644--- a/studio/backend/core/inference/diffusion_krea2.py+++ b/studio/backend/core/inference/diffusion_krea2.py@@ -104,6 +104,20 @@ def load_krea2_text_encoder(return Qwen3VLModel.from_pretrained(repo_id, config = config, dtype = dtype, **kwargs)+def _read_model_index(path: Path, source: str) -> dict[str, Any]:+ try:+ model_index = json.loads(path.read_text(encoding = "utf-8-sig"))+ # A nesting bomb raises RecursionError, not a ValueError, so it needs naming separately or it+ # stays the one raw traceback left. diffusion_families.pipeline_class_from_index does the same.+ except (OSError, UnicodeDecodeError, json.JSONDecodeError, RecursionError) as exc:+ raise ValueError(+ f"Unable to read valid model_index.json from {source} at {path}: {exc}"+ ) from exc+ if not isinstance(model_index, dict):+ raise ValueError(f"model_index.json from {source} at {path} must contain a JSON object")+ return model_index++def _load_model_index(repo_id: str,hf_token: Optional[str] = None,@@ -116,7 +130,7 @@ def _load_model_index(is_local_dir = root.is_dir()local = root / "model_index.json"if local.is_file():- return json.loads(local.read_text(encoding = "utf-8"))+ return _read_model_index(local, f"local model directory {root}")except OSError:passif is_local_dir:@@ -131,7 +145,7 @@ def _load_model_index(local_files_only = local_files_only,cache_dir = _live_cache_dir(),)- return json.loads(Path(path).read_text(encoding = "utf-8"))+ return _read_model_index(Path(path), f"Hub/cache for {repo_id}")def load_krea2_pipeline(@@ -171,6 +185,9 @@ def load_krea2_pipeline(token = hf_token or Nonecache_dir = _live_cache_dir()+ # A few KB, and it configures the components, so it is read before them: read last, a corrupt+ # index only surfaced after the encoder, the VAE and the 26 GB transformer were already built.+ model_index = _load_model_index(repo_id, hf_token = token, local_files_only = local_files_only)tokenizer = load_krea2_tokenizer(repo_id, hf_token = token, local_files_only = local_files_only)if text_encoder is None:text_encoder = load_krea2_text_encoder(@@ -200,7 +217,6 @@ def load_krea2_pipeline(local_files_only = local_files_only,cache_dir = cache_dir,)- model_index = _load_model_index(repo_id, hf_token = token, local_files_only = local_files_only)return diffusers.Krea2Pipeline(scheduler = scheduler,vae = vae,diff --git a/studio/backend/tests/test_diffusion_krea2.py b/studio/backend/tests/test_diffusion_krea2.pyindex 1d50a89b2cf..f16784120c3 100644--- a/studio/backend/tests/test_diffusion_krea2.py+++ b/studio/backend/tests/test_diffusion_krea2.py@@ -5,8 +5,10 @@from __future__ import annotations+import errnoimport jsonimport sys+from pathlib import Pathfrom types import SimpleNamespaceimport pytest@@ -64,6 +66,99 @@ def test_load_model_index_from_local_path(tmp_path):assert _load_model_index(str(tmp_path)) == {"is_distilled": True, "patch_size": 2}+def test_load_model_index_wraps_truncated_local_json(tmp_path):+ (tmp_path / "model_index.json").write_text('{"patch_size":', encoding = "utf-8")++ with pytest.raises(ValueError, match = r"model_index\.json.*local model directory") as exc_info:+ _load_model_index(str(tmp_path))++ assert isinstance(exc_info.value.__cause__, json.JSONDecodeError)+++def test_load_model_index_wraps_invalid_utf8(tmp_path):+ (tmp_path / "model_index.json").write_bytes(b'\xff{"patch_size": 2}')++ with pytest.raises(ValueError, match = r"model_index\.json.*local model directory") as exc_info:+ _load_model_index(str(tmp_path))++ assert isinstance(exc_info.value.__cause__, UnicodeDecodeError)+++def test_load_model_index_accepts_utf8_bom(tmp_path):+ (tmp_path / "model_index.json").write_bytes(b'\xef\xbb\xbf{"patch_size": 2}')++ assert _load_model_index(str(tmp_path)) == {"patch_size": 2}+++ "payload", ["[]", "null", "3", "2.5", '"str"', "true", "false", '[{"a": 1}]']+)+def test_load_model_index_rejects_non_object_json(tmp_path, payload):+ # All of these parsed and reached the caller, which then died on ``.get`` one frame away.+ (tmp_path / "model_index.json").write_text(payload, encoding = "utf-8")++ with pytest.raises(+ ValueError, match = r"model_index\.json.*must contain a JSON object"+ ) as exc_info:+ _load_model_index(str(tmp_path))++ assert exc_info.value.__cause__ is None+++def test_load_model_index_wraps_unreadable_local_file(monkeypatch, tmp_path):+ # Present but unreadable (0600, EIO, a Windows AV lock): the OSError used to be swallowed and+ # re-reported as "not found". Faulted at the read because chmod is a no-op as root.+ (tmp_path / "model_index.json").write_text('{"patch_size": 2}', encoding = "utf-8")+ original = Path.read_text++ def _deny(self, *args, **kwargs):+ if self.name == "model_index.json":+ raise PermissionError(errno.EACCES, "Permission denied")+ return original(self, *args, **kwargs)++ monkeypatch.setattr(Path, "read_text", _deny)++ with pytest.raises(ValueError, match = r"model_index\.json.*local model directory") as exc_info:+ _load_model_index(str(tmp_path))++ assert isinstance(exc_info.value.__cause__, PermissionError)+++def test_load_model_index_wraps_a_nesting_bomb(monkeypatch, tmp_path):+ # Valid JSON and valid UTF-8, so neither guard above sees it; the parser blows the stack.+ # Faulted directly because the depth is not portable: 3.14 parses what 3.10-3.13 reject.+ (tmp_path / "model_index.json").write_text('{"a": 1}', encoding = "utf-8")+ monkeypatch.setattr(+ json, "loads", lambda *args, **kwargs: (_ for _ in ()).throw(RecursionError("too deep"))+ )++ with pytest.raises(ValueError, match = r"model_index\.json.*local model directory") as exc_info:+ _load_model_index(str(tmp_path))++ assert isinstance(exc_info.value.__cause__, RecursionError)+++def test_load_model_index_missing_local_file(tmp_path):+ with pytest.raises(FileNotFoundError, match = r"model_index\.json not found in local model dir"):+ _load_model_index(str(tmp_path))+++def test_load_model_index_wraps_malformed_hub_cache_content(monkeypatch, tmp_path):+ import huggingface_hub++ downloaded = tmp_path / "downloaded-model_index.json"+ downloaded.write_text('{"patch_size":', encoding = "utf-8")+ monkeypatch.setattr(+ huggingface_hub, "hf_hub_download", lambda *_args, **_kwargs: str(downloaded)+ )++ with pytest.raises(ValueError, match = r"model_index\.json.*Hub/cache") as exc_info:+ _load_model_index("krea/Krea-2-Turbo", local_files_only = True)++ assert str(downloaded) in str(exc_info.value)+ assert isinstance(exc_info.value.__cause__, json.JSONDecodeError)++# ── pipeline assembly threads the model_index init config ────────────────────@@ -125,6 +220,46 @@ def test_load_krea2_pipeline_threads_init_config(monkeypatch, tmp_path):assert pipe.transformer is prebuilt+def test_a_corrupt_index_is_rejected_before_any_component_is_built(monkeypatch, tmp_path):+ """A few KB against the ~35 GB it configures, so it is read first. Read last, a clear message+ still costs a full load to reach, which is most of what the opaque traceback cost."""+ (tmp_path / "model_index.json").write_text('{"_class_name": "Krea2Pipe', encoding = "utf-8")++ built: list = []++ class _Records:+ def __init__(self, tag):+ self.tag = tag++ def from_pretrained(self, repo_id, **kwargs):+ built.append(self.tag)+ return SimpleNamespace(tag = self.tag)++ monkeypatch.setitem(+ sys.modules,+ "diffusers",+ SimpleNamespace(+ FlowMatchEulerDiscreteScheduler = _Records("scheduler"),+ AutoencoderKLQwenImage = _Records("vae"),+ Krea2Transformer2DModel = _Records("transformer"),+ Krea2Pipeline = lambda **kwargs: SimpleNamespace(**kwargs),+ ),+ )+ monkeypatch.setattr(+ "core.inference.diffusion_krea2.load_krea2_tokenizer",+ lambda repo_id, hf_token = None, local_files_only = False: built.append("tokenizer"),+ )+ monkeypatch.setattr(+ "core.inference.diffusion_krea2.load_krea2_text_encoder",+ lambda repo_id, dtype, hf_token = None, local_files_only = False: built.append("text_encoder"),+ )++ with pytest.raises(ValueError, match = r"model_index\.json"):+ load_krea2_pipeline(str(tmp_path), "bf16")++ assert built == []++# ── registry / trust / int8 exclusion wiring ─────────────────────────────────