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: load ComfyUI text encoder and VAE files beside a single-file DiT (#12883)
Daniel Han8e259fd05e6e
diff --git a/studio/backend/core/inference/diffusion.py b/studio/backend/core/inference/diffusion.pyindex 0e3d6a3a54b..e7057e13736 100644--- a/studio/backend/core/inference/diffusion.py+++ b/studio/backend/core/inference/diffusion.py@@ -260,7 +260,7 @@ from .diffusion_precision import (te_quant_unsupported_reason,torchao_quantize_importable,)-from .diffusion_te_prequant import te_prequant_pipe_kwargs+from .diffusion_te_prequant import supplied_component_pipe_kwargs, te_prequant_pipe_kwargsfrom .diffusion_fast_load import start_load_prefetch, stop_prefetch, te_precast_componentsfrom .diffusion_flow_shift import apply_comfy_flow_shiftfrom .diffusion_single_file_converters import (@@ -1089,6 +1089,84 @@ def _te_quant_reason(return reason+def _with_supplied_components(load: Callable[..., dict]) -> Callable[..., dict]:+ """Supplied text-encoder / VAE files replace the base repo's for this load, via a context variable the+ assembly, memory plan and status read."""++ @functools.wraps(load)+ def wrapper(self: Any, repo_id: str, **kwargs: Any) -> dict:+ from .diffusion_comfy_components import (+ reset_active_component_overrides,+ set_active_component_overrides,+ )++ text_encoder_files = kwargs.pop("text_encoder_files", None)+ vae_file = kwargs.pop("vae_file", None)+ overrides = kwargs.pop("_component_overrides", None)+ if overrides is None and (text_encoder_files or vae_file):+ fam = self.validate_load_request(+ repo_id,+ gguf_filename = kwargs.get("gguf_filename"),+ family_override = kwargs.get("family_override"),+ model_kind = kwargs.get("model_kind"),+ text_encoder_files = text_encoder_files,+ vae_file = vae_file,+ )+ hf_token = (kwargs.get("hf_token") or "").strip() or None+ base = _resolve_base_repo(repo_id, kwargs.get("base_repo"), fam, hf_token)+ overrides = self._plan_component_overrides(+ fam,+ repo_id,+ base,+ text_encoder_files,+ vae_file,+ hf_token,+ local_files_only = bool(kwargs.get("local_files_only")),+ base_local_dir = kwargs.get("_base_local_dir"),+ text_encoder_quant = kwargs.get("text_encoder_quant"),+ )+ if overrides is not None and overrides.text_encoder_components:+ kwargs["text_encoder_quant"] = _te_quant_for_supplied_encoders(+ kwargs.get("text_encoder_quant")+ )+ token = set_active_component_overrides(overrides)+ try:+ return load(self, repo_id, **kwargs)+ finally:+ reset_active_component_overrides(token)++ return wrapper+++def _te_quant_for_supplied_encoders(requested: Optional[str]) -> Optional[str]:+ """Unset / auto never re-casts a supplied encoder (it would fetch the hosted encoder the file replaces)."""+ if requested is None or str(requested).strip().lower() in ("", "auto"):+ return "none"+ return requested+++def _hub_file_size(repo_id: str, filename: str, hf_token: Optional[str]) -> int:+ try:+ from huggingface_hub import HfApi+ for info in HfApi().get_paths_info(repo_id, [filename], token = hf_token):+ return int(getattr(info, "size", 0) or 0)+ except Exception: # noqa: BLE001 - a size is a progress-bar hint, never a refusal+ pass+ return 0+++def _active_supplied_text_encoders() -> tuple[str, ...]:+ from .diffusion_comfy_components import active_component_overrides+ overrides = active_component_overrides()+ return tuple(c for c in overrides.paths if c.startswith("text_encoder")) if overrides else ()+++def _active_component_summary() -> Optional[dict]:+ from .diffusion_comfy_components import active_component_overrides+ overrides = active_component_overrides()+ return overrides.summary() if overrides is not None and overrides.files else None++@dataclass(frozen = True)class _LoadState:"""Everything about the currently-loaded pipeline, swapped as one unit."""@@ -1145,6 +1223,7 @@ class _LoadState:resolved: Optional[dict] = None# The single-file checkpoint basename this load committed (None for a pipeline). Part of the build identity.gguf_filename: Optional[str] = None+ component_files: Optional[dict] = None# The torch ordinal this pipeline's weights were placed on, or None for an automatic pick. Committed WITH the# pipeline, so a load in flight never moves the resident model's card.gpu_ordinal: Optional[int] = None@@ -2971,6 +3050,95 @@ class DiffusionBackend:return Nonereturn snapshot_root+ @staticmethod+ def _validate_component_files(+ fam: DiffusionFamily,+ kind: str,+ repo_id: str,+ text_encoder_files: Optional[Sequence[str]],+ vae_file: Optional[str],+ ) -> None:+ """Header-only, so a bad pick is a 400 before eviction. Single-file / GGUF denoisers only."""+ from .diffusion_comfy_components import validate_component_specs++ if kind not in ("gguf", "single_file") or fam.single_file_is_pipeline or fam.pipeline_only:+ raise ValueError(+ "text_encoder_file / vae_file load beside a single-file or GGUF transformer; a full pipeline "+ "(or a whole-pipeline single file) already carries its own text encoders and VAE."+ )+ if vae_file and fam.name == KREA2_FAMILY_NAME:+ raise ValueError(+ f"a separate VAE file is not supported for '{fam.name}' yet; omit vae_file."+ )+ validate_component_specs(+ list(text_encoder_files or ()),+ vae_file,+ model_path = repo_id,+ trusted_repo = _is_trusted_diffusion_repo,+ )++ def _plan_component_overrides(+ self,+ fam: DiffusionFamily,+ repo_id: str,+ base: str,+ text_encoder_files: Optional[Sequence[str]],+ vae_file: Optional[str],+ hf_token: Optional[str],+ *,+ local_files_only: bool = False,+ base_local_dir: Optional[str] = None,+ cancel_event: Optional[threading.Event] = None,+ download: bool = True,+ text_encoder_quant: Optional[str] = None,+ ) -> Any:+ if not text_encoder_files and not vae_file:+ return None+ from .diffusion_comfy_components import plan_component_overrides, read_model_index++ index = read_model_index(+ prefer_ungated_mirror(base, hf_token),+ base_local_dir = base_local_dir or (base if _is_local_path(base) else None),+ hf_token = hf_token,+ local_files_only = local_files_only,+ cache_dir = hub_cache_dir(),+ )++ def _resolve_hub(ref: Any) -> str:+ from utils.hf_xet_fallback import hf_hub_download_with_xet_fallback+ return hf_hub_download_with_xet_fallback(+ ref.repo_id,+ ref.filename,+ hf_token,+ cancel_event = cancel_event if cancel_event is not None else self._cancel_event,+ reuse_other_cache_root = True,+ local_files_only = local_files_only,+ )++ overrides = plan_component_overrides(+ text_encoder_files = list(text_encoder_files or ()),+ vae_file = vae_file,+ model_path = repo_id,+ model_index = index,+ family = fam.name,+ trusted_repo = _is_trusted_diffusion_repo,+ hf_token = hf_token,+ resolve_hub = _resolve_hub if download else None,+ )+ if download and overrides is not None:+ # The load path: fit every file to its real class before anything resident is unloaded.+ from .diffusion_comfy_components import verify_override_fit+ verify_override_fit(+ overrides,+ base = base_local_dir or prefer_ungated_mirror(base, hf_token),+ hf_token = hf_token,+ local_files_only = local_files_only,+ family = fam.name,+ cache_dir = hub_cache_dir(),+ text_encoder_quant = text_encoder_quant,+ )+ return overrides+def validate_load_request(self,repo_id: str,@@ -2979,6 +3147,8 @@ class DiffusionBackend:family_override: Optional[str] = None,model_kind: Optional[str] = None,base_repo: Optional[str] = None,+ text_encoder_files: Optional[Sequence[str]] = None,+ vae_file: Optional[str] = None,) -> DiffusionFamily:"""Cheap, network-free validation shared by the route (before it evicts the chat model) andthe load paths, so an unloadable pick fails BEFORE the GPU handoff. Resolves the load@@ -3102,6 +3272,8 @@ class DiffusionBackend:f"'{repo_id}' is a single-file GGUF repo; load it with model_kind 'gguf' "f"and a .gguf filename, not as a full pipeline.")+ if text_encoder_files or vae_file:+ self._validate_component_files(fam, kind, repo_id, text_encoder_files, vae_file)return famdef preflight_base_access(@@ -3169,6 +3341,8 @@ class DiffusionBackend:gpu_ids: Optional[list[int]] = None,# The ordinal the ROUTE already ranked, so the preflight and the load agree on one card.gpu_ordinal: Optional[int] = None,+ text_encoder_files: Optional[Sequence[str]] = None,+ vae_file: Optional[str] = None,_load_token: Optional[int] = None,) -> dict[str, Any]:"""Validate, then run the (slow) load on a daemon thread. Returns at once."""@@ -3193,6 +3367,8 @@ class DiffusionBackend:gguf_filename = gguf_filename,family_override = family_override,model_kind = model_kind,+ text_encoder_files = text_encoder_files,+ vae_file = vae_file,)# Refuse an EXPLICIT precision this host can never honor BEFORE the load starts, so the route answers 409 with# the reason instead of evicting the resident model, downloading several GB and only then failing. The@@ -3252,6 +3428,8 @@ class DiffusionBackend:model_kind = model_kind,loras = loras,gpu_ordinal = gpu_ordinal,+ text_encoder_files = list(text_encoder_files or ()) or None,+ vae_file = vae_file,_load_token = token,_cancel_event = cancel_event,),@@ -3289,6 +3467,38 @@ class DiffusionBackend:kwargs["repo_id"], kwargs.get("base_repo"), fam, kwargs.get("hf_token"))kwargs["base_repo"] = base+ # Claimed before a byte moves, so the cache-delete guard sees a Hub component repo.+ from .diffusion_comfy_components import hub_repo_ids++ component_repos = hub_repo_ids(+ kwargs.get("text_encoder_files") or (),+ kwargs.get("vae_file"),+ model_path = kwargs["repo_id"],+ )+ if component_repos:+ with self._load_cancel_lock:+ if self._load_token == token and self._loading is not None:+ self._loading.asset_repos = tuple(+ dict.fromkeys(self._loading.asset_repos + component_repos)+ )+ # Assigned before the plan so replaced components' shards are never staged.+ component_overrides = self._plan_component_overrides(+ fam,+ kwargs["repo_id"],+ base,+ kwargs.get("text_encoder_files"),+ kwargs.get("vae_file"),+ kwargs.get("hf_token"),+ local_files_only = local_files_only,+ cancel_event = cancel_event,+ text_encoder_quant = kwargs.get("text_encoder_quant"),+ )+ kwargs["_component_overrides"] = component_overrides+ replaced = tuple(component_overrides.components) if component_overrides else ()+ if component_overrides is not None and component_overrides.text_encoder_components:+ kwargs["text_encoder_quant"] = _te_quant_for_supplied_encoders(+ kwargs.get("text_encoder_quant")+ )# The pre-cast encoder replaces these weights, so skip their dense shards. Same resolver as the injection,# and the same tri-state: a family whose UNSET request resolves to a hosted scheme must not stage the dense# encoder the load is about to not open. kwargs keep the RAW request, which stays the single source of@@ -3296,14 +3506,18 @@ class DiffusionBackend:te_quant_planned, _ = resolve_te_quant_request(kwargs.get("text_encoder_quant"), getattr(fam, "te_quant_auto", None))- te_prequant_files = self._te_prequant_plan_files(- fam,- te_quant_planned,- kwargs.get("hf_token"),- kwargs.get("gpu_ordinal"),- local_files_only = local_files_only,- base_repo = base,- )+ te_prequant_files = {+ c: v+ for c, v in self._te_prequant_plan_files(+ fam,+ te_quant_planned,+ kwargs.get("hf_token"),+ kwargs.get("gpu_ordinal"),+ local_files_only = local_files_only,+ base_repo = base,+ ).items()+ if c not in replaced+ }pipeline_planned = self._pipeline_planned_denoiser_scheme(fam,base = base,@@ -3365,7 +3579,7 @@ class DiffusionBackend:if kind == "gguf"else False),- skip_te_components = tuple(te_prequant_files),+ skip_te_components = tuple(te_prequant_files) + replaced,skip_transformer_weights = skip_transformer_weights,skipped_files_out = skipped_transformer_files,local_files_only = local_files_only,@@ -4399,6 +4613,29 @@ class DiffusionBackend:incompatible = flux2_pick_mismatch(fam, repo_id, gguf_filename, base, hf_token) or speech_pick_refusal(repo_id, gguf_filename, hf_token)+ component_overrides = None+ if (+ load_kwargs.get("text_encoder_files") or load_kwargs.get("vae_file")+ ) and fam is not None:+ self._validate_component_files(+ fam,+ kind,+ repo_id,+ load_kwargs.get("text_encoder_files"),+ load_kwargs.get("vae_file"),+ )+ component_overrides = self._plan_component_overrides(+ fam,+ repo_id,+ base,+ load_kwargs.get("text_encoder_files"),+ load_kwargs.get("vae_file"),+ hf_token,+ download = False,+ )+ replaced = tuple(component_overrides.components) if component_overrides else ()+ if component_overrides is not None and component_overrides.text_encoder_components:+ text_encoder_quant = _te_quant_for_supplied_encoders(text_encoder_quant)# Only a checkpoint that really resolves on the Hub earns the right to drop dense shards# Resolved through the same tri-state the loader uses, so the size the picker SHOWS is the size the load will# actually move on a family whose unset request takes a hosted encoder.@@ -4406,13 +4643,17 @@ class DiffusionBackend:text_encoder_quant, getattr(fam, "te_quant_auto", None))te_files = (- self._te_prequant_plan_files(- fam,- te_quant_planned,- hf_token,- load_kwargs.get("gpu_ordinal"),- base_repo = base,- )+ {+ c: v+ for c, v in self._te_prequant_plan_files(+ fam,+ te_quant_planned,+ hf_token,+ load_kwargs.get("gpu_ordinal"),+ base_repo = base,+ ).items()+ if c not in replaced+ }if allow_device_probeelse {})@@ -4495,7 +4736,7 @@ class DiffusionBackend:resident_file_sizes_out = resident_file_sizes,revisions_out = revisions,fetch_repos_out = fetch_repos,- skip_te_components = tuple(te_files),+ skip_te_components = tuple(te_files) + replaced,skip_transformer_weights = skip_transformer_weights,failures_out = plan_failures,)@@ -4671,6 +4912,12 @@ class DiffusionBackend:# Staged, not just counted: leaving it out means a multi-GB inline pull under the load lock.prequant_repo, prequant_file, prequant_size = dit_prequantadd_missing_entry(prequant_repo, [prequant_file], {prequant_file: prequant_size})+ for ref in component_overrides.files.values() if component_overrides else ():+ if not ref.is_hub:+ continue+ ref_size = _hub_file_size(ref.repo_id, ref.filename, hf_token)+ required_total += ref_size+ add_missing_entry(ref.repo_id, [ref.filename], {ref.filename: ref_size})if incompatible is None and allow_device_probe and memory_verdict:incompatible = self.declared_footprint_shortfall(fam,@@ -5230,6 +5477,41 @@ class DiffusionBackend:merged[rel] = max(merged.get(rel, 0), count)return sum(merged.values())+ @staticmethod+ def _supplied_component_mib(+ base: str, staged_dir: Optional[str], load_dtype: Any+ ) -> Optional[tuple[int, int, int, int]]:+ """``(scanned MiB, scanned TE MiB, supplied MiB, supplied TE MiB)``; scanned = what the base-repo walk+ counted for the replaced components."""+ from .diffusion_comfy_components import active_component_overrides, scanned_component_bytes++ overrides = active_component_overrides()+ if overrides is None or not overrides.paths:+ return None+ replaced = set(overrides.paths)+ replaced_te = {c for c in replaced if c.startswith("text_encoder")}++ def _scan(components: set) -> int:+ return DiffusionBackend._union_over_cached_revs(+ base,+ lambda d: scanned_component_bytes(+ DiffusionBackend._local_dir_weight_sizes(+ d, exclude_transformer = True, load_dtype = load_dtype+ ),+ components,+ ),+ staged_dir,+ )++ mib = 1024 * 1024+ resident = overrides.resident_mib(_float_load_itemsize(load_dtype) or 2)+ return (+ _scan(replaced) // mib,+ (_scan(replaced_te) // mib) if replaced_te else 0,+ int(sum(resident.values())),+ int(sum(v for c, v in resident.items() if c in replaced_te)),+ )+@staticmethoddef _companion_cache_bytes(base: str,@@ -5287,6 +5569,7 @@ class DiffusionBackend:target: Any,text_encoder_quant: Optional[str],staged_dir: Optional[str] = None,+ skip_components: tuple[str, ...] = (),) -> Optional[tuple[int, tuple[str, ...], bool]]:"""``(MiB, components, exact)`` for the hosted pre-cast text encoder(s) this pick loads, or None.@@ -5308,6 +5591,7 @@ class DiffusionBackend:sources = te_prequant_sources_for_base(fam, base, te_quant_mode = text_encoder_quant, target = target, **extra)+ sources = {c: v for c, v in (sources or {}).items() if c not in skip_components}if not sources:return Nonetotal = 0@@ -5427,6 +5711,7 @@ class DiffusionBackend:@_account_owned_load@_plans_at_requested_speed@scoped_local_files_only+ @_with_supplied_componentsdef load_pipeline(self,repo_id: str,@@ -7814,6 +8099,7 @@ class DiffusionBackend:hf_token = hf_token,resolved = resolved,gguf_filename = gguf_filename,+ component_files = _active_component_summary(),variant_hint = _image_variant_hint(fam.name,Path(single_file_path).name if single_file_path else None,@@ -8273,6 +8559,15 @@ class DiffusionBackend:))check_cancelled()+ pipe_kwargs.update(+ supplied_component_pipe_kwargs(+ base_local_dir or base,+ dtype = dtype,+ hf_token = hf_token,+ local_files_only = local_files_only,+ family = getattr(fam, "name", None),+ )+ )pipe = pipeline_cls.from_pretrained(base_local_dir or base, **pipe_kwargs)check_cancelled()pipe.to(device)@@ -8891,6 +9186,7 @@ class DiffusionBackend:if _float_load_itemsize(load_dtype) is None:load_dtype = Nonecompanions_from_cache = False+ supplied_te: tuple[str, ...] = ()if kind == "pipeline" and transformer_resident_override_mib is not None:# Re-planning an assembled pipeline against its dense-quant candidate. The family estimate already# splits transformer from companions; the cache scan below would price the bf16 transformer this@@ -9039,12 +9335,29 @@ class DiffusionBackend:)text_encoder_mib = int(text_encoder // (1024 * 1024)) if text_encoder else Nonecompanions_from_cache = True+ # Price supplied files instead of the replaced components a cached base repo still holds.+ supplied = self._supplied_component_mib(+ fetch_base or base, base_local_dir, load_dtype+ )+ if supplied is not None:+ scanned_mib, scanned_te_mib, supplied_mib, supplied_te_mib = supplied+ companion_mib = max(0, int(companion_mib or 0) - scanned_mib) + supplied_mib+ text_encoder_mib = (+ max(0, int(text_encoder_mib or 0) - scanned_te_mib) + supplied_te_mib+ ) or None+ supplied_te = _active_supplied_text_encoders()model_dense_mib = Noneif transformer_resident is not None:model_dense_mib = transformer_resident + (companion_mib or 0)if companions_from_cache and text_encoder_quant is not None:+ # Supplied encoders are priced above; only the slots they leave to a hosted pre-cast count here.precast = self._precast_text_encoder_mib(- fam, base, target, text_encoder_quant, base_local_dir+ fam,+ base,+ target,+ text_encoder_quant,+ base_local_dir,+ **({"skip_components": supplied_te} if supplied_te else {}),)if precast:precast_mib, precast_components, _exact = precast@@ -10866,6 +11179,7 @@ class DiffusionBackend:"dtype": state.dtype,"model_kind": state.kind,"gguf_filename": state.gguf_filename,+ "component_files": state.component_files,"gguf_variant": (extract_quant_token(state.gguf_filename)if state.kind == "gguf" and state.gguf_filenamediff --git a/studio/backend/core/inference/diffusion_comfy_components.py b/studio/backend/core/inference/diffusion_comfy_components.pynew file mode 100644index 00000000000..a1fd9fa18d9--- /dev/null+++ b/studio/backend/core/inference/diffusion_comfy_components.py@@ -0,0 +1,1273 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Separate text-encoder / VAE files (ComfyUI ``models/text_encoders``, ``models/vae``) beside a single-file DiT.++Each file is classified from its header, assigned to the base pipeline slot whose class it fits, renamed under a+rule that loads strictly, and built from the base repo's config (which still supplies configs and tokenizers).+fp8 dequantizes, int8 ConvRot stays int8, every other ComfyUI quant format is refused by name.+"""++from __future__ import annotations++import contextvars+import json+import os+import re+from dataclasses import dataclass, field+from pathlib import Path+from typing import Any, Callable, Iterable, Optional, Sequence++COMPONENT_VAE = "vae"+TEXT_ENCODER_COMPONENTS = ("text_encoder", "text_encoder_2", "text_encoder_3", "text_encoder_4")+MAX_TEXT_ENCODER_FILES = len(TEXT_ENCODER_COMPONENTS)+COMPONENT_FILE_SUFFIX = ".safetensors"+_NON_WEIGHT_KEYS = frozenset({"scaled_fp8", "tekken_model", "spiece_model"})+_QUANT_COMPANION_SUFFIXES = (+ ".comfy_quant",+ ".weight_scale",+ ".weight_scale_2",+ ".input_scale",+ ".pre_quant_scale",+ ".weight_s_rel",+ ".weight_s_channel",+ ".weight_codebook",+ ".scale_weight",+ ".scale_input",+)++TE_KIND_CLASSES: dict[str, frozenset] = {+ "clip_l": frozenset({"CLIPTextModel", "CLIPTextModelWithProjection"}),+ "clip_g": frozenset({"CLIPTextModelWithProjection", "CLIPTextModel"}),+ "t5": frozenset({"T5EncoderModel"}),+ "umt5": frozenset({"UMT5EncoderModel"}),+ "qwen3": frozenset({"Qwen3Model", "Qwen3ForCausalLM"}),+ "qwen2_5_vl": frozenset({"Qwen2_5_VLForConditionalGeneration", "Qwen2_5_VLModel"}),+ "qwen3_vl": frozenset({"Qwen3VLForConditionalGeneration", "Qwen3VLModel"}),+ "mistral3": frozenset({"Mistral3ForConditionalGeneration", "Mistral3Model"}),+ "llama": frozenset({"LlamaForCausalLM", "LlamaModel"}),+ "gemma2": frozenset({"Gemma2Model", "Gemma2ForCausalLM"}),+ "gemma3": frozenset({"Gemma3ForConditionalGeneration", "Gemma3Model", "Gemma3ForCausalLM"}),+}+# File kind -> diffusers VAE classes it can fill. Qwen-Image's VAE is the Wan 2.1 layout.+VAE_KIND_CLASSES: dict[str, frozenset] = {+ "ldm_kl": frozenset({"AutoencoderKL", "AutoencoderKLFlux2"}),+ "wan": frozenset({"AutoencoderKLWan", "AutoencoderKLQwenImage"}),+ # Wan 2.2 / Qwen-Image-2.1: residual blocks and the resampler nested under one ``downsamples.<i>`` stage.+ "wan_nested": frozenset({"AutoencoderKLWan", "AutoencoderKLQwenImage21"}),+ "diffusers": frozenset(+ {+ "AutoencoderKL",+ "AutoencoderKLFlux2",+ "AutoencoderKLWan",+ "AutoencoderKLQwenImage",+ "AutoencoderKLQwenImage21",+ }+ ),+}++# Slots a family loads from their own repo (not ``<base>/<slot>``), so a supplied file has no config to fit.+_STANDALONE_TE_SLOTS: dict[str, tuple[str, ...]] = {"hidream-i1": ("text_encoder_4",)}++# Tensors a ComfyUI file may carry that the diffusers-side class never reads. Everything else must match.+_DEAD_UNEXPECTED = (+ re.compile(r"(^|\.)position_ids$"),+ re.compile(r"^logit_scale$"),+ re.compile(r"^text_projection\.weight$"), # full-CLIP export into CLIPTextModel+ re.compile(r"^lm_head\.weight$"), # class without (or a trimmed) lm_head+ re.compile(r"(^|\.)num_batches_tracked$"),+)+_DEAD_MISSING = (+ re.compile(r"(^|\.)position_ids$"),+ re.compile(r"^encoder\.embed_tokens\.weight$"), # T5 / UMT5: tied to shared.weight+)+++class ComponentFileError(ValueError):+ """A supplied text-encoder / VAE file this load cannot use; the message names the file and why."""+++@dataclass(frozen = True)+class ComponentFileRef:+ """One request-supplied file: a local path, or ``owner/repo/path/in/repo.safetensors`` on the Hub."""++ spec: str+ local_path: Optional[str] = None+ repo_id: Optional[str] = None+ filename: Optional[str] = None++ @property+ def name(self) -> str:+ return os.path.basename(self.local_path or self.filename or self.spec)++ @property+ def is_hub(self) -> bool:+ return self.repo_id is not None+++def normalize_text_encoder_files(value: Any) -> list[str]:+ """The request's ``text_encoder_file`` (one string or a list) as a deduplicated list of specs."""+ if value is None:+ return []+ items = [value] if isinstance(value, str) else list(value)+ out: list[str] = []+ for item in items:+ if not isinstance(item, str):+ raise ComponentFileError("text_encoder_file entries must be strings")+ item = item.strip()+ if item and item not in out:+ out.append(item)+ if len(out) > MAX_TEXT_ENCODER_FILES:+ raise ComponentFileError(+ f"at most {MAX_TEXT_ENCODER_FILES} text-encoder files can be supplied; got {len(out)}"+ )+ return out+++def _path_shaped(spec: str) -> bool:+ return (+ spec.startswith(("/", "\\", "~", "."))+ or "\\" in spec+ or bool(re.match(r"^[A-Za-z]:[\\/]", spec))+ or Path(spec).is_absolute()+ )+++def parse_component_file(+ spec: str,+ *,+ model_path: Optional[str] = None,+ trusted_repo: Optional[Callable[[str], bool]] = None,+ what: str = "text_encoder_file",+) -> ComponentFileRef:+ """Validate one spec without touching the network. Local: an existing ``.safetensors`` file (a relative or+ bare name resolves against a local ``model_path`` directory, so a ComfyUI ``models/`` tree works with+ ``../text_encoders/x.safetensors``). Hub: ``owner/repo/path.safetensors`` held to ``trusted_repo``, the+ same bar a single-file DiT clears."""+ spec = (spec or "").strip()+ if not spec:+ raise ComponentFileError(f"{what} is empty")+ if not spec.lower().endswith(COMPONENT_FILE_SUFFIX):+ raise ComponentFileError(+ f"{what} '{os.path.basename(spec)}' is not a .safetensors file; only .safetensors "+ "text-encoder / VAE files are supported"+ )+ root: Optional[Path] = None+ if model_path:+ try:+ candidate = Path(model_path).expanduser()+ if candidate.is_dir():+ root = candidate+ elif candidate.is_file():+ root = candidate.parent+ except OSError:+ root = None+ local: Optional[Path] = None+ if root is not None and not _path_shaped(spec) and (root / spec).is_file():+ local = (+ root / spec+ ) # an existing file under model_path wins over the owner/repo/file reading+ elif _path_shaped(spec):+ local = Path(spec).expanduser()+ if not local.is_absolute():+ if root is None:+ raise ComponentFileError(+ f"{what} '{spec}' is a relative path, but model_path is not a local directory "+ "to resolve it against; pass an absolute path"+ )+ local = root / local+ elif "/" not in spec.replace("\\", "/"):+ if root is None:+ raise ComponentFileError(+ f"{what} '{spec}' names no directory; pass an absolute path or owner/repo/file.safetensors"+ )+ local = root / spec+ if local is not None:+ try:+ resolved = local.resolve()+ except OSError as exc:+ raise ComponentFileError(f"{what} '{spec}' cannot be resolved: {exc}") from exc+ if not resolved.is_file():+ raise ComponentFileError(f"{what} '{spec}' does not exist or is not a file")+ return ComponentFileRef(spec = spec, local_path = str(resolved))+ parts = spec.replace("\\", "/").split("/")+ if len(parts) < 3 or not all(parts):+ raise ComponentFileError(+ f"{what} '{spec}' is neither a local file nor owner/repo/path/to/file.safetensors"+ )+ repo_id, filename = "/".join(parts[:2]), "/".join(parts[2:])+ if trusted_repo is not None and not trusted_repo(repo_id):+ raise ComponentFileError(+ f"{what} from the Hub is restricted to the same repos as a single-file transformer "+ f"(unsloth/* or a local path); got '{repo_id}'"+ )+ return ComponentFileRef(spec = spec, repo_id = repo_id, filename = filename)+++def read_safetensors_header(path: str) -> tuple[dict[str, dict], dict]:+ """``({tensor: {"dtype", "shape", "data_offsets"}}, metadata)`` from the file header alone."""+ from .diffusion_comfy_quant import _read_header++ try:+ header, _ = _read_header(str(path))+ except Exception as exc: # noqa: BLE001+ raise ComponentFileError(+ f"'{os.path.basename(path)}' is not a readable safetensors file: {exc}"+ )+ metadata = header.pop("__metadata__", None) or {}+ return header, metadata if isinstance(metadata, dict) else {}+++def weight_keys(header: dict[str, Any]) -> list[str]:+ """The header's weight tensors: quant companions, tokenizer blobs and markers left out."""+ return [+ k for k in header if k not in _NON_WEIGHT_KEYS and not k.endswith(_QUANT_COMPANION_SUFFIXES)+ ]+++def classify_text_encoder(+ keys: Iterable[str], shapes: Optional[dict[str, Sequence[int]]] = None+) -> Optional[str]:+ """The text-encoder kind of a ComfyUI / original-layout header, or None when it is not one."""+ keyset = set(keys)++ def has(prefix: str) -> bool:+ return any(k.startswith(prefix) for k in keyset)++ if has("text_model.encoder.layers."):+ width = None+ shape = (shapes or {}).get("text_model.embeddings.token_embedding.weight")+ if shape and len(shape) == 2:+ width = int(shape[1])+ return "clip_g" if width == 1280 else "clip_l"+ if has("encoder.block.") and ("shared.weight" in keyset or has("encoder.embed_tokens.")):+ umt5 = any(+ re.match(+ r"^encoder\.block\.[1-9]\d*\.layer\.0\.SelfAttention\.relative_attention_bias\.", k+ )+ for k in keyset+ )+ return "umt5" if umt5 else "t5"+ lm_prefix = "model.language_model." if has("model.language_model.layers.") else "model."+ if not has(lm_prefix + "layers."):+ return None+ q_norm = has(lm_prefix + "layers.0.self_attn.q_norm.")+ if has(lm_prefix + "layers.0.pre_feedforward_layernorm."):+ return (+ "gemma3" if (q_norm or has("vision_model.") or has("model.vision_tower.")) else "gemma2"+ )+ if has("visual.") or has("model.visual."):+ return "qwen3_vl" if q_norm else "qwen2_5_vl"+ if (+ has("vision_tower.")+ or has("model.vision_tower.")+ or has("multi_modal_projector.")+ or "tekken_model" in keyset+ ):+ return "mistral3"+ if q_norm:+ return "qwen3"+ return "llama"+++def classify_vae(keys: Iterable[str]) -> Optional[str]:+ keyset = set(keys)++ def has(prefix: str) -> bool:+ return any(k.startswith(prefix) for k in keyset)++ if any(+ re.match(r"^(encoder\.downsamples|decoder\.upsamples)\.\d+\.(downsamples|upsamples)\.", k)+ for k in keyset+ ):+ return "wan_nested"+ if has("decoder.upsamples.") or has("encoder.downsamples."):+ return "wan"+ if has("decoder.up.") or has("encoder.down.") or has("first_stage_model.decoder.up."):+ return "ldm_kl"+ if has("decoder.up_blocks.") or has("encoder.down_blocks."):+ return "diffusers"+ return None+++def _rule_identity(key: str) -> str:+ return key+++def _rule_strip_model(key: str) -> Optional[str]:+ if key.startswith("model."):+ return key[len("model.") :]+ if key.startswith("lm_head."):+ return key # left unexpected; dead for a headless class+ return key+++_VL_KEEP = (+ "model.visual.",+ "model.language_model.",+ "model.vision_tower.",+ "model.multi_modal_projector.",+)+++def _rule_nest_language_model(key: str) -> str:+ # transformers >= 4.52 (and 5.x) nest the decoder under ``model.language_model`` and the vision tower under+ # ``model.visual`` / ``model.vision_tower``; ComfyUI keeps the flat pre-4.52 layout.+ if key.startswith(_VL_KEEP) or key.startswith("lm_head."):+ return key+ if key.startswith("visual."):+ return "model." + key+ if key.startswith("vision_tower."):+ return "model." + key+ if key.startswith("vision_model."):+ return "model.vision_tower." + key+ if key.startswith("multi_modal_projector."):+ return "model." + key+ if key.startswith("model."):+ return "model.language_model." + key[len("model.") :]+ return key+++KEY_RULES: tuple[tuple[str, Callable[[str], Optional[str]]], ...] = (+ ("identity", _rule_identity),+ ("strip_model_prefix", _rule_strip_model),+ ("nest_language_model", _rule_nest_language_model),+ ("nest_language_model_headless", lambda k: _rule_strip_model(_rule_nest_language_model(k))),+)+++@dataclass+class KeyMapping:+ rule: str+ mapping: dict[str, str] # file key -> model key+ dead_unexpected: list[str] = field(default_factory = list)+ dead_missing: list[str] = field(default_factory = list)+++def _is_dead(key: str, patterns: Sequence[Any]) -> bool:+ return any(p.search(key) for p in patterns)+++def match_keys(+ file_shapes: dict[str, Sequence[int]],+ expected: dict[str, Sequence[int]],+ *,+ tied_missing: Iterable[str] = (),+ rules: Sequence[tuple[str, Callable[[str], Optional[str]]]] = KEY_RULES,+) -> KeyMapping:+ """The first rename rule under which ``file_shapes`` loads STRICTLY into ``expected``: every expected+ tensor present with the same shape, nothing extra except the known-dead tensors. ``tied_missing``+ names model tensors the class re-ties after loading (an ``lm_head`` tied to the embedding).+ Raises ``ComponentFileError`` with the closest rule's diagnostics."""+ tied = set(tied_missing)+ best: Optional[tuple[int, str, list, list, list]] = None+ for name, rule in rules:+ mapping: dict[str, str] = {}+ collisions = False+ for key in file_shapes:+ new = rule(key)+ if new is None:+ continue+ if new in mapping.values():+ collisions = True+ break+ mapping[key] = new+ if collisions:+ continue+ reverse = {v: k for k, v in mapping.items()}+ missing = [+ k+ for k in expected+ if k not in reverse and k not in tied and not _is_dead(k, _DEAD_MISSING)+ ]+ unexpected = [+ k for k, v in mapping.items() if v not in expected and not _is_dead(v, _DEAD_UNEXPECTED)+ ]+ mismatched = [+ f"{k} {list(file_shapes[k])} != {list(expected[v])}"+ for k, v in mapping.items()+ if v in expected+ and tuple(int(d) for d in file_shapes[k]) != tuple(int(d) for d in expected[v])+ ]+ score = len(missing) + len(unexpected) + len(mismatched)+ if score == 0:+ return KeyMapping(+ rule = name,+ mapping = {k: v for k, v in mapping.items() if v in expected},+ dead_unexpected = sorted(k for k, v in mapping.items() if v not in expected),+ dead_missing = sorted(k for k in expected if k not in reverse),+ )+ if best is None or score < best[0]:+ best = (score, name, missing, unexpected, mismatched)+ if best is None:+ raise ComponentFileError("no key rule applies")+ _, name, missing, unexpected, mismatched = best+ parts = []+ if missing:+ parts.append(f"{len(missing)} missing (e.g. {', '.join(sorted(missing)[:3])})")+ if unexpected:+ parts.append(f"{len(unexpected)} unexpected (e.g. {', '.join(sorted(unexpected)[:3])})")+ if mismatched:+ parts.append(f"{len(mismatched)} shape mismatches (e.g. {'; '.join(mismatched[:2])})")+ raise ComponentFileError("; ".join(parts) + f" under the closest key rule '{name}'")+++def quant_layers(path: str) -> dict[str, Any]:+ """``{layer name (file naming, no .weight): ComfyQuantLayer}``; raises for a format Studio cannot run."""+ from .diffusion_comfy_quant import scan_comfy_quant++ scan = scan_comfy_quant(path)+ if scan is None:+ return {}+ if scan.problems:+ shown = "; ".join(scan.problems[:3])+ more = f" (and {len(scan.problems) - 3} more)" if len(scan.problems) > 3 else ""+ raise ComponentFileError(+ f"'{os.path.basename(path)}' uses a ComfyUI quantization Studio cannot load as a text encoder "+ f"or VAE: {shown}{more}. Supported: unquantized, scaled fp8 (float8_e4m3fn / float8_e5m2) and "+ "int8_tensorwise (with or without ConvRot); use the bf16 or fp8 file instead."+ )+ return dict(scan.layers)+++_HEADER_DTYPE_BYTES = {+ "F64": 8,+ "I64": 8,+ "U64": 8,+ "F32": 4,+ "I32": 4,+ "U32": 4,+ "F16": 2,+ "BF16": 2,+ "I16": 2,+ "U16": 2,+ "F8_E4M3": 1,+ "F8_E5M2": 1,+ "I8": 1,+ "U8": 1,+ "BOOL": 1,+}+++def _numel(shape: Sequence[int]) -> int:+ n = 1+ for d in shape:+ n *= int(d)+ return n+++def resident_bytes(+ path: str,+ *,+ dtype_itemsize: int = 2,+ kind: str = "text_encoder",+) -> int:+ """What the loaded component holds: int8 ConvRot Linears at stored size (+ scales), every other weight+ (dequantized fp8 included) at the compute dtype. Header-only."""+ header, _ = read_safetensors_header(path)+ layers = quant_layers(path) if kind != COMPONENT_VAE else {}+ total = 0+ for key in weight_keys(header):+ entry = header[key]+ shape = entry.get("shape") or ()+ dtype = str(entry.get("dtype", ""))+ layer = layers.get(key[: -len(".weight")]) if key.endswith(".weight") else None+ if layer is not None and layer.convrot and layer.format == "int8_tensorwise":+ total += _numel(shape) + int(shape[0]) * 4+ elif dtype in ("F32", "F16", "BF16", "F8_E4M3", "F8_E5M2", "I8", "U8") or layer is not None:+ total += _numel(shape) * dtype_itemsize+ else:+ total += _numel(shape) * _HEADER_DTYPE_BYTES.get(dtype, dtype_itemsize)+ return total+++def _fp8_view(codes: Any, fmt: str) -> Any:+ import torch+ if codes.dtype == torch.uint8:+ return codes.view(torch.float8_e5m2 if fmt == "float8_e5m2" else torch.float8_e4m3fn)+ return codes+++def _dequant_fp8(codes: Any, scale: Optional[Any], fmt: str, dtype: Any) -> Any:+ import torch++ weight = _fp8_view(codes, fmt).to(torch.float32)+ if scale is not None:+ s = scale.to(torch.float32)+ weight = weight * (s.reshape(-1, 1) if s.numel() > 1 else s.reshape(()))+ return weight.to(dtype)+++def _expected_shapes(module: Any) -> dict[str, tuple]:+ return {k: tuple(v.shape) for k, v in module.state_dict().items()}+++def _file_logical_shapes(header: dict) -> dict[str, tuple]:+ return {k: tuple(int(d) for d in (header[k].get("shape") or ())) for k in weight_keys(header)}+++def _strip_meta(module: Any) -> list[str]:+ stranded = [n for n, p in module.named_parameters() if p.is_meta]+ stranded += [n for n, b in module.named_buffers() if b is not None and b.is_meta]+ return stranded+++def _fit_text_encoder(+ path: str, header: dict, encoder_cls: Any, config: Any, trim_lm_head: bool+) -> tuple[Any, KeyMapping, tuple]:+ """``encoder_cls`` on the meta device plus the strict key mapping of ``header`` onto it."""+ from accelerate import init_empty_weights++ from .diffusion_text_encoder_trim import config_ties_lm_head, trim_text_encoder++ with init_empty_weights(include_buffers = False):+ encoder = encoder_cls(config)+ if trim_lm_head:+ trim_text_encoder(encoder)+ expected = _expected_shapes(encoder)+ tied = ()+ if config_ties_lm_head(config) and "lm_head.weight" in expected:+ tied = ("lm_head.weight",)+ try:+ mapping = match_keys(_file_logical_shapes(header), expected, tied_missing = tied)+ except ComponentFileError as exc:+ raise ComponentFileError(+ f"'{os.path.basename(path)}' does not fit this pipeline's {encoder_cls.__name__}: {exc}"+ ) from None+ return encoder, mapping, tied+++def build_text_encoder(+ path: str,+ *,+ encoder_cls: Any,+ config: Any,+ dtype: Any,+ trim_lm_head: bool = False,+ logger: Any = None,+) -> Any:+ """``encoder_cls`` (a transformers class) built from ``config`` and loaded from the ComfyUI file at+ ``path``, strictly. CPU; the pipeline assembly places it."""+ import torch+ from safetensors import safe_open++ from .diffusion_te_prequant import TE_PREQUANT_SCHEME_ATTR++ name = os.path.basename(path)+ header, _ = read_safetensors_header(path)+ layers = quant_layers(path)+ encoder, mapping, tied = _fit_text_encoder(path, header, encoder_cls, config, trim_lm_head)++ from .diffusion_comfy_quant import _dequant++ convrot_cls = None+ state: dict[str, Any] = {}+ kept_int8 = 0+ with safe_open(path, framework = "pt", device = "cpu") as handle:+ for src, dst in mapping.mapping.items():+ layer = layers.get(src[: -len(".weight")]) if src.endswith(".weight") else None+ if layer is None:+ tensor = handle.get_tensor(src)+ if tensor.is_floating_point() and dtype is not None and tensor.dtype != dtype:+ tensor = tensor.to(dtype)+ state[dst] = tensor+ continue+ stem = src[: -len(".weight")]+ scale_key = next(+ (stem + s for s in (".weight_scale", ".scale_weight") if stem + s in header), None+ )+ scale = handle.get_tensor(scale_key) if scale_key else None+ codes = handle.get_tensor(src)+ if layer.format == "int8_tensorwise":+ if scale is None:+ raise ComponentFileError(f"'{name}': {stem} is int8 with no weight_scale")+ parent_path, _, leaf = dst[: -len(".weight")].rpartition(".")+ target = encoder.get_submodule(parent_path) if parent_path else encoder+ existing = getattr(target, leaf, None)+ if layer.convrot and isinstance(existing, torch.nn.Linear):+ if convrot_cls is None:+ from .video_minimax_h3_te import _int8_convrot_linear_class+ convrot_cls = _int8_convrot_linear_class()+ has_bias = (stem + ".bias") in mapping.mapping+ setattr(+ target,+ leaf,+ convrot_cls(+ existing.in_features,+ existing.out_features,+ bias = has_bias,+ group_size = int(layer.group),+ ),+ )+ state[dst] = codes.to(torch.int8)+ state[dst[: -len(".weight")] + ".weight_scale"] = (+ scale.to(torch.float32)+ .reshape(-1, 1)+ .expand(codes.shape[0], 1)+ .contiguous()+ )+ kept_int8 += 1+ else:+ state[dst] = _dequant(codes, scale, int(layer.group or 0), dtype)+ else:+ state[dst] = _dequant_fp8(codes, scale, layer.format, dtype)+ if convrot_cls is not None:+ # Int8ConvRotLinear keeps its bias in bf16 storage.+ for key, tensor in list(state.items()):+ if key.endswith(".bias") and tensor.is_floating_point():+ state[key] = tensor.to(dtype)+ missing, unexpected = encoder.load_state_dict(state, strict = False, assign = True)+ bad_missing = [k for k in missing if k not in tied and not _is_dead(k, _DEAD_MISSING)]+ if bad_missing or unexpected:+ raise ComponentFileError(+ f"'{name}' did not load strictly into {encoder_cls.__name__}: missing {bad_missing[:3]}, "+ f"unexpected {list(unexpected)[:3]}"+ )+ tie = getattr(encoder, "tie_weights", None)+ if callable(tie):+ tie()+ # T5 / UMT5: ``encoder.embed_tokens`` IS ``shared``; re-point a meta leftover rather than trust tie_weights.+ inner = getattr(encoder, "encoder", None)+ shared = getattr(encoder, "shared", None)+ if (+ inner is not None+ and shared is not None+ and getattr(inner, "embed_tokens", None) is not None+ ):+ if inner.embed_tokens.weight.is_meta:+ inner.embed_tokens = shared+ stranded = _strip_meta(encoder)+ if stranded:+ raise ComponentFileError(+ f"'{name}': {len(stranded)} tensor(s) of {encoder_cls.__name__} were not in the file, "+ f"e.g. {stranded[0]}"+ )+ encoder.requires_grad_(False)+ encoder.eval()+ if kept_int8:+ # Already quantized: the runtime text-encoder cast must leave it alone and report it as int8.+ setattr(encoder, TE_PREQUANT_SCHEME_ATTR, "int8")+ if logger is not None:+ logger.info(+ "diffusion.comfy_components: %s -> %s (rule %s, %d int8 ConvRot linears kept, %d dead tensors "+ "skipped)",+ name,+ encoder_cls.__name__,+ mapping.rule,+ kept_int8,+ len(mapping.dead_unexpected),+ )+ return encoder+++_WAN_RESIDUAL = {+ "residual.0.gamma": "norm1.gamma",+ "residual.2.weight": "conv1.weight",+ "residual.2.bias": "conv1.bias",+ "residual.3.gamma": "norm2.gamma",+ "residual.6.weight": "conv2.weight",+ "residual.6.bias": "conv2.bias",+ "shortcut.weight": "conv_shortcut.weight",+ "shortcut.bias": "conv_shortcut.bias",+}+++def _convert_wan_nested_vae(state: dict) -> dict:+ """Wan 2.2-layout VAE (Qwen-Image-2.1's too) -> diffusers ``AutoencoderKLWan`` / ``AutoencoderKLQwenImage21``+ naming. Each ``downsamples.<i>`` stage nests its residual blocks and its resampler as numbered children; the+ residual children become ``resnets.<n>`` in order and the resampler ``downsampler`` / ``upsampler``."""+ out: dict = {}+ stage = re.compile(+ r"^(encoder|decoder)\.(downsamples|upsamples)\.(\d+)\.(downsamples|upsamples)\.(\d+)\.(.+)$"+ )+ residual_children: dict[tuple[str, int], list[int]] = {}+ for key in state:+ m = stage.match(key)+ if m and (m.group(6).startswith("residual.") or m.group(6).startswith("shortcut.")):+ residual_children.setdefault((m.group(1), int(m.group(3))), [])+ if int(m.group(5)) not in residual_children[(m.group(1), int(m.group(3)))]:+ residual_children[(m.group(1), int(m.group(3)))].append(int(m.group(5)))+ for children in residual_children.values():+ children.sort()+ for key, value in state.items():+ new = None+ m = stage.match(key)+ if m:+ side, _, i, _, j, rest = m.groups()+ block = "down_blocks" if side == "encoder" else "up_blocks"+ children = residual_children.get((side, int(i)), [])+ if int(j) in children and rest in _WAN_RESIDUAL:+ new = f"{side}.{block}.{i}.resnets.{children.index(int(j))}.{_WAN_RESIDUAL[rest]}"+ elif rest.startswith(("resample.", "time_conv.")):+ sampler = "downsampler" if side == "encoder" else "upsampler"+ new = f"{side}.{block}.{i}.{sampler}.{rest}"+ else:+ m2 = re.match(r"^(encoder|decoder)\.middle\.(\d+)\.(.+)$", key)+ if m2:+ side, idx, rest = m2.groups()+ if idx == "1":+ new = f"{side}.mid_block.attentions.0.{rest}"+ elif rest in _WAN_RESIDUAL:+ new = f"{side}.mid_block.resnets.{int(idx) // 2}.{_WAN_RESIDUAL[rest]}"+ else:+ m3 = re.match(r"^(encoder|decoder)\.(conv1|head\.0|head\.2)\.(.+)$", key)+ if m3:+ side, part, rest = m3.groups()+ new = (+ f"{side}."+ + {"conv1": "conv_in", "head.0": "norm_out", "head.2": "conv_out"}[part]+ + f".{rest}"+ )+ elif key.startswith("conv1."):+ new = "quant_conv." + key[len("conv1.") :]+ elif key.startswith("conv2."):+ new = "post_quant_conv." + key[len("conv2.") :]+ out[new or key] = value+ return out+++def fit_conv_shapes(state: dict, expected: dict) -> dict:+ """A causal-3D conv stored with a singleton time axis (``[out, in, 1, k, k]``) loads into a 2-D conv+ (``[out, in, k, k]``): squeeze exactly that axis, nothing else."""+ out = {}+ for key, value in state.items():+ want = expected.get(key)+ shape = tuple(value.shape)+ if want is not None and len(shape) == len(want) + 1 and len(shape) == 5 and shape[2] == 1:+ if (shape[:2] + shape[3:]) == tuple(want):+ value = value.squeeze(2)+ out[key] = value+ return out+++def convert_vae_state_dict(state: dict, kind: str, config: dict) -> dict:+ """ComfyUI / original VAE layout -> diffusers naming, through diffusers' own single-file converters."""+ if kind == "wan_nested":+ return _convert_wan_nested_vae(state)+ if kind == "ldm_kl":+ from diffusers.loaders.single_file_utils import convert_ldm_vae_checkpoint++ converted = convert_ldm_vae_checkpoint(state, dict(config))+ # FLUX.2's VAE adds a latent BatchNorm the LDM converter does not know; it keeps its name.+ for key, value in state.items():+ if key.startswith("bn."):+ converted.setdefault(key, value)+ return converted+ if kind == "wan":+ from diffusers.loaders.single_file_utils import convert_wan_vae_to_diffusers+ return convert_wan_vae_to_diffusers(state)+ return dict(state)+++def _fit_vae(name: str, raw: dict, kind: str, vae_cls: Any, config: dict) -> tuple[Any, dict, dict]:+ """``vae_cls`` on the meta device and ``raw`` converted to its naming, checked strictly. ``raw`` may hold meta+ tensors (a header-only check)."""+ from accelerate import init_empty_weights++ converted = convert_vae_state_dict(raw, kind, config)+ with init_empty_weights():+ vae = vae_cls.from_config(config)+ expected = _expected_shapes(vae)+ converted = fit_conv_shapes(converted, expected)+ try:+ match_keys(+ {k: tuple(v.shape) for k, v in converted.items()},+ expected,+ rules = (("identity", _rule_identity),),+ )+ except ComponentFileError as exc:+ raise ComponentFileError(+ f"'{name}' does not fit this pipeline's {vae_cls.__name__}: {exc}"+ ) from None+ return vae, converted, expected+++def build_vae(+ path: str,+ *,+ vae_cls: Any,+ config: dict,+ dtype: Any,+ logger: Any = None,+) -> Any:+ """``vae_cls`` from ``config``, loaded strictly from the supplied VAE file."""+ from safetensors.torch import load_file++ name = os.path.basename(path)+ header, _ = read_safetensors_header(path)+ if quant_layers(path):+ raise ComponentFileError(+ f"'{name}': quantized VAE files are not supported; use the bf16/fp32 VAE"+ )+ kind = classify_vae(weight_keys(header))+ if kind is None or vae_cls.__name__ not in VAE_KIND_CLASSES.get(kind, ()):+ raise ComponentFileError(+ f"'{name}' is not a VAE this pipeline's {vae_cls.__name__} can load (detected {kind or 'unknown'})"+ )+ raw = {k: v for k, v in load_file(path).items() if k not in _NON_WEIGHT_KEYS}+ vae, converted, expected = _fit_vae(name, raw, kind, vae_cls, config)+ state = {}+ for key, tensor in converted.items():+ if key not in expected:+ continue+ if tensor.is_floating_point() and dtype is not None and tensor.dtype != dtype:+ tensor = tensor.to(dtype)+ state[key] = tensor.contiguous()+ vae.load_state_dict(state, strict = True, assign = True)+ stranded = _strip_meta(vae)+ if stranded:+ raise ComponentFileError(+ f"'{name}': {len(stranded)} VAE tensor(s) not in the file, e.g. {stranded[0]}"+ )+ vae.requires_grad_(False)+ vae.eval()+ if logger is not None:+ logger.info(+ "diffusion.comfy_components: %s -> %s (%s layout)", name, vae_cls.__name__, kind+ )+ return vae+++@dataclass+class ComponentOverrides:+ """The supplied files of one load, assigned to base pipeline components, plus the built modules."""++ files: dict[str, ComponentFileRef] = field(default_factory = dict) # component -> file+ paths: dict[str, str] = field(default_factory = dict) # component -> resolved local path+ classes: dict[str, str] = field(default_factory = dict) # component -> class name+ kinds: dict[str, str] = field(default_factory = dict) # component -> detected file kind+ modules: dict[str, Any] = field(default_factory = dict)++ @property+ def components(self) -> tuple[str, ...]:+ return tuple(self.files)++ @property+ def text_encoder_components(self) -> tuple[str, ...]:+ return tuple(c for c in self.files if c.startswith("text_encoder"))++ def summary(self) -> dict[str, str]:+ return {c: ref.name for c, ref in self.files.items()}++ def resident_mib(self, dtype_itemsize: int = 2) -> dict[str, int]:+ out = {}+ for component, path in self.paths.items():+ try:+ out[component] = resident_bytes(+ path,+ dtype_itemsize = dtype_itemsize,+ kind = COMPONENT_VAE if component == COMPONENT_VAE else "text_encoder",+ ) // (1024 * 1024)+ except ComponentFileError:+ out[component] = 0+ return out+++_ACTIVE: contextvars.ContextVar[Optional[ComponentOverrides]] = contextvars.ContextVar(+ "unsloth_diffusion_component_overrides", default = None+)+++def active_component_overrides() -> Optional[ComponentOverrides]:+ return _ACTIVE.get()+++def set_active_component_overrides(value: Optional[ComponentOverrides]) -> Any:+ return _ACTIVE.set(value)+++def reset_active_component_overrides(token: Any) -> None:+ try:+ _ACTIVE.reset(token)+ except (ValueError, RuntimeError):+ _ACTIVE.set(None)+++def component_classes_from_index(index: dict) -> dict[str, str]:+ """``{component: class name}`` for the text encoders and VAE a ``model_index.json`` declares."""+ out: dict[str, str] = {}+ for component, value in (index or {}).items():+ if component != COMPONENT_VAE and component not in TEXT_ENCODER_COMPONENTS:+ continue+ if isinstance(value, (list, tuple)) and len(value) == 2 and value[1]:+ out[component] = str(value[1])+ return out+++def assign_components(+ te_headers: Sequence[tuple[ComponentFileRef, dict]],+ vae_header: Optional[tuple[ComponentFileRef, dict]],+ classes: dict[str, str],+ *,+ family: str = "",+) -> tuple[dict[str, ComponentFileRef], dict[str, str]]:+ """Each supplied file onto the one base component whose class it can fill (header-only). Raises+ when a file fits nothing, or two files want the same slot. A CLIP-L vs CLIP-G pair is told apart by+ width, so HiDream's two CLIP slots resolve in index order."""+ assigned: dict[str, ComponentFileRef] = {}+ kinds: dict[str, str] = {}+ for ref, header in te_headers:+ keys = weight_keys(header)+ shapes = {k: header[k].get("shape") for k in keys}+ # Tokenizer blobs (``tekken_model``) are evidence too, so classify on every non-companion name.+ kind = classify_text_encoder(keys + [k for k in header if k in _NON_WEIGHT_KEYS], shapes)+ if kind is None:+ raise ComponentFileError(f"'{ref.name}' is not a recognised text-encoder file")+ fits = [+ c+ for c in TEXT_ENCODER_COMPONENTS+ if c in classes+ and classes[c] in TE_KIND_CLASSES.get(kind, ())+ and c not in assigned+ and c not in _STANDALONE_TE_SLOTS.get(family, ())+ ]+ if kind in ("clip_l", "clip_g") and len(fits) > 1:+ # HiDream: text_encoder = CLIP-L, text_encoder_2 = CLIP-G (both WithProjection).+ fits = [fits[0]] if kind == "clip_l" else [fits[-1]]+ if not fits:+ wanted = ", ".join(f"{c}={classes[c]}" for c in TEXT_ENCODER_COMPONENTS if c in classes)+ taken = [c for c in assigned if classes.get(c) in TE_KIND_CLASSES.get(kind, ())]+ standalone = [+ c+ for c in _STANDALONE_TE_SLOTS.get(family, ())+ if classes.get(c) in TE_KIND_CLASSES.get(kind, ())+ ]+ why = (+ f"its slot ({', '.join(taken)}) is already taken by another supplied file"+ if taken+ else f"{family} loads {', '.join(standalone)} from its own repo, not from a supplied file"+ if standalone+ else f"the {family or 'pipeline'} text encoders are {wanted or 'none'}"+ )+ raise ComponentFileError(f"'{ref.name}' is a {kind} text encoder, but {why}")+ assigned[fits[0]] = ref+ kinds[fits[0]] = kind+ if vae_header is not None:+ ref, header = vae_header+ kind = classify_vae(weight_keys(header))+ vae_class = classes.get(COMPONENT_VAE)+ if kind is None:+ raise ComponentFileError(f"'{ref.name}' is not a recognised VAE file")+ if vae_class is None or vae_class not in VAE_KIND_CLASSES.get(kind, ()):+ raise ComponentFileError(+ f"'{ref.name}' is a {kind}-layout VAE, but the {family or 'pipeline'} VAE is "+ f"{vae_class or 'absent'}"+ )+ assigned[COMPONENT_VAE] = ref+ kinds[COMPONENT_VAE] = kind+ return assigned, kinds+++def hub_header(ref: ComponentFileRef, hf_token: Optional[str]) -> dict:+ """A Hub file's safetensors header without downloading its weights."""+ from huggingface_hub import HfApi++ try:+ info = HfApi().parse_safetensors_file_metadata(ref.repo_id, ref.filename, token = hf_token)+ except Exception as exc: # noqa: BLE001+ raise ComponentFileError(+ f"'{ref.name}': cannot read its safetensors header on the Hub: {exc}"+ )+ return {+ name: {"dtype": t.dtype, "shape": list(t.shape)} for name, t in (info.tensors or {}).items()+ }+++def plan_component_overrides(+ *,+ text_encoder_files: Sequence[str],+ vae_file: Optional[str],+ model_path: Optional[str],+ model_index: dict,+ family: str = "",+ trusted_repo: Optional[Callable[[str], bool]] = None,+ hf_token: Optional[str] = None,+ resolve_hub: Optional[Callable[[ComponentFileRef], str]] = None,+) -> Optional[ComponentOverrides]:+ """Parse, classify and assign. ``resolve_hub`` turns a Hub ref into a local path (the load's download);+ None plans from the Hub header alone (the download plan)."""+ te_specs = list(text_encoder_files or ())+ if not te_specs and not vae_file:+ return None+ classes = component_classes_from_index(model_index)+ refs = [+ parse_component_file(s, model_path = model_path, trusted_repo = trusted_repo) for s in te_specs+ ]+ vae_ref = (+ parse_component_file(+ vae_file, model_path = model_path, trusted_repo = trusted_repo, what = "vae_file"+ )+ if vae_file+ else None+ )+ paths: dict[int, str] = {}++ def header_of(ref: ComponentFileRef) -> dict:+ if ref.local_path:+ return read_safetensors_header(ref.local_path)[0]+ if resolve_hub is not None:+ local = resolve_hub(ref)+ paths[id(ref)] = local+ return read_safetensors_header(local)[0]+ return hub_header(ref, hf_token)++ te_headers = [(ref, header_of(ref)) for ref in refs]+ vae_header = (vae_ref, header_of(vae_ref)) if vae_ref is not None else None+ assigned, kinds = assign_components(te_headers, vae_header, classes, family = family)+ out = ComponentOverrides(files = assigned, kinds = kinds)+ for component, ref in assigned.items():+ out.classes[component] = classes[component]+ local = ref.local_path or paths.get(id(ref))+ if local:+ # Refused before anything is evicted (a Hub file is only on disk from here).+ if component != COMPONENT_VAE:+ quant_layers(local)+ elif quant_layers(local):+ raise ComponentFileError(+ f"'{ref.name}': quantized VAE files are not supported; use the bf16/fp32 VAE"+ )+ out.paths[component] = local+ return out+++def _component_class_and_config(+ component: str,+ class_name: str,+ *,+ base: str,+ hf_token: Optional[str],+ local_files_only: bool,+ cache_dir: Optional[str],+) -> tuple[Any, Any]:+ if component == COMPONENT_VAE:+ import diffusers++ vae_cls = getattr(diffusers, class_name, None)+ if vae_cls is None:+ raise ComponentFileError(f"diffusers has no {class_name}; update diffusers")+ return vae_cls, vae_cls.load_config(+ base,+ subfolder = COMPONENT_VAE,+ token = hf_token,+ cache_dir = cache_dir,+ local_files_only = local_files_only,+ )+ import transformers++ encoder_cls = getattr(transformers, class_name, None)+ if encoder_cls is None:+ raise ComponentFileError(f"transformers has no {class_name}; update transformers")+ config = transformers.AutoConfig.from_pretrained(+ base,+ subfolder = component,+ token = hf_token,+ cache_dir = cache_dir,+ local_files_only = local_files_only,+ )+ from .diffusion_krea2 import remap_rope_parameters++ remap_rope_parameters(getattr(config, "text_config", config))+ return encoder_cls, config+++def _resolved_path(overrides: ComponentOverrides, component: str) -> str:+ path = overrides.paths.get(component)+ if not path:+ raise ComponentFileError(+ f"'{overrides.files[component].name}' was not resolved to a local file before assembly"+ )+ return path+++def verify_override_fit(+ overrides: ComponentOverrides,+ *,+ base: str,+ hf_token: Optional[str] = None,+ local_files_only: bool = False,+ family: Optional[str] = None,+ cache_dir: Optional[str] = None,+ text_encoder_quant: Optional[str] = None,+) -> None:+ """Header-only strict fit of every supplied file against the base repo's real class, plus the precision+ request, so a wrong-size or un-castable file is refused before the resident pipeline is unloaded."""+ import torch++ from .diffusion_precision import TE_QUANT_INT8, normalize_te_quant+ from .diffusion_text_encoder_trim import family_trims_lm_head++ requested = normalize_te_quant(text_encoder_quant)+ if requested is None and str(text_encoder_quant or "").strip().lower() in ("none", "off"):+ requested = "dense" # an explicit request, unlike unset / auto+ for component, class_name in overrides.classes.items():+ path = _resolved_path(overrides, component)+ cls, config = _component_class_and_config(+ component,+ class_name,+ base = base,+ hf_token = hf_token,+ local_files_only = local_files_only,+ cache_dir = cache_dir,+ )+ header, _ = read_safetensors_header(path)+ name = os.path.basename(path)+ if component == COMPONENT_VAE:+ meta = {+ k: torch.empty(tuple(int(d) for d in (header[k].get("shape") or ())), device = "meta")+ for k in weight_keys(header)+ }+ _fit_vae(+ name, meta, overrides.kinds.get(component) or classify_vae(meta) or "", cls, config+ )+ continue+ trim = component == "text_encoder" and family_trims_lm_head(family)+ _fit_text_encoder(path, header, cls, config, trim)+ if requested not in (None, TE_QUANT_INT8) and any(+ layer.convrot and layer.format == "int8_tensorwise"+ for layer in quant_layers(path).values()+ ):+ raise ComponentFileError(+ f"'{name}' is stored as int8 ConvRot and cannot be re-cast to {requested}; leave "+ "text_encoder_quant at auto or pick the bf16 file"+ )+++def load_override_modules(+ overrides: ComponentOverrides,+ *,+ base: str,+ dtype: Any,+ hf_token: Optional[str] = None,+ local_files_only: bool = False,+ family: Optional[str] = None,+ cache_dir: Optional[str] = None,+ logger: Any = None,+) -> dict[str, Any]:+ """Build every supplied component once per load (cached on ``overrides``) and return the pipe kwargs."""+ missing = [c for c in overrides.files if c not in overrides.modules]+ if not missing:+ return dict(overrides.modules)+ from .diffusion_text_encoder_trim import family_trims_lm_head++ for component in missing:+ path = _resolved_path(overrides, component)+ cls, config = _component_class_and_config(+ component,+ overrides.classes[component],+ base = base,+ hf_token = hf_token,+ local_files_only = local_files_only,+ cache_dir = cache_dir,+ )+ if component == COMPONENT_VAE:+ overrides.modules[component] = build_vae(+ path, vae_cls = cls, config = config, dtype = dtype, logger = logger+ )+ continue+ trim = component == "text_encoder" and family_trims_lm_head(family)+ overrides.modules[component] = build_text_encoder(+ path,+ encoder_cls = cls,+ config = config,+ dtype = dtype,+ trim_lm_head = trim,+ logger = logger,+ )+ return dict(overrides.modules)+++def read_model_index(+ base: str,+ *,+ base_local_dir: Optional[str] = None,+ hf_token: Optional[str] = None,+ local_files_only: bool = False,+ cache_dir: Optional[str] = None,+) -> dict:+ for root in (base_local_dir, base):+ if not root:+ continue+ candidate = Path(root).expanduser() / "model_index.json"+ try:+ if candidate.is_file():+ return json.loads(candidate.read_text(encoding = "utf-8"))+ except (OSError, ValueError):+ continue+ from huggingface_hub import hf_hub_download++ local = hf_hub_download(+ base,+ "model_index.json",+ token = hf_token,+ cache_dir = cache_dir,+ local_files_only = local_files_only,+ )+ return json.loads(Path(local).read_text(encoding = "utf-8"))+++def scanned_component_bytes(sizes: dict[str, int], components: Iterable[str]) -> dict[str, int]:+ """The ``{relative path: bytes}`` entries of a base-repo scan that ``components`` replace."""+ wanted = set(components)+ return {rel: size for rel, size in sizes.items() if rel.split("/", 1)[0] in wanted}+++def hub_repo_ids(+ text_encoder_files: Sequence[str], vae_file: Optional[str], *, model_path: Optional[str]+) -> tuple[str, ...]:+ """Hub repos the supplied specs name; unparseable specs are left to validation."""+ out: list[str] = []+ for spec in [*(text_encoder_files or ()), *([vae_file] if vae_file else [])]:+ try:+ ref = parse_component_file(spec, model_path = model_path)+ except ComponentFileError:+ continue+ if ref.is_hub and ref.repo_id not in out:+ out.append(ref.repo_id)+ return tuple(out)+++def validate_component_specs(+ text_encoder_files: Sequence[str],+ vae_file: Optional[str],+ *,+ model_path: Optional[str],+ trusted_repo: Optional[Callable[[str], bool]] = None,+) -> list[ComponentFileRef]:+ """Network-free request validation, run before anything is evicted: every spec parses and clears the trust+ bar, and every LOCAL file is a text encoder / VAE Studio recognises in a quantization it can load. The slot+ assignment needs the base repo's ``model_index.json`` and happens at load time."""+ refs: list[ComponentFileRef] = []+ for spec in text_encoder_files or ():+ ref = parse_component_file(spec, model_path = model_path, trusted_repo = trusted_repo)+ if ref.local_path:+ header, _ = read_safetensors_header(ref.local_path)+ keys = weight_keys(header)+ kind = classify_text_encoder(+ keys + [k for k in header if k in _NON_WEIGHT_KEYS],+ {k: header[k].get("shape") for k in keys},+ )+ if kind is None:+ vae_kind = classify_vae(keys)+ hint = " (it looks like a VAE; pass it as vae_file)" if vae_kind else ""+ raise ComponentFileError(+ f"'{ref.name}' is not a recognised text-encoder file{hint}"+ )+ quant_layers(ref.local_path)+ refs.append(ref)+ if vae_file:+ ref = parse_component_file(+ vae_file, model_path = model_path, trusted_repo = trusted_repo, what = "vae_file"+ )+ if ref.local_path:+ header, _ = read_safetensors_header(ref.local_path)+ if classify_vae(weight_keys(header)) is None:+ raise ComponentFileError(f"'{ref.name}' is not a recognised VAE file")+ if quant_layers(ref.local_path):+ raise ComponentFileError(+ f"'{ref.name}': quantized VAE files are not supported; use the bf16/fp32 VAE"+ )+ refs.append(ref)+ names = [r.local_path or f"{r.repo_id}/{r.filename}" for r in refs]+ if len(set(names)) != len(names):+ raise ComponentFileError("the same file was supplied twice")+ return refsdiff --git a/studio/backend/core/inference/diffusion_precision.py b/studio/backend/core/inference/diffusion_precision.pyindex 2d0d60cf9b3..9a229d9990c 100644--- a/studio/backend/core/inference/diffusion_precision.py+++ b/studio/backend/core/inference/diffusion_precision.py@@ -263,6 +263,15 @@ def quantize_text_encoders(leaves the encoder dense."""mode = normalize_te_quant(mode)if mode is None:+ present = [a for a in _TEXT_ENCODER_ATTRS if getattr(pipe, a, None) is not None]+ stored_int8 = [a for a in present if _hosted_te_scheme(getattr(pipe, a)) == TE_QUANT_INT8]+ if stored_int8:+ return TEQuantOutcome(+ TE_QUANT_INT8,+ "int8 ConvRot weight-only text encoder, as stored in the supplied file"+ + ("" if len(stored_int8) == len(present) else f" ({', '.join(stored_int8)} only)"),+ RESOLVED_APPLIED,+ )return TEQuantOutcome(None)# A hosted int8 ConvRot encoder is already quantized (plain tensors, offload-safe): report it, never re-cast it.present = [a for a in _TEXT_ENCODER_ATTRS if getattr(pipe, a, None) is not None]diff --git a/studio/backend/core/inference/diffusion_te_prequant.py b/studio/backend/core/inference/diffusion_te_prequant.pyindex 7ba2a143845..b2a938677fb 100644--- a/studio/backend/core/inference/diffusion_te_prequant.py+++ b/studio/backend/core/inference/diffusion_te_prequant.py@@ -651,6 +651,44 @@ def load_prequant_text_encoder(return None+def supplied_component_pipe_kwargs(+ base: str,+ *,+ dtype: Any,+ hf_token: Optional[str] = None,+ local_files_only: bool = False,+ family: Optional[str] = None,+ logger: Any = None,+) -> dict[str, Any]:+ """Supplied text-encoder / VAE modules by component. Never swallows a failure: the base repo's weights for+ these components were not downloaded, so there is nothing to fall back to."""+ from .diffusion_comfy_components import active_component_overrides, load_override_modules++ overrides = active_component_overrides()+ if overrides is None or not overrides.files:+ return {}+ from utils.hf_cache_settings import active_hf_hub_cache++ return load_override_modules(+ overrides,+ base = base,+ dtype = dtype,+ hf_token = hf_token,+ local_files_only = local_files_only,+ family = family,+ cache_dir = active_hf_hub_cache(),+ logger = logger if logger is not None else _module_logger(),+ )+++def _module_logger() -> Any:+ try:+ from loggers import get_logger+ return get_logger(__name__)+ except Exception: # noqa: BLE001+ return None++def te_prequant_pipe_kwargs(fam: Any,base: str,@@ -661,6 +699,41 @@ def te_prequant_pipe_kwargs(hf_token: Optional[str] = None,logger: Any = None,local_files_only: bool = False,+) -> dict[str, Any]:+ supplied = supplied_component_pipe_kwargs(+ base,+ dtype = dtype,+ hf_token = hf_token,+ local_files_only = local_files_only,+ family = getattr(fam, "name", None),+ logger = logger,+ )+ injected = _te_prequant_pipe_kwargs(+ fam,+ base,+ te_quant_mode = te_quant_mode,+ target = target,+ dtype = dtype,+ hf_token = hf_token,+ logger = logger,+ local_files_only = local_files_only,+ skip_components = tuple(supplied),+ )+ injected.update(supplied)+ return injected+++def _te_prequant_pipe_kwargs(+ fam: Any,+ base: str,+ *,+ te_quant_mode: Optional[str],+ target: Any,+ dtype: Any,+ hf_token: Optional[str] = None,+ logger: Any = None,+ local_files_only: bool = False,+ skip_components: tuple = (),) -> dict[str, Any]:"""Component overrides for pipeline assembly: ``{<component>: <pre-cast encoder>}``for every ``TE_PREQUANT_COMPONENTS`` attr the family hosts a pre-cast checkpoint for@@ -685,6 +758,8 @@ def te_prequant_pipe_kwargs(mode = normalize_te_quant(te_quant_mode) or TE_QUANT_FP8injected: dict[str, Any] = {}for component, source in sources.items():+ if component in skip_components:+ continuetrim = component == "text_encoder" and family_trims_lm_head(getattr(fam, "name", None))encoder = load_prequant_text_encoder(base,diff --git a/studio/backend/hub/services/models/account_access.py b/studio/backend/hub/services/models/account_access.pyindex 89f0afb6c2a..19b51ec284f 100644--- a/studio/backend/hub/services/models/account_access.py+++ b/studio/backend/hub/services/models/account_access.py@@ -887,6 +887,46 @@ def require_media_references(request) -> None:raise HTTPException(status_code = 404, detail = "Model not found")elif Path(request.model_path).is_absolute():require_model_access(str(Path(request.model_path) / path))+ for reference in media_component_file_references(request):+ if reference is None:+ raise HTTPException(status_code = 404, detail = "Model not found")+ require_model_access(reference)+++def media_component_file_references(request) -> list[str | None]:+ """What each supplied text-encoder / VAE file loads: a resolved local path or the Hub ``owner/repo``. None for a+ relative path with no local ``model_path`` to resolve against. Mirrors ``parse_component_file``."""+ supplied = getattr(request, "text_encoder_file", None)+ supplied = [supplied] if isinstance(supplied, str) else list(supplied or ())+ vae_file = getattr(request, "vae_file", None)+ if isinstance(vae_file, str) and vae_file:+ supplied.append(vae_file)+ root = None+ try:+ model_path = Path(str(getattr(request, "model_path", "") or "")).expanduser()+ if model_path.is_absolute():+ root = model_path if model_path.is_dir() else model_path.parent+ except OSError:+ root = None+ references: list[str | None] = []+ for reference in supplied:+ if not isinstance(reference, str) or not reference.strip():+ continue+ spec = reference.strip()+ path = Path(spec).expanduser()+ if path.is_absolute():+ references.append(str(path.resolve()))+ continue+ local = root / path if root is not None else None+ if local is not None and (+ spec.startswith(".") or "\\" in spec or len(path.parts) < 3 or local.is_file()+ ):+ references.append(str(local.resolve()))+ elif local is None and (spec.startswith(".") or "\\" in spec or len(path.parts) < 3):+ references.append(None)+ else:+ references.append("/".join(spec.replace("\\", "/").split("/")[:2]))+ return referencesdef resident_components(status: dict, modality: str | None = None) -> list[str]:diff --git a/studio/backend/models/inference.py b/studio/backend/models/inference.pyindex ce58c47f78d..98395f07d45 100644--- a/studio/backend/models/inference.py+++ b/studio/backend/models/inference.py@@ -4278,6 +4278,22 @@ class DiffusionLoadRequest(BaseModel):)# Referenced out, so resolved back in, or a caller handed a `ref:` base cannot load it._resolve_the_base_handle = field_validator("base_repo")(resolve_inventory_handle)+ text_encoder_file: Optional[Union[str, List[str]]] = Field(+ None,+ description = "Separate text-encoder file(s) to use instead of the base repo's, e.g. a ComfyUI "+ "models/text_encoders file. One path or a list (FLUX.1: clip_l + t5xxl); each is matched to the "+ "pipeline slot whose encoder class it fits. A local .safetensors path (relative paths resolve against "+ "model_path, so ../text_encoders/x.safetensors works from a ComfyUI diffusion_models folder) or "+ "owner/repo/path.safetensors under the same repo rule as model_path. Unquantized, scaled fp8 and "+ "int8 (ConvRot) files load; other ComfyUI formats are refused. Only with a gguf / single_file load; "+ "the base repo then supplies only configs and tokenizers for these encoders.",+ )+ vae_file: Optional[str] = Field(+ None,+ description = "Separate VAE file to use instead of the base repo's, e.g. a ComfyUI models/vae file "+ "(ae.safetensors, qwen_image_vae.safetensors, wan_2.1_vae.safetensors). Same path rules as "+ "text_encoder_file. Only with a gguf / single_file load.",+ )family_override: Optional[str] = Field(None, description = "Force a family when it can't be inferred from the repo id")@@ -4421,6 +4437,30 @@ class DiffusionLoadRequest(BaseModel):# The dispatcher accepts case/whitespace variants, but the Literal above is validated before any normaliser runs, so fold it here.return value.strip().lower() if isinstance(value, str) else value+ @field_validator("text_encoder_file")+ @classmethod+ def _normalize_text_encoder_file(cls, value):+ if value is None:+ return None+ items = [value] if isinstance(value, str) else list(value)+ items = [item.strip() for item in items if isinstance(item, str) and item.strip()]+ if len(set(items)) != len(items):+ raise ValueError("text_encoder_file lists the same file twice")+ if len(items) > 4:+ raise ValueError("at most 4 text_encoder_file entries (one per encoder slot)")+ return items or None++ @field_validator("vae_file")+ @classmethod+ def _blank_vae_file(cls, value):+ return (value or "").strip() or None++ def supplied_text_encoder_files(self) -> Optional[list[str]]:+ value = self.text_encoder_file+ if value is None:+ return None+ return [value] if isinstance(value, str) else list(value)+@field_validator("loras")@classmethoddef _unique_lora_ids(cls, value: Optional[list["LoraSpec"]]) -> Optional[list["LoraSpec"]]:@@ -5040,6 +5080,11 @@ class DiffusionStatusResponse(BaseModel):gguf_variant: Optional[str] = Field(None, description = "Selected GGUF quantisation variant (for example Q8_0)")+ component_files: Optional[Dict[str, str]] = Field(+ None,+ description = "Supplied text-encoder / VAE files by pipeline component (e.g. text_encoder_2: "+ "t5xxl_fp8_e4m3fn_scaled.safetensors); null when every companion came from the base repo",+ )cpu_offload: bool = Field(False, description = "Whether CPU offload is engaged")offload_policy: Optional[str] = Field(None, description = "Resolved offload policy: none | group | model | streaming | sequential"diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.pyindex 4c788dafa18..51b8b312d63 100644--- a/studio/backend/routes/inference.py+++ b/studio/backend/routes/inference.py@@ -45701,6 +45701,28 @@ async def _refuse_disabled_nvfp4_checkpoint(request: Any) -> None:raise HTTPException(status_code = 400, detail = str(exc))+def _component_file_kwargs(request: DiffusionLoadRequest) -> dict:+ """Empty when none, so the native engine and older callers see the same keywords as before."""+ files = getattr(request, "text_encoder_file", None)+ files = [files] if isinstance(files, str) else list(files or ())+ out: dict = {}+ if files:+ out["text_encoder_files"] = files+ vae_file = getattr(request, "vae_file", None)+ if vae_file:+ out["vae_file"] = vae_file+ return out+++def _refuse_native_component_files(request: DiffusionLoadRequest) -> None:+ if _component_file_kwargs(request):+ raise HTTPException(+ status_code = 400,+ detail = "Separate text-encoder / VAE files load on the diffusers engine (a CUDA / ROCm GPU); "+ "this host routes the pick to the native engine. Omit text_encoder_file / vae_file.",+ )++@studio_router.post("/images/download-plan", response_model = DiffusionDownloadPlanResponse)async def diffusion_download_plan(request: DiffusionLoadRequest, current_subject: str = Depends(get_current_subject)@@ -45757,6 +45779,7 @@ async def diffusion_download_plan(family_override = request.family_override,model_kind = kind,base_repo = request.base_repo,+ **_component_file_kwargs(request),)planner = backend# BEFORE the plan is handed back and staged. The load route refuses a precision this@@ -45785,6 +45808,7 @@ async def diffusion_download_plan(fam is not Noneand predict_engine(fam, model_kind = kind, gpu_ordinal = gpu_ordinal) == ENGINE_SD_CPP):+ _refuse_native_component_files(request)from core.inference.sd_cpp_backend import get_sd_cpp_backendplanner = get_sd_cpp_backend()if fam is not None and not training:@@ -45833,6 +45857,7 @@ async def diffusion_download_plan(# this the plan stages a file the load refuses and replaces with dense shards.transformer_quant_fast_accum = request.transformer_quant_fast_accum,loras = request.loras,+ **_component_file_kwargs(request),# Only the verdict, not the probe: the panel stages exactly what this reports.# Clearing the probe drops the hosted DiT prequant, so a GGUF pick naming an explicit# transformer_quant reports ~21 GB short, stages that, says done, and the load pulls@@ -45948,7 +45973,16 @@ async def load_diffusion_model_gated(# deferred to the launch below, since the validation in between 400s without moving a byte._media_repos_to_record = [ref- for ref in (request.model_path, request.base_repo)+ for ref in (+ request.model_path,+ request.base_repo,+ # Hub-hosted text-encoder / VAE files are fetched with this request's token too.+ *(+ r+ for r in account_access.media_component_file_references(request)+ if r and not Path(r).is_absolute()+ ),+ )if ref and _repo_is_in_the_hub_cache(ref) is not True]from core.inference.diffusion import (@@ -46007,6 +46041,7 @@ async def load_diffusion_model_gated(family_override = request.family_override,model_kind = kind,base_repo = request.base_repo,+ **_component_file_kwargs(request),)# Off-torch native shares no VRAM with training or chat; re-settled after selection (diffusers lands on torch's card).off_torch = await asyncio.to_thread(off_torch_sd_cpp_device)@@ -46073,6 +46108,7 @@ async def load_diffusion_model_gated(base_repo = request.base_repo,)elif fam is not None and pending_name == ENGINE_SD_CPP:+ _refuse_native_component_files(request)# The native engine accepts both knobs for interface parity and ignores them. It was# excluded from the gate above so as not to refuse loads that work today, but the# loads it "works" for are precisely the silent mismatch this whole change exists to@@ -46135,6 +46171,7 @@ async def load_diffusion_model_gated(activated = active_engine_name()if fam is not None and activated != pending_name:if activated == ENGINE_SD_CPP:+ _refuse_native_component_files(request)_assert_native_precision_unset(transformer_quant = request.transformer_quant,text_encoder_quant = request.text_encoder_quant,@@ -46192,6 +46229,7 @@ async def load_diffusion_model_gated(# The winner this route already ranked and preflighted, so the load cannot pick a# different card from free VRAM that has moved since.gpu_ordinal = gpu_ordinal,+ **_component_file_kwargs(request),)def _begin_load():@@ -46228,6 +46266,7 @@ async def load_diffusion_model_gated(request.model_path,request.base_repo,*account_access.media_adapter_references(request),+ *(r for r in account_access.media_component_file_references(request) if r),)reset_media_load_progress("image")return DiffusionStatusResponse(**(await asyncio.to_thread(annotate_status, status_dict)))diff --git a/studio/backend/tests/test_diffusion_comfy_components.py b/studio/backend/tests/test_diffusion_comfy_components.pynew file mode 100644index 00000000000..7d5cba8930d--- /dev/null+++ b/studio/backend/tests/test_diffusion_comfy_components.py@@ -0,0 +1,976 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Separate ComfyUI text-encoder / VAE files beside a single-file DiT (``diffusion_comfy_components.py``).++Everything runs on CPU against tiny models and tiny synthetic safetensors files written in the ComfyUI+layout: the key rules must load STRICTLY (nothing missing, nothing extra beyond the known-dead tensors),+quantized layers must dequantize (scaled fp8) or stay int8 (ConvRot), unsupported formats must be refused+by name, and the request / planner wiring must drop and re-price the replaced components.+"""++from __future__ import annotations++import json+import types+from pathlib import Path++import pytest++torch = pytest.importorskip("torch")+safetensors_torch = pytest.importorskip("safetensors.torch")+transformers = pytest.importorskip("transformers")++import core.inference.diffusion_comfy_components as C # noqa: E402+++def _save(+ path: Path,+ tensors: dict,+ metadata: dict | None = None,+) -> str:+ path.parent.mkdir(parents = True, exist_ok = True)+ safetensors_torch.save_file(+ {k: v.detach().clone().contiguous() for k, v in tensors.items()},+ str(path),+ metadata = metadata,+ )+ return str(path)+++def _quant_blob(conf: dict) -> "torch.Tensor":+ return torch.tensor(list(json.dumps(conf).encode("utf-8")), dtype = torch.uint8)+++# ----------------------------------------------------------------------------------------------------------------------+# Spec parsing and trust+++def test_parse_local_absolute_relative_and_bare(tmp_path):+ models = tmp_path / "ComfyUI" / "models"+ te = _save(models / "text_encoders" / "clip_l.safetensors", {"x": torch.zeros(1)})+ dit_dir = models / "diffusion_models"+ dit_dir.mkdir(parents = True)+ _save(dit_dir / "vae_here.safetensors", {"x": torch.zeros(1)})+ assert C.parse_component_file(te).local_path == str(Path(te).resolve())+ rel = C.parse_component_file("../text_encoders/clip_l.safetensors", model_path = str(dit_dir))+ assert rel.local_path == str(Path(te).resolve())+ bare = C.parse_component_file("vae_here.safetensors", model_path = str(dit_dir))+ assert bare.local_path.endswith("vae_here.safetensors")+++def test_parse_existing_subpath_under_model_dir_is_local(tmp_path):+ dit_dir = tmp_path / "models" / "diffusion_models"+ two = _save(dit_dir / "components" / "clip_l.safetensors", {"x": torch.zeros(1)})+ three = _save(dit_dir / "unsloth" / "nested" / "ae.safetensors", {"x": torch.zeros(1)})+ trusted = lambda r: r.startswith("unsloth/")+ assert C.parse_component_file(+ "components/clip_l.safetensors", model_path = str(dit_dir), trusted_repo = trusted+ ).local_path == str(Path(two).resolve())+ # A local file shadows the owner/repo/file reading of the same string.+ assert C.parse_component_file(+ "unsloth/nested/ae.safetensors", model_path = str(dit_dir), trusted_repo = trusted+ ).local_path == str(Path(three).resolve())+ hub = C.parse_component_file(+ "unsloth/other/ae.safetensors", model_path = str(dit_dir), trusted_repo = trusted+ )+ assert (hub.repo_id, hub.filename) == ("unsloth/other", "ae.safetensors")+++def test_hub_header_reads_one_file(monkeypatch):+ calls = []++ class _Api:+ def parse_safetensors_file_metadata(+ self,+ repo_id,+ filename,+ *,+ token = None,+ ):+ calls.append((repo_id, filename, token))+ tensor = types.SimpleNamespace(dtype = "BF16", shape = [4, 8])+ return types.SimpleNamespace(tensors = {"encoder.block.0.w": tensor})++ import huggingface_hub++ monkeypatch.setattr(huggingface_hub, "HfApi", _Api)+ ref = C.ComponentFileRef(+ spec = "unsloth/r/te.safetensors", repo_id = "unsloth/r", filename = "te.safetensors"+ )+ assert C.hub_header(ref, "tok") == {"encoder.block.0.w": {"dtype": "BF16", "shape": [4, 8]}}+ assert calls == [("unsloth/r", "te.safetensors", "tok")]+++def test_account_access_resolves_component_references(tmp_path):+ from hub.services.models import account_access++ models = tmp_path / "ComfyUI" / "models"+ te = _save(models / "text_encoders" / "clip_l.safetensors", {"x": torch.zeros(1)})+ dit_dir = models / "diffusion_models"+ dit_dir.mkdir(parents = True)+ request = types.SimpleNamespace(+ model_path = str(dit_dir),+ text_encoder_file = ["../text_encoders/clip_l.safetensors", "unsloth/r/te.safetensors"],+ vae_file = str(models / "vae" / "ae.safetensors"),+ )+ assert account_access.media_component_file_references(request) == [+ str(Path(te).resolve()),+ "unsloth/r",+ str((models / "vae" / "ae.safetensors").resolve()),+ ]+ hub_model = types.SimpleNamespace(+ model_path = "unsloth/FLUX.1-schnell", text_encoder_file = "../x.safetensors", vae_file = None+ )+ assert account_access.media_component_file_references(hub_model) == [None]+++def test_parse_refuses_non_safetensors_missing_and_untrusted(tmp_path):+ with pytest.raises(C.ComponentFileError, match = "not a .safetensors"):+ C.parse_component_file(str(tmp_path / "t5.gguf"))+ with pytest.raises(C.ComponentFileError, match = "does not exist"):+ C.parse_component_file(str(tmp_path / "missing.safetensors"))+ with pytest.raises(C.ComponentFileError, match = "relative path"):+ C.parse_component_file("../x.safetensors", model_path = "unsloth/FLUX.1-schnell")+ with pytest.raises(C.ComponentFileError, match = "restricted"):+ C.parse_component_file(+ "someone/repo/te.safetensors", trusted_repo = lambda r: r.startswith("unsloth/")+ )+ hub = C.parse_component_file(+ "unsloth/X-ComfyUI/split_files/te.safetensors",+ trusted_repo = lambda r: r.startswith("unsloth/"),+ )+ assert (hub.repo_id, hub.filename) == ("unsloth/X-ComfyUI", "split_files/te.safetensors")+++def test_normalize_text_encoder_files():+ assert C.normalize_text_encoder_files(None) == []+ assert C.normalize_text_encoder_files(" a.safetensors ") == ["a.safetensors"]+ assert C.normalize_text_encoder_files(["a", "a", " ", "b"]) == ["a", "b"]+ with pytest.raises(C.ComponentFileError):+ C.normalize_text_encoder_files(["a", "b", "c", "d", "e"])+++# ----------------------------------------------------------------------------------------------------------------------+# Classification and key rules (real ComfyUI key layouts, tiny shapes)+++ "keys, kind",+ [+ (+ [+ "text_model.encoder.layers.0.mlp.fc1.weight",+ "text_model.embeddings.token_embedding.weight",+ ],+ "clip_l",+ ),+ (["encoder.block.0.layer.0.SelfAttention.q.weight", "shared.weight"], "t5"),+ (+ [+ "encoder.block.0.layer.0.SelfAttention.q.weight",+ "encoder.block.1.layer.0.SelfAttention.relative_attention_bias.weight",+ "shared.weight",+ ],+ "umt5",+ ),+ (["model.layers.0.self_attn.q_norm.weight", "model.embed_tokens.weight"], "qwen3"),+ (+ ["model.layers.0.self_attn.q_proj.weight", "visual.blocks.0.attn.qkv.weight"],+ "qwen2_5_vl",+ ),+ (+ ["model.layers.0.self_attn.q_norm.weight", "model.visual.blocks.0.attn.qkv.weight"],+ "qwen3_vl",+ ),+ (["model.layers.0.self_attn.q_proj.weight", "tekken_model"], "mistral3"),+ (+ [+ "model.layers.0.self_attn.q_proj.weight",+ "model.layers.0.pre_feedforward_layernorm.weight",+ ],+ "gemma2",+ ),+ (["model.layers.0.self_attn.q_proj.weight"], "llama"),+ (["decoder.conv_in.weight"], None),+ ],+)+def test_classify_text_encoder(keys, kind):+ assert C.classify_text_encoder(keys) == kind+++def test_classify_clip_g_by_width():+ keys = [+ "text_model.encoder.layers.0.mlp.fc1.weight",+ "text_model.embeddings.token_embedding.weight",+ ]+ shapes = {"text_model.embeddings.token_embedding.weight": [49408, 1280]}+ assert C.classify_text_encoder(keys, shapes) == "clip_g"+++ "keys, kind",+ [+ (["decoder.up.0.block.0.conv1.weight", "encoder.down.0.block.0.conv1.weight"], "ldm_kl"),+ (["decoder.upsamples.0.residual.0.gamma", "encoder.downsamples.0.residual.0.gamma"], "wan"),+ (+ [+ "decoder.upsamples.0.upsamples.0.residual.0.gamma",+ "encoder.downsamples.0.downsamples.1.resample.1.weight",+ ],+ "wan_nested",+ ),+ (["decoder.up_blocks.0.resnets.0.conv1.weight"], "diffusers"),+ (["model.layers.0.self_attn.q_proj.weight"], None),+ ],+)+def test_classify_vae(keys, kind):+ assert C.classify_vae(keys) == kind+++def test_match_keys_vl_nest_strict_and_dead_lm_head():+ expected = {+ "model.language_model.embed_tokens.weight": (10, 4),+ "model.language_model.layers.0.self_attn.q_proj.weight": (4, 4),+ "model.language_model.norm.weight": (4,),+ "model.visual.blocks.0.attn.qkv.weight": (12, 4),+ }+ comfy = {+ "model.embed_tokens.weight": (10, 4),+ "model.layers.0.self_attn.q_proj.weight": (4, 4),+ "model.norm.weight": (4,),+ "model.visual.blocks.0.attn.qkv.weight": (12, 4),+ "lm_head.weight": (10, 4), # trimmed by the family: dead+ }+ km = C.match_keys(comfy, expected)+ assert km.rule == "nest_language_model"+ assert km.dead_unexpected == ["lm_head.weight"]+ # Qwen2.5-VL keeps its vision tower at the top level in ComfyUI files.+ comfy25 = {+ ("visual." + k[len("model.visual.") :] if k.startswith("model.visual.") else k): v+ for k, v in comfy.items()+ }+ assert C.match_keys(comfy25, expected).rule == "nest_language_model"+++def test_match_keys_refuses_missing_extra_and_shape():+ expected = {"layers.0.w.weight": (4, 4), "norm.weight": (4,)}+ with pytest.raises(C.ComponentFileError, match = "missing"):+ C.match_keys({"model.layers.0.w.weight": (4, 4)}, expected)+ with pytest.raises(C.ComponentFileError, match = "unexpected"):+ C.match_keys(+ {"layers.0.w.weight": (4, 4), "norm.weight": (4,), "extra.weight": (1,)}, expected+ )+ with pytest.raises(C.ComponentFileError, match = "shape"):+ C.match_keys({"layers.0.w.weight": (4, 8), "norm.weight": (4,)}, expected)+++def test_match_keys_tied_lm_head_may_be_missing():+ expected = {"model.embed_tokens.weight": (10, 4), "lm_head.weight": (10, 4)}+ km = C.match_keys(+ {"model.embed_tokens.weight": (10, 4)}, expected, tied_missing = ("lm_head.weight",)+ )+ assert km.dead_missing == ["lm_head.weight"]+ with pytest.raises(C.ComponentFileError):+ C.match_keys({"model.embed_tokens.weight": (10, 4)}, expected)+++# ----------------------------------------------------------------------------------------------------------------------+# Building real (tiny) transformers encoders from ComfyUI-layout files+++def _tiny_clip():+ cfg = transformers.CLIPTextConfig(+ vocab_size = 64,+ hidden_size = 32,+ intermediate_size = 64,+ num_hidden_layers = 2,+ num_attention_heads = 4,+ max_position_embeddings = 16,+ projection_dim = 32,+ )+ torch.manual_seed(0)+ return cfg, transformers.CLIPTextModel(cfg).eval()+++def test_clip_l_full_clip_export_loads_strictly_and_matches(tmp_path):+ cfg, ref = _tiny_clip()+ state = {k: v for k, v in ref.state_dict().items() if not k.endswith("position_ids")}+ # A full-CLIP export also carries the projection and logit scale CLIPTextModel never reads.+ state["text_projection.weight"] = torch.randn(32, 32)+ state["logit_scale"] = torch.tensor(4.6)+ path = _save(+ tmp_path / "clip_l.safetensors", {k: v.to(torch.float16) for k, v in state.items()}+ )+ enc = C.build_text_encoder(+ path, encoder_cls = transformers.CLIPTextModel, config = cfg, dtype = torch.float32+ )+ ids = torch.tensor([[1, 5, 9, 2]])+ with torch.no_grad():+ got = enc(input_ids = ids).last_hidden_state+ want = ref.to(torch.float16).float()(input_ids = ids).last_hidden_state+ assert torch.allclose(got, want, atol = 1e-5)+++def _tiny_t5():+ cfg = transformers.T5Config(+ vocab_size = 64,+ d_model = 32,+ d_kv = 8,+ d_ff = 64,+ num_layers = 2,+ num_heads = 4,+ feed_forward_proj = "gated-gelu",+ is_encoder_decoder = False,+ use_cache = False,+ )+ torch.manual_seed(0)+ return cfg, transformers.T5EncoderModel(cfg).eval()+++def test_t5_legacy_scaled_fp8_dequantizes_strictly(tmp_path):+ cfg, ref = _tiny_t5()+ state = dict(ref.state_dict())+ out = {}+ dequant_ref = {}+ for key, value in state.items():+ if key.endswith(".weight") and value.ndim == 2 and ".block." in key:+ scale = value.abs().max() / 448.0+ codes = (value / scale).to(torch.float8_e4m3fn)+ out[key] = codes+ out[key[: -len(".weight")] + ".scale_weight"] = scale.reshape(())+ dequant_ref[key] = codes.float() * scale+ else:+ out[key] = value+ out["scaled_fp8"] = torch.zeros(0, dtype = torch.float8_e4m3fn)+ path = _save(tmp_path / "t5xxl_fp8_e4m3fn_scaled.safetensors", out)+ enc = C.build_text_encoder(+ path, encoder_cls = transformers.T5EncoderModel, config = cfg, dtype = torch.float32+ )+ loaded = enc.state_dict()+ for key, want in dequant_ref.items():+ assert torch.equal(loaded[key], want), key+ assert enc.encoder.embed_tokens.weight.data_ptr() == enc.shared.weight.data_ptr()+ ids = torch.tensor([[3, 7, 11, 1]])+ with torch.no_grad():+ cos = torch.nn.functional.cosine_similarity(+ enc(input_ids = ids).last_hidden_state.flatten(),+ ref(input_ids = ids).last_hidden_state.flatten(),+ dim = 0,+ )+ assert cos > 0.99+++def _tiny_qwen3():+ cfg = transformers.Qwen3Config(+ vocab_size = 64,+ hidden_size = 64,+ intermediate_size = 128,+ num_hidden_layers = 2,+ num_attention_heads = 4,+ num_key_value_heads = 2,+ head_dim = 16,+ max_position_embeddings = 32,+ tie_word_embeddings = False,+ )+ torch.manual_seed(0)+ return cfg, transformers.Qwen3Model(cfg).eval()+++def _convrot_int8(weight: "torch.Tensor", group: int):+ from core.inference.diffusion_convrot import build_convrot_hadamard++ h = build_convrot_hadamard(group, device = weight.device, dtype = torch.float32)+ rows, cols = weight.shape+ rotated = (weight.float().reshape(rows, cols // group, group) @ h.T).reshape(rows, cols)+ scale = rotated.abs().amax(dim = 1, keepdim = True) / 127.0+ codes = torch.round(rotated / scale).clamp(-127, 127).to(torch.int8)+ return codes, scale.reshape(rows)+++def test_qwen3_comfy_layout_int8_convrot_stays_int8(tmp_path):+ cfg, ref = _tiny_qwen3()+ group = 16+ out = {}+ for key, value in ref.state_dict().items():+ comfy_key = "model." + key # ComfyUI keeps the causal-LM naming+ if ".mlp." in key and key.endswith(".weight"):+ codes, scale = _convrot_int8(value, group)+ stem = comfy_key[: -len(".weight")]+ out[comfy_key] = codes+ out[stem + ".weight_scale"] = scale+ out[stem + ".comfy_quant"] = _quant_blob(+ {"format": "int8_tensorwise", "convrot": True, "convrot_groupsize": group}+ )+ else:+ out[comfy_key] = value.to(torch.bfloat16)+ path = _save(tmp_path / "qwen_3_4b_int8_convrot.safetensors", out)+ enc = C.build_text_encoder(+ path, encoder_cls = transformers.Qwen3Model, config = cfg, dtype = torch.bfloat16+ )+ assert type(enc.layers[0].mlp.gate_proj).__name__ == "Int8ConvRotLinear"+ assert enc.layers[0].mlp.gate_proj.weight.dtype == torch.int8+ assert getattr(enc, "_unsloth_te_prequant_scheme", None) == "int8"+ ids = torch.tensor([[1, 2, 3, 4, 5]])+ with torch.no_grad():+ got = enc(input_ids = ids).last_hidden_state.float()+ want = ref.to(torch.bfloat16)(input_ids = ids).last_hidden_state.float()+ cos = torch.nn.functional.cosine_similarity(got.flatten(), want.flatten(), dim = 0)+ assert cos > 0.98+++def test_qwen3_bf16_strip_model_prefix_and_dead_lm_head(tmp_path):+ cfg, ref = _tiny_qwen3()+ out = {"model." + k: v for k, v in ref.state_dict().items()}+ out["lm_head.weight"] = torch.randn(64, 64)+ path = _save(tmp_path / "qwen_3_4b.safetensors", out)+ enc = C.build_text_encoder(+ path, encoder_cls = transformers.Qwen3Model, config = cfg, dtype = torch.float32+ )+ ids = torch.tensor([[1, 2, 3]])+ with torch.no_grad():+ assert torch.allclose(+ enc(input_ids = ids).last_hidden_state, ref(input_ids = ids).last_hidden_state+ )+++ "conf",+ [+ {"format": "asym_w4a8_int8", "group_size": 16, "convrot": True, "convrot_groupsize": 256},+ {"format": "nvfp4"},+ {"format": "mxfp8"},+ ],+)+def test_unsupported_comfy_quant_formats_refused_by_name(tmp_path, conf):+ out = {+ "model.layers.0.mlp.down_proj.weight": torch.zeros(8, 8, dtype = torch.int8),+ "model.layers.0.mlp.down_proj.weight_scale": torch.ones(8),+ "model.layers.0.mlp.down_proj.comfy_quant": _quant_blob(conf),+ "model.layers.0.self_attn.q_norm.weight": torch.ones(8),+ }+ path = _save(tmp_path / "te_quant.safetensors", out)+ with pytest.raises(C.ComponentFileError, match = conf["format"]):+ C.quant_layers(path)+ with pytest.raises(C.ComponentFileError, match = conf["format"]):+ C.validate_component_specs([path], None, model_path = None)+++def test_wrong_class_refused_with_diagnostics(tmp_path):+ cfg, ref = _tiny_clip()+ path = _save(tmp_path / "clip.safetensors", dict(ref.state_dict()))+ qcfg, _ = _tiny_qwen3()+ with pytest.raises(C.ComponentFileError, match = "does not fit"):+ C.build_text_encoder(+ path, encoder_cls = transformers.Qwen3Model, config = qcfg, dtype = torch.float32+ )+++# ----------------------------------------------------------------------------------------------------------------------+# VAEs+++def _ldm_vae_header(+ ch = 32,+ mult = (1, 2),+ z = 4,+ layers = 2,+) -> dict:+ """The original (``ae.safetensors``) LDM VAE naming for a tiny config."""+ t: dict = {}++ def conv(+ name,+ o,+ i,+ k = 3,+ ):+ t[name + ".weight"] = (o, i, k, k)+ t[name + ".bias"] = (o,)++ def norm(name, c):+ t[name + ".weight"] = (c,)+ t[name + ".bias"] = (c,)++ def res(name, i, o):+ norm(name + ".norm1", i)+ conv(name + ".conv1", o, i)+ norm(name + ".norm2", o)+ conv(name + ".conv2", o, o)+ if i != o:+ conv(name + ".nin_shortcut", o, i, 1)++ def attn(name, c):+ norm(name + ".norm", c)+ for p in ("q", "k", "v", "proj_out"):+ conv(f"{name}.{p}", c, c, 1)++ chans = [ch * m for m in mult]+ conv("encoder.conv_in", ch, 3)+ prev = ch+ for i, c in enumerate(chans):+ for j in range(layers):+ res(f"encoder.down.{i}.block.{j}", prev, c)+ prev = c+ if i != len(chans) - 1:+ conv(f"encoder.down.{i}.downsample.conv", c, c)+ res("encoder.mid.block_1", prev, prev)+ attn("encoder.mid.attn_1", prev)+ res("encoder.mid.block_2", prev, prev)+ norm("encoder.norm_out", prev)+ conv("encoder.conv_out", 2 * z, prev)+ conv("decoder.conv_in", chans[-1], z)+ res("decoder.mid.block_1", chans[-1], chans[-1])+ attn("decoder.mid.attn_1", chans[-1])+ res("decoder.mid.block_2", chans[-1], chans[-1])+ prev = chans[-1]+ for i in reversed(range(len(chans))):+ c = chans[i]+ for j in range(layers + 1):+ res(f"decoder.up.{i}.block.{j}", prev, c)+ prev = c+ if i != 0:+ conv(f"decoder.up.{i}.upsample.conv", c, c)+ norm("decoder.norm_out", prev)+ conv("decoder.conv_out", 3, prev)+ return t+++def _tiny_kl_config():+ return {+ "in_channels": 3,+ "out_channels": 3,+ "down_block_types": ["DownEncoderBlock2D"] * 2,+ "up_block_types": ["UpDecoderBlock2D"] * 2,+ "block_out_channels": [32, 64],+ "layers_per_block": 2,+ "latent_channels": 4,+ "norm_num_groups": 32,+ "use_quant_conv": False,+ "use_post_quant_conv": False,+ }+++def test_ldm_ae_vae_loads_strictly_into_autoencoderkl(tmp_path):+ diffusers = pytest.importorskip("diffusers")+ torch.manual_seed(0)+ header = _ldm_vae_header()+ state = {k: torch.randn(shape) * 0.02 for k, shape in header.items()}+ path = _save(tmp_path / "ae.safetensors", state)+ vae = C.build_vae(+ path, vae_cls = diffusers.AutoencoderKL, config = _tiny_kl_config(), dtype = torch.float32+ )+ loaded = vae.state_dict()+ assert torch.equal(loaded["encoder.conv_in.weight"], state["encoder.conv_in.weight"])+ assert torch.equal(+ loaded["encoder.mid_block.attentions.0.to_q.weight"],+ state["encoder.mid.attn_1.q.weight"].squeeze(-1).squeeze(-1),+ )+ with torch.no_grad():+ assert vae.decode(torch.randn(1, 4, 8, 8)).sample.shape == (1, 3, 16, 16)+++def test_vae_missing_tensor_refused(tmp_path):+ diffusers = pytest.importorskip("diffusers")+ header = _ldm_vae_header()+ header.pop("decoder.conv_out.weight")+ path = _save(tmp_path / "ae.safetensors", {k: torch.zeros(s) for k, s in header.items()})+ with pytest.raises(C.ComponentFileError, match = "missing"):+ C.build_vae(+ path, vae_cls = diffusers.AutoencoderKL, config = _tiny_kl_config(), dtype = torch.float32+ )+++def test_wan_nested_vae_names_and_time_axis_squeeze():+ state = {+ "encoder.downsamples.0.downsamples.0.residual.0.gamma": 0,+ "encoder.downsamples.0.downsamples.1.residual.2.weight": 1,+ "encoder.downsamples.0.downsamples.2.resample.1.weight": 2,+ "decoder.upsamples.1.upsamples.0.shortcut.bias": 3,+ "decoder.upsamples.1.upsamples.3.time_conv.weight": 4,+ "decoder.middle.0.residual.6.weight": 5,+ "decoder.middle.2.residual.3.gamma": 6,+ "decoder.middle.1.to_qkv.weight": 7,+ "encoder.head.2.bias": 8,+ "decoder.conv1.weight": 9,+ "conv1.weight": 10,+ "conv2.bias": 11,+ }+ got = C._convert_wan_nested_vae(state)+ assert got == {+ "encoder.down_blocks.0.resnets.0.norm1.gamma": 0,+ "encoder.down_blocks.0.resnets.1.conv1.weight": 1,+ "encoder.down_blocks.0.downsampler.resample.1.weight": 2,+ "decoder.up_blocks.1.resnets.0.conv_shortcut.bias": 3,+ "decoder.up_blocks.1.upsampler.time_conv.weight": 4,+ "decoder.mid_block.resnets.0.conv2.weight": 5,+ "decoder.mid_block.resnets.1.norm2.gamma": 6,+ "decoder.mid_block.attentions.0.to_qkv.weight": 7,+ "encoder.conv_out.bias": 8,+ "decoder.conv_in.weight": 9,+ "quant_conv.weight": 10,+ "post_quant_conv.bias": 11,+ }+ fitted = C.fit_conv_shapes(+ {"a": torch.zeros(4, 2, 1, 3, 3), "b": torch.zeros(4, 2, 1, 3, 3)}, {"a": (4, 2, 3, 3)}+ )+ assert tuple(fitted["a"].shape) == (4, 2, 3, 3) and tuple(fitted["b"].shape) == (4, 2, 1, 3, 3)+++# ----------------------------------------------------------------------------------------------------------------------+# Assignment, pricing, wiring++FLUX_INDEX = {+ "text_encoder": ["transformers", "CLIPTextModel"],+ "text_encoder_2": ["transformers", "T5EncoderModel"],+ "vae": ["diffusers", "AutoencoderKL"],+ "transformer": ["diffusers", "FluxTransformer2DModel"],+}+++def _hdr(*keys, shape = (4, 4)):+ return {k: {"dtype": "BF16", "shape": list(shape)} for k in keys}+++def test_assign_flux_clip_t5_vae_in_any_order():+ t5 = (+ C.ComponentFileRef("t5"),+ _hdr("encoder.block.0.layer.0.SelfAttention.q.weight", "shared.weight"),+ )+ clip = (C.ComponentFileRef("clip"), _hdr("text_model.encoder.layers.0.mlp.fc1.weight"))+ ae = (C.ComponentFileRef("ae"), _hdr("decoder.up.0.block.0.conv1.weight"))+ assigned, kinds = C.assign_components(+ [t5, clip], ae, C.component_classes_from_index(FLUX_INDEX)+ )+ assert {c: r.spec for c, r in assigned.items()} == {+ "text_encoder_2": "t5",+ "text_encoder": "clip",+ "vae": "ae",+ }+ assert kinds["vae"] == "ldm_kl"+++def test_assign_refuses_wrong_family_and_double_slot():+ classes = C.component_classes_from_index(FLUX_INDEX)+ qwen = (C.ComponentFileRef("qwen_3_4b"), _hdr("model.layers.0.self_attn.q_norm.weight"))+ with pytest.raises(C.ComponentFileError, match = "qwen3 text encoder"):+ C.assign_components([qwen], None, classes, family = "flux.1")+ t5 = (+ C.ComponentFileRef("t5"),+ _hdr("encoder.block.0.layer.0.SelfAttention.q.weight", "shared.weight"),+ )+ with pytest.raises(C.ComponentFileError, match = "already taken"):+ C.assign_components([t5, t5], None, classes)+ wan = (C.ComponentFileRef("wan"), _hdr("decoder.upsamples.0.residual.0.gamma"))+ with pytest.raises(C.ComponentFileError, match = "AutoencoderKL"):+ C.assign_components([], wan, classes)+++def test_resident_bytes_prices_int8_at_stored_size_and_fp8_dequantized(tmp_path):+ out = {+ "a.weight": torch.zeros(64, 64, dtype = torch.int8),+ "a.weight_scale": torch.ones(64),+ "a.comfy_quant": _quant_blob(+ {"format": "int8_tensorwise", "convrot": True, "convrot_groupsize": 16}+ ),+ "b.weight": torch.zeros(64, 64, dtype = torch.float8_e4m3fn),+ "b.weight_scale": torch.ones(()),+ "b.comfy_quant": _quant_blob({"format": "float8_e4m3fn"}),+ "c.weight": torch.zeros(64, dtype = torch.bfloat16),+ }+ path = _save(tmp_path / "te.safetensors", out)+ assert C.resident_bytes(path, dtype_itemsize = 2) == (64 * 64 + 64 * 4) + 64 * 64 * 2 + 64 * 2+++def test_planner_replaces_scanned_component_with_supplied_file(tmp_path):+ from core.inference.diffusion import DiffusionBackend++ base = tmp_path / "base"+ _save(+ base / "text_encoder" / "model.safetensors",+ {"w": torch.zeros(1024, 1024, dtype = torch.bfloat16)},+ )+ _save(+ base / "vae" / "diffusion_pytorch_model.safetensors",+ {"w": torch.zeros(512, 512, dtype = torch.bfloat16)},+ )+ (base / "model_index.json").write_text("{}")+ supplied = _save(+ tmp_path / "te.safetensors", {"w": torch.zeros(2048, 1024, dtype = torch.bfloat16)}+ )+ ov = C.ComponentOverrides(+ files = {"text_encoder": C.ComponentFileRef(supplied, local_path = supplied)},+ paths = {"text_encoder": supplied},+ classes = {"text_encoder": "Qwen3Model"},+ )+ token = C.set_active_component_overrides(ov)+ try:+ scanned, scanned_te, got, got_te = DiffusionBackend._supplied_component_mib(+ str(base), None, torch.bfloat16+ )+ finally:+ C.reset_active_component_overrides(token)+ assert (scanned, scanned_te, got, got_te) == (2, 2, 4, 4)+ assert DiffusionBackend._supplied_component_mib(str(base), None, torch.bfloat16) is None+++def test_te_prequant_kwargs_inject_supplied_and_skip_precast(monkeypatch):+ import core.inference.diffusion_te_prequant as tp++ sentinel = object()+ ov = C.ComponentOverrides(+ files = {"text_encoder": C.ComponentFileRef("x")}, paths = {"text_encoder": "x"}, classes = {}+ )+ ov.modules["text_encoder"] = sentinel+ monkeypatch.setattr(+ tp,+ "te_prequant_sources_for_base",+ lambda *a, **k: {+ "text_encoder": types.SimpleNamespace(kind = "repo", location = "r", filename = "f")+ },+ )++ def _boom(*a, **k):+ raise AssertionError("the pre-cast encoder must not load for a supplied component")++ monkeypatch.setattr(tp, "load_prequant_text_encoder", _boom)+ token = C.set_active_component_overrides(ov)+ try:+ got = tp.te_prequant_pipe_kwargs(+ types.SimpleNamespace(name = "qwen-image-2.1"),+ "base",+ te_quant_mode = "fp8",+ target = None,+ dtype = None,+ )+ finally:+ C.reset_active_component_overrides(token)+ assert got == {"text_encoder": sentinel}+ assert tp.supplied_component_pipe_kwargs("base", dtype = None) == {}+++def test_te_quant_auto_does_not_recast_supplied_encoder():+ from core.inference.diffusion import _te_quant_for_supplied_encoders++ assert _te_quant_for_supplied_encoders(None) == "none"+ assert _te_quant_for_supplied_encoders("auto") == "none"+ assert _te_quant_for_supplied_encoders("fp8") == "fp8"+++def test_request_model_normalizes_and_validates():+ from models.inference import DiffusionLoadRequest++ req = DiffusionLoadRequest(model_path = "/x", text_encoder_file = " /a.safetensors ", vae_file = " ")+ assert req.text_encoder_file == ["/a.safetensors"] and req.vae_file is None+ assert req.supplied_text_encoder_files() == ["/a.safetensors"]+ with pytest.raises(Exception):+ DiffusionLoadRequest(+ model_path = "/x", text_encoder_file = ["/a.safetensors", "/a.safetensors"]+ )+ assert DiffusionLoadRequest(model_path = "/x").supplied_text_encoder_files() is None+++def test_validate_load_request_refuses_pipeline_kind_and_missing_files(tmp_path):+ from core.inference.diffusion import DiffusionBackend++ fam = types.SimpleNamespace(name = "flux.1", single_file_is_pipeline = False, pipeline_only = False)+ with pytest.raises(ValueError, match = "single-file or GGUF"):+ DiffusionBackend._validate_component_files(+ fam, "pipeline", "unsloth/FLUX.1-schnell", ["/x.safetensors"], None+ )+ with pytest.raises(ValueError, match = "does not exist"):+ DiffusionBackend._validate_component_files(+ fam, "gguf", str(tmp_path), [str(tmp_path / "nope.safetensors")], None+ )+ sdxl = types.SimpleNamespace(name = "sdxl", single_file_is_pipeline = True, pipeline_only = False)+ with pytest.raises(ValueError, match = "whole-pipeline"):+ DiffusionBackend._validate_component_files(+ sdxl, "single_file", str(tmp_path), None, "/v.safetensors"+ )+ vae_as_te = _save(+ tmp_path / "ae.safetensors", {"decoder.up.0.block.0.conv1.weight": torch.zeros(2, 2)}+ )+ with pytest.raises(ValueError, match = "pass it as vae_file"):+ DiffusionBackend._validate_component_files(fam, "gguf", str(tmp_path), [vae_as_te], None)+++def test_supplied_int8_encoder_reported_as_int8_without_a_request():+ from core.inference.diffusion_precision import quantize_text_encoders++ encoder = torch.nn.Linear(2, 2)+ encoder._unsloth_te_prequant_scheme = "int8"+ pipe = types.SimpleNamespace(text_encoder = encoder)+ outcome = quantize_text_encoders(pipe, types.SimpleNamespace(device = "cpu"), mode = None)+ assert outcome.mode == "int8" and "supplied file" in outcome.reason+ # A dense encoder with no request stays unreported, exactly as before.+ assert (+ quantize_text_encoders(+ types.SimpleNamespace(text_encoder = torch.nn.Linear(2, 2)), None, mode = None+ ).mode+ is None+ )+++def test_mixed_supplied_int8_encoder_still_reported():+ from core.inference.diffusion_precision import quantize_text_encoders++ int8 = torch.nn.Linear(2, 2)+ int8._unsloth_te_prequant_scheme = "int8"+ pipe = types.SimpleNamespace(text_encoder = torch.nn.Linear(2, 2), text_encoder_2 = int8)+ outcome = quantize_text_encoders(pipe, types.SimpleNamespace(device = "cpu"), mode = None)+ assert outcome.mode == "int8" and "text_encoder_2 only" in outcome.reason+++def test_hub_repo_ids_names_only_hub_specs(tmp_path):+ te = _save(tmp_path / "clip_l.safetensors", {"x": torch.zeros(1)})+ assert C.hub_repo_ids(+ [te, "unsloth/A/te.safetensors", "unsloth/A/te2.safetensors"],+ "unsloth/B/vae/ae.safetensors",+ model_path = str(tmp_path),+ ) == ("unsloth/A", "unsloth/B")+++def test_quantized_hub_vae_refused_at_planning(tmp_path, monkeypatch):+ vae = _save(+ tmp_path / "hub" / "ae.safetensors",+ {k: torch.zeros(shape) for k, shape in _ldm_vae_header().items()},+ )+ monkeypatch.setattr(+ C, "quant_layers", lambda path: {"decoder.conv_in": object()} if path == vae else {}+ )+ with pytest.raises(C.ComponentFileError, match = "quantized VAE"):+ C.plan_component_overrides(+ text_encoder_files = [],+ vae_file = "unsloth/R/ae.safetensors",+ model_path = None,+ model_index = {"vae": ["diffusers", "AutoencoderKL"]},+ resolve_hub = lambda ref: vae,+ )+++def _base_with_configs(+ tmp_path,+ te_cfg,+ vae_cfg = None,+):+ base = tmp_path / "base"+ te_cfg.save_pretrained(base / "text_encoder")+ if vae_cfg is not None:+ (base / "vae").mkdir(parents = True)+ (base / "vae" / "config.json").write_text(+ json.dumps({"_class_name": "AutoencoderKL", **vae_cfg}), encoding = "utf-8"+ )+ return str(base)+++def _overrides(+ paths: dict,+ classes: dict,+ kinds: dict | None = None,+):+ refs = {c: C.ComponentFileRef(spec = p, local_path = p) for c, p in paths.items()}+ return C.ComponentOverrides(files = refs, paths = dict(paths), classes = classes, kinds = kinds or {})+++def test_verify_fit_refuses_wrong_size_encoder_before_load(tmp_path):+ cfg, ref = _tiny_qwen3()+ path = _save(+ tmp_path / "qwen3.safetensors", {"model." + k: v for k, v in ref.state_dict().items()}+ )+ big = transformers.Qwen3Config(+ **{**cfg.to_dict(), "hidden_size": 128, "num_attention_heads": 8}+ )+ ok = _overrides({"text_encoder": path}, {"text_encoder": "Qwen3Model"})+ C.verify_override_fit(ok, base = _base_with_configs(tmp_path / "a", cfg), local_files_only = True)+ with pytest.raises(C.ComponentFileError, match = "does not fit"):+ C.verify_override_fit(+ ok, base = _base_with_configs(tmp_path / "b", big), local_files_only = True+ )+++def test_verify_fit_checks_vae_from_header_only(tmp_path):+ pytest.importorskip("diffusers")+ cfg, _ = _tiny_qwen3()+ header = _ldm_vae_header()+ good = _save(tmp_path / "ae.safetensors", {k: torch.zeros(s) for k, s in header.items()})+ header.pop("decoder.conv_out.weight")+ bad = _save(tmp_path / "ae_bad.safetensors", {k: torch.zeros(s) for k, s in header.items()})+ base = _base_with_configs(tmp_path, cfg, _tiny_kl_config())+ classes = {"vae": "AutoencoderKL"}+ C.verify_override_fit(+ _overrides({"vae": good}, classes, {"vae": "ldm_kl"}), base = base, local_files_only = True+ )+ with pytest.raises(C.ComponentFileError, match = "does not fit"):+ C.verify_override_fit(+ _overrides({"vae": bad}, classes, {"vae": "ldm_kl"}), base = base, local_files_only = True+ )+++def test_verify_fit_refuses_recasting_a_stored_int8_encoder(tmp_path):+ cfg, ref = _tiny_qwen3()+ out = {}+ for key, value in ref.state_dict().items():+ comfy_key = "model." + key+ if ".mlp." in key and key.endswith(".weight"):+ codes, scale = _convrot_int8(value, 16)+ stem = comfy_key[: -len(".weight")]+ out[comfy_key], out[stem + ".weight_scale"] = codes, scale+ out[stem + ".comfy_quant"] = _quant_blob(+ {"format": "int8_tensorwise", "convrot": True, "convrot_groupsize": 16}+ )+ else:+ out[comfy_key] = value.to(torch.bfloat16)+ path = _save(tmp_path / "q_int8.safetensors", out)+ base = _base_with_configs(tmp_path, cfg)+ overrides = _overrides({"text_encoder": path}, {"text_encoder": "Qwen3Model"})+ for ok in (None, "auto", "int8"):+ C.verify_override_fit(overrides, base = base, local_files_only = True, text_encoder_quant = ok)+ with pytest.raises(C.ComponentFileError, match = "cannot be re-cast to fp8"):+ C.verify_override_fit(overrides, base = base, local_files_only = True, text_encoder_quant = "fp8")+ for dense in ("none", "off"):+ with pytest.raises(C.ComponentFileError, match = "cannot be re-cast to dense"):+ C.verify_override_fit(+ overrides, base = base, local_files_only = True, text_encoder_quant = dense+ )+++def test_memory_plan_prices_hosted_precast_only_for_unsupplied_slots(monkeypatch):+ import core.inference.diffusion as D+ import core.inference.diffusion_te_prequant as P++ src = types.SimpleNamespace(kind = "path", location = __file__)+ monkeypatch.setattr(+ P,+ "te_prequant_sources_for_base",+ lambda *a, **k: {"text_encoder": src, "text_encoder_2": src},+ )+ full = D.DiffusionBackend._precast_text_encoder_mib(+ types.SimpleNamespace(name = "flux"), "b", None, "fp8"+ )+ one = D.DiffusionBackend._precast_text_encoder_mib(+ types.SimpleNamespace(name = "flux"), "b", None, "fp8", skip_components = ("text_encoder",)+ )+ both = D.DiffusionBackend._precast_text_encoder_mib(+ types.SimpleNamespace(name = "flux"),+ "b",+ None,+ "fp8",+ skip_components = ("text_encoder", "text_encoder_2"),+ )+ assert (+ full[1] == ("text_encoder", "text_encoder_2")+ and one[1] == ("text_encoder_2",)+ and both is None+ )+++def test_hidream_standalone_llama_slot_refused_by_name():+ ref = C.ComponentFileRef(spec = "llama.safetensors", local_path = "llama.safetensors")+ header = {+ "model.layers.0.self_attn.q_proj.weight": {"shape": [4, 4]},+ "model.embed_tokens.weight": {"shape": [4, 4]},+ }+ with pytest.raises(C.ComponentFileError, match = "loads text_encoder_4 from its own repo"):+ C.assign_components(+ [(ref, header)], None, {"text_encoder_4": "LlamaForCausalLM"}, family = "hidream-i1"+ )diff --git a/studio/frontend/src/features/images/api.ts b/studio/frontend/src/features/images/api.tsindex 2eab812ff50..89350d82d6a 100644--- a/studio/frontend/src/features/images/api.ts+++ b/studio/frontend/src/features/images/api.ts@@ -40,6 +40,8 @@ export interface DiffusionStatus {// Resolved load kind: "gguf" | "single_file" | "pipeline". Gates GGUF-only controls. Null when not loaded.model_kind?: string | null;gguf_filename?: string | null;+ // Supplied text-encoder / VAE files: pipeline component -> basename.+ component_files?: Record<string, string> | null;// Selected GGUF quant. Newer backends report this separately from the compute dtype.gguf_variant?: string | null;cpu_offload: boolean;@@ -127,6 +129,9 @@ export interface DiffusionLoadRequest {family_override?: string;hf_token?: string;cpu_offload?: boolean;+ // Separate .safetensors files (e.g. ComfyUI models/text_encoders, models/vae); gguf / single_file only.+ text_encoder_file?: string | string[];+ vae_file?: string;// Advanced (load-time) tuning. All optional; omit for the backend's auto defaults.speed_mode?: "off" | "eager" | "default" | "max";transformer_quant?: "auto" | "none" | "off" | "int8" | "fp8" | "nvfp4" | "mxfp8";diff --git a/studio/frontend/src/features/images/component-files.ts b/studio/frontend/src/features/images/component-files.tsnew file mode 100644index 00000000000..2c7bbad3378--- /dev/null+++ b/studio/frontend/src/features/images/component-files.ts@@ -0,0 +1,35 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++const LIST_SEPARATOR = /[\n,]/;++/** One path per line or comma separated. */+export function splitComponentFileList(raw: string | null | undefined): string[] {+ if (!raw) {+ return [];+ }+ return raw+ .split(LIST_SEPARATOR)+ .map((part) => part.trim())+ .filter((part) => part.length > 0);+}++/** Only a single-file / GGUF transformer takes these, so plan and load requests stay identical. */+export function componentFileFields(+ kind: string | null | undefined,+ textEncoderFiles: string | readonly string[] | undefined,+ vaeFile: string | undefined,+): { text_encoder_file?: string[]; vae_file?: string } {+ if (kind !== "gguf" && kind !== "single_file") {+ return {};+ }+ const encoders =+ typeof textEncoderFiles === "string"+ ? splitComponentFileList(textEncoderFiles)+ : (textEncoderFiles ?? []).map((f) => f.trim()).filter((f) => f.length > 0);+ const vae = vaeFile?.trim();+ return {+ ...(encoders.length > 0 ? { text_encoder_file: encoders } : {}),+ ...(vae ? { vae_file: vae } : {}),+ };+}diff --git a/studio/frontend/src/features/images/image-model-recall.ts b/studio/frontend/src/features/images/image-model-recall.tsindex d2fa3d8753b..06b006fc22e 100644--- a/studio/frontend/src/features/images/image-model-recall.ts+++ b/studio/frontend/src/features/images/image-model-recall.ts@@ -9,6 +9,9 @@ export interface RememberedImageModel {filename?: string;// An opaque pipeline reloads only under the family it was loaded with.familyOverride?: string;+ // Supplied text-encoder / VAE files: status names only basenames, so a recall must carry the paths.+ textEncoderFiles?: string[];+ vaeFile?: string;}const KEY = "unsloth:images:last-model";@@ -25,6 +28,11 @@ export function readImageModel(): RememberedImageModel | null {)return null;const family = explicitFamily(value.familyOverride);+ const encoders = Array.isArray(value.textEncoderFiles)+ ? value.textEncoderFiles.filter(+ (f: unknown): f is string => typeof f === "string" && f.length > 0,+ )+ : [];return {repoId: value.repoId,kind: value.kind,@@ -32,6 +40,10 @@ export function readImageModel(): RememberedImageModel | null {? { filename: value.filename }: {}),...(family ? { familyOverride: family } : {}),+ ...(encoders.length > 0 ? { textEncoderFiles: encoders } : {}),+ ...(typeof value.vaeFile === "string" && value.vaeFile+ ? { vaeFile: value.vaeFile }+ : {}),};} catch {return null;@@ -62,3 +74,20 @@ export function matchesRememberedModel((model.kind === "pipeline" || status.gguf_filename === model.filename));}++const basename = (path: string): string => path.split(/[\\/]/).pop() ?? path;++/** Whether the resident build's component files (basenames, from status) are the remembered paths. */+export function componentFilesMatch(+ model: Pick<RememberedImageModel, "textEncoderFiles" | "vaeFile">,+ componentFiles: Record<string, string> | null | undefined,+): boolean {+ const remembered = [...(model.textEncoderFiles ?? []), ...(model.vaeFile ? [model.vaeFile] : [])]+ .map(basename)+ .sort();+ const resident = Object.values(componentFiles ?? {}).sort();+ return (+ remembered.length === resident.length &&+ remembered.every((name, i) => name === resident[i])+ );+}diff --git a/studio/frontend/src/features/images/images-page.tsx b/studio/frontend/src/features/images/images-page.tsxindex a0d1e691d70..87e2ad02d8d 100644--- a/studio/frontend/src/features/images/images-page.tsx+++ b/studio/frontend/src/features/images/images-page.tsx@@ -2,7 +2,8 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import { generationFailureLogsAction } from "@/features/settings/lib/view-logs-action";-import { readImageModel, rememberImageModel, matchesRememberedModel, type RememberedImageModel } from "./image-model-recall";+import { readImageModel, rememberImageModel, matchesRememberedModel, componentFilesMatch, type RememberedImageModel } from "./image-model-recall";+import { componentFileFields, splitComponentFileList } from "./component-files";import {type ReactNode,type SetStateAction,@@ -269,11 +270,18 @@ import {} from "./train/train-base-selector";function withEngagedFamily(- { repoId, kind, filename }: RememberedImageModel,+ { repoId, kind, filename, textEncoderFiles, vaeFile }: RememberedImageModel,status: Pick<DiffusionStatus, "resolved">,): RememberedImageModel {const family = explicitFamily(resolvedFamilyOverrideSelection(status.resolved?.family_override));- return { repoId, kind, ...(filename ? { filename } : {}), ...(family ? { familyOverride: family } : {}) };+ return {+ repoId,+ kind,+ ...(filename ? { filename } : {}),+ ...(family ? { familyOverride: family } : {}),+ ...(textEncoderFiles?.length ? { textEncoderFiles } : {}),+ ...(vaeFile ? { vaeFile } : {}),+ };}/** Whether this pick may receive a transformer precision request. Unknown repos defer to the backend. */@@ -787,6 +795,54 @@ function ResolvedBadge({);}+const COMPONENT_FILES_HINT =+ "Optional. Use separate ComfyUI text encoder / VAE .safetensors files instead of downloading the base model's. Absolute path, or relative to the model folder (e.g. ../text_encoders/clip_l.safetensors). Only for single-file or GGUF transformers.";++function AdvancedTextField({+ label,+ hint,+ placeholder,+ value,+ onValueChange,+ multiline = false,+}: {+ label: string;+ hint?: ReactNode;+ placeholder?: string;+ value: string;+ onValueChange: (v: string) => void;+ multiline?: boolean;+}) {+ return (+ <div className="flex flex-col gap-1">+ <span className="flex shrink-0 items-center gap-1 whitespace-nowrap text-xs font-medium text-muted-foreground">+ {label}+ {hint && <InfoHint>{hint}</InfoHint>}+ </span>+ {multiline ? (+ <Textarea+ aria-label={label}+ rows={2}+ spellCheck={false}+ placeholder={placeholder}+ value={value}+ onChange={(e) => onValueChange(e.target.value)}+ className="min-h-0 resize-y font-mono text-xs"+ />+ ) : (+ <Input+ aria-label={label}+ spellCheck={false}+ placeholder={placeholder}+ value={value}+ onChange={(e) => onValueChange(e.target.value)}+ className="h-8 font-mono text-xs"+ />+ )}+ </div>+ );+}+function AdvancedSelect({label,hint,@@ -1270,6 +1326,14 @@ function LoadedBuildSummary({ status }: { status: DiffusionStatus | null }) {}badge={<ResolvedBadge status={status} controlKey="text_encoder_quant" />}/>+ {status.component_files && Object.keys(status.component_files).length > 0 ? (+ <BuildRow+ label="Text encoder / VAE files"+ value={Object.entries(status.component_files)+ .map(([component, file]) => `${component}: ${file}`)+ .join(", ")}+ />+ ) : null}<BuildRowlabel="Memory"value={@@ -1308,6 +1372,7 @@ function reportLoadFailure(message: string | null | undefined, fallback: string)type Busy = "loading" | "unloading" | "generating" | null;type ImageLoadOptions = { kind: "gguf" | "single_file" | "pipeline"; filename?: string; displayRepoId?: string };+type LastLoad = { repoId: string } & ImageLoadOptions & Pick<RememberedImageModel, "textEncoderFiles" | "vaeFile">;// What a pick optimistically replaced, so a load that never takes can put it all back. The// quant label and the recipe move together at pick time, so they roll back together.@@ -1336,6 +1401,8 @@ type LoadAdvanced = Pick<| "family_override"| "loras"| "gpu_ids"+ | "text_encoder_file"+ | "vae_file">;function openImageLabel(t: ReturnType<typeof useT>, prompt: string): string {@@ -1527,6 +1594,8 @@ export function ImagesPage({setTextEncoderQuant((v) => nvfp4SelectionFallback(v, nvfp4DiffusionKnown, nvfp4Diffusion));}, [nvfp4Diffusion, nvfp4DiffusionKnown, transformerQuant, textEncoderQuant]);const [memoryMode, setMemoryMode] = useState<"auto" | "fast" | "balanced" | "low_vram">("auto");+ const [textEncoderFiles, setTextEncoderFiles] = useState("");+ const [vaeFile, setVaeFile] = useState("");// "auto", or the physical index to pin this load to; offered only on a multi-card CUDA/ROCm// host. Persisted, unlike the selects around it: status carries the device a pipeline is on// but not which card, so a refresh would reset it to Auto. A stale id is dropped on send.@@ -1538,7 +1607,7 @@ export function ImagesPage({const [transformerCache, setTransformerCache] = useState<"auto" | "off" | "fbcache" | "static">("auto");const [cpuOffload, setCpuOffload] = useState(false);// The last load descriptor, so "Reapply" can reload the same model with new advanced options without re-picking it.- const lastLoad = useRef<({ repoId: string } & ImageLoadOptions) | null>(null);+ const lastLoad = useRef<LastLoad | null>(null);// Render-safe mirror of whether a page-initiated load supplied a complete Reapply target.const [canReapply, setCanReapply] = useState(false);// Repo id whose defaults were already seeded from a discovered resident model, so we seed@@ -2848,6 +2917,11 @@ export function ImagesPage({gpuChoices.some((d) => String(d.index) === selectedGpu)? [Number(selectedGpu)]: undefined,+ text_encoder_file: (() => {+ const files = splitComponentFileList(textEncoderFiles);+ return files.length > 0 ? files : undefined;+ })(),+ vae_file: vaeFile.trim() || undefined,};},[@@ -2862,6 +2936,8 @@ export function ImagesPage({familyOverride,selectedGpu,gpuChoices,+ textEncoderFiles,+ vaeFile,],);@@ -2909,7 +2985,15 @@ export function ImagesPage({const bakeLoras = advanced.loras ?? [];// Whether THIS load carries the selection into the build, so a quantized load that did not can drop it.bakedLorasOnLoad.current = bakeLoras.length > 0;- lastLoad.current = { repoId, kind: opts.kind, filename: opts.filename, displayRepoId: opts.displayRepoId };+ const componentFiles = componentFileFields(opts.kind, advanced.text_encoder_file, advanced.vae_file);+ lastLoad.current = {+ repoId,+ kind: opts.kind,+ filename: opts.filename,+ displayRepoId: opts.displayRepoId,+ textEncoderFiles: componentFiles.text_encoder_file,+ vaeFile: componentFiles.vae_file,+ };setCanReapply(true);// Carry the prior target so the async poll can restore it if the background load fails after starting.lastLoadRevert.current = { prev: prevLastLoad };@@ -2935,6 +3019,7 @@ export function ImagesPage({family_override: advanced.family_override,loras: bakeLoras.length > 0 ? bakeLoras : undefined,gpu_ids: advanced.gpu_ids,+ ...componentFiles,});await startRequest;} catch (err) {@@ -3157,6 +3242,7 @@ export function ImagesPage({// The plan route preflights precision and sizes the file set against the card the load will// use, so a selection the load carries has to reach the plan.gpu_ids: advanced.gpu_ids,+ ...componentFileFields(opts.kind, advanced.text_encoder_file, advanced.vae_file),}),[],);@@ -4439,7 +4525,18 @@ export function ImagesPage({(kind === "pipeline" ||((kind === "gguf" || kind === "single_file") && status.gguf_filename))) {- const model = withEngagedFamily({ repoId: status.repo_id, kind, filename: status.gguf_filename ?? undefined }, status);+ const model = withEngagedFamily(+ lastLoad.current &&+ matchesRememberedModel(lastLoad.current, status) &&+ componentFilesMatch(lastLoad.current, status.component_files)+ ? lastLoad.current+ : rememberedModel &&+ matchesRememberedModel(rememberedModel, status) &&+ componentFilesMatch(rememberedModel, status.component_files)+ ? rememberedModel+ : { repoId: status.repo_id, kind, filename: status.gguf_filename ?? undefined },+ status,+ );rememberImageModel(model);setRememberedModel(model);}@@ -4465,7 +4562,13 @@ export function ImagesPage({rememberedModel.repoId,{ kind: rememberedModel.kind, filename: rememberedModel.filename },// Only the family the remembered load engaged; the live selection belongs to whatever is picked next.- { ...currentLoadAdvanced(rememberedModel.repoId, false, true), family_override: rememberedModel.familyOverride },+ {+ ...currentLoadAdvanced(rememberedModel.repoId, false, true),+ family_override: rememberedModel.familyOverride,+ // The recalled build's own encoder / VAE files, not whatever the fields hold now.+ text_encoder_file: rememberedModel.textEncoderFiles,+ vae_file: rememberedModel.vaeFile,+ },);if (!started) pendingRecalledGeneration.current = null;}, [@@ -4630,6 +4733,21 @@ export function ImagesPage({nvfp4Diffusion,)}/>+ <AdvancedTextField+ label="Text encoder file(s)"+ hint={COMPONENT_FILES_HINT}+ multiline+ placeholder="../text_encoders/clip_l.safetensors"+ value={textEncoderFiles}+ onValueChange={setTextEncoderFiles}+ />+ <AdvancedTextField+ label="VAE file"+ hint={COMPONENT_FILES_HINT}+ placeholder="../vae/ae.safetensors"+ value={vaeFile}+ onValueChange={setVaeFile}+ /><AdvancedSelectlabel="Attention"hint="Attention kernel. Auto upgrades to cuDNN fused attention on NVIDIA when a speed profile is active. sage is INT8 attention (SageAttention 2; without a local install Studio fetches the Hugging Face kernels-hub build, which runs on Ampere, Ada and Hopper GPUs, and any other GPU keeps the default): fast (10-40%) but can black-frame some families (Qwen, Wan), so it never engages automatically."diff --git a/studio/frontend/tests/image-component-files.test.ts b/studio/frontend/tests/image-component-files.test.tsnew file mode 100644index 00000000000..f4fc69112f6--- /dev/null+++ b/studio/frontend/tests/image-component-files.test.ts@@ -0,0 +1,33 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import assert from "node:assert/strict";+import test from "node:test";+import {+ componentFileFields,+ splitComponentFileList,+} from "../src/features/images/component-files.ts";++test("splitComponentFileList accepts newlines and commas, trims, drops blanks", () => {+ assert.deepEqual(splitComponentFileList(""), []);+ assert.deepEqual(splitComponentFileList(undefined), []);+ assert.deepEqual(splitComponentFileList(" \n , \n"), []);+ assert.deepEqual(+ splitComponentFileList(" ../text_encoders/clip_l.safetensors \n\n/abs/t5xxl.safetensors, owner/repo/te.safetensors ,"),+ ["../text_encoders/clip_l.safetensors", "/abs/t5xxl.safetensors", "owner/repo/te.safetensors"],+ );+});++test("componentFileFields sends only for single-file / GGUF and only non-empty values", () => {+ assert.deepEqual(componentFileFields("pipeline", ["a.safetensors"], "vae.safetensors"), {});+ assert.deepEqual(componentFileFields(undefined, ["a.safetensors"], "vae.safetensors"), {});+ assert.deepEqual(componentFileFields("gguf", undefined, undefined), {});+ assert.deepEqual(componentFileFields("gguf", [" ", ""], " "), {});+ assert.deepEqual(componentFileFields("single_file", ["a.safetensors"], undefined), {+ text_encoder_file: ["a.safetensors"],+ });+ assert.deepEqual(componentFileFields("gguf", "a.safetensors\nb.safetensors", " vae.safetensors "), {+ text_encoder_file: ["a.safetensors", "b.safetensors"],+ vae_file: "vae.safetensors",+ });+});diff --git a/studio/frontend/tests/image-model-recall.test.ts b/studio/frontend/tests/image-model-recall.test.tsindex 54a604a8be2..44e6ecf9bb5 100644--- a/studio/frontend/tests/image-model-recall.test.ts+++ b/studio/frontend/tests/image-model-recall.test.ts@@ -6,10 +6,12 @@ import test from "node:test";import ts from "typescript";import { explicitFamily } from "../src/features/model-picker/components/model-selector/family-override.ts";import {+ componentFilesMatch,matchesRememberedModel,readImageModel,rememberImageModel,} from "../src/features/images/image-model-recall.ts";+import { splitComponentFileList } from "../src/features/images/component-files.ts";import { installLocalStorageFake, readSrc } from "./helpers/kit.ts";const { storage } = installLocalStorageFake();@@ -59,6 +61,9 @@ test("recalling a quantized model carries the selected adapters into its load",transformerCache: "auto",selectedGpu: "auto",gpuChoices: [],+ textEncoderFiles: "",+ vaeFile: "",+ splitComponentFileList,busy: null,imagePresets: { hydrated: true },prompt: "a teapot",@@ -131,6 +136,88 @@ test("recalling a quantized model carries the selected adapters into its load",});await callbacks.handleGenerateWithRecall();assert.equal((loads[0][2] as { family_override?: string }).family_override, "flux.1");++ // A recalled build loads with its own encoder / VAE files, never the live fields.+ type Files = { text_encoder_file?: string[]; vae_file?: string };+ const supplied = {+ repoId: "/comfy/models/diffusion_models",+ kind: "gguf",+ filename: "z.gguf",+ textEncoderFiles: ["../text_encoders/qwen_3_4b.safetensors"],+ vaeFile: "../vae/ae.safetensors",+ };+ const withFiles = recall({ rememberedModel: supplied, textEncoderFiles: "live.safetensors", vaeFile: "live_vae.safetensors" });+ await withFiles.callbacks.handleGenerateWithRecall();+ assert.deepEqual((withFiles.loads[0][2] as Files).text_encoder_file, supplied.textEncoderFiles);+ assert.equal((withFiles.loads[0][2] as Files).vae_file, supplied.vaeFile);+ // After a refresh with the model still resident, the stored paths survive (status names only basenames).+ const resident = recall({+ rememberedModel: supplied,+ status: {+ loaded: true,+ repo_id: supplied.repoId,+ model_kind: "gguf",+ gguf_filename: "z.gguf",+ component_files: { text_encoder: "qwen_3_4b.safetensors", vae: "ae.safetensors" },+ },+ matchesRememberedModel,+ componentFilesMatch,+ withEngagedFamily: (m: Record<string, unknown>) => m,+ rememberImageModel: (m: unknown) => storage.setItem("unsloth:images:last-model", JSON.stringify(m)),+ setRememberedModel: () => {},+ handleGenerate: async () => {},+ });+ await resident.callbacks.handleGenerateWithRecall();+ assert.deepEqual(readImageModel()?.textEncoderFiles, supplied.textEncoderFiles);+ assert.equal(readImageModel()?.vaeFile, supplied.vaeFile);+ // Another client reloaded the same checkpoint without the files: the stale paths are dropped.+ const reloaded = recall({+ rememberedModel: supplied,+ status: { loaded: true, repo_id: supplied.repoId, model_kind: "gguf", gguf_filename: "z.gguf", component_files: null },+ matchesRememberedModel,+ componentFilesMatch,+ withEngagedFamily: (m: Record<string, unknown>) => m,+ rememberImageModel: (m: unknown) => storage.setItem("unsloth:images:last-model", JSON.stringify(m)),+ setRememberedModel: () => {},+ handleGenerate: async () => {},+ });+ await reloaded.callbacks.handleGenerateWithRecall();+ assert.equal(readImageModel()?.textEncoderFiles, undefined);+ assert.equal(readImageModel()?.vaeFile, undefined);+ // Same for this tab's own last load once the resident build no longer uses its files.+ const ownStale = recall({+ rememberedModel: null,+ lastLoad: { current: supplied },+ status: { loaded: true, repo_id: supplied.repoId, model_kind: "gguf", gguf_filename: "z.gguf", component_files: null },+ matchesRememberedModel,+ componentFilesMatch,+ withEngagedFamily: (m: Record<string, unknown>) => m,+ rememberImageModel: (m: unknown) => storage.setItem("unsloth:images:last-model", JSON.stringify(m)),+ setRememberedModel: () => {},+ handleGenerate: async () => {},+ });+ await ownStale.callbacks.handleGenerateWithRecall();+ assert.equal(readImageModel()?.textEncoderFiles, undefined);+ const without = recall({ rememberedModel: { ...supplied, textEncoderFiles: undefined, vaeFile: undefined }, textEncoderFiles: "live.safetensors" });+ await without.callbacks.handleGenerateWithRecall();+ assert.equal((without.loads[0][2] as Files).text_encoder_file, undefined);+ assert.equal((without.loads[0][2] as Files).vae_file, undefined);+});++test("recall keeps supplied encoder / VAE file paths", () => {+ const model = {+ repoId: "/comfy/models/diffusion_models",+ kind: "gguf" as const,+ filename: "z.gguf",+ textEncoderFiles: ["../text_encoders/clip_l.safetensors", "../text_encoders/t5xxl.safetensors"],+ vaeFile: "../vae/ae.safetensors",+ };+ rememberImageModel(model);+ assert.deepEqual(readImageModel(), model);+ storage.setItem("unsloth:images:last-model", JSON.stringify({ ...model, textEncoderFiles: [1, ""], vaeFile: 2 }));+ const read = readImageModel();+ assert.equal(read?.textEncoderFiles, undefined);+ assert.equal(read?.vaeFile, undefined);});test("recall keeps an explicit family and drops Auto", () => {