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 NVFP4: tag the compile cache in both switch states so a legacy cache never matches (#15055)
Daniel Han2b0c60e7e29f
diff --git a/studio/backend/core/inference/diffusion.py b/studio/backend/core/inference/diffusion.pyindex 9d1d2bf465d..170f9a70cd0 100644--- a/studio/backend/core/inference/diffusion.py+++ b/studio/backend/core/inference/diffusion.py@@ -8057,6 +8057,12 @@ class DiffusionBackend:from .diffusion_nvfp4_install import record_install_reasonrecord_install_reason(self, *(_nvfp4_install_outcome or (True, None)), device)+ # Drop the previous load's NVFP4 cache tag; an NVFP4 load sets it again.+ try:+ from .diffusion_nvfp4_act_quant import reset_compile_cache_tag+ reset_compile_cache_tag()+ except Exception as exc: # noqa: BLE001 - keying only+ logger.debug("nvfp4 cache tag reset skipped: %r", exc)# Single-file kinds resolve a checkpoint path; the pipeline kind has none.single_file_path = (diff --git a/studio/backend/core/inference/diffusion_nvfp4_act_quant.py b/studio/backend/core/inference/diffusion_nvfp4_act_quant.pyindex bba89c48d41..d70497b20d1 100644--- a/studio/backend/core/inference/diffusion_nvfp4_act_quant.py+++ b/studio/backend/core/inference/diffusion_nvfp4_act_quant.py@@ -121,12 +121,15 @@ def describe() -> dict:_CACHE_TAG_PREFIX = "unsloth_nvfp4_act_quant="+_TAG_ON = "1"+_TAG_OFF = "0"def _set_compile_cache_tag(tag: str | None) -> None:"""Key torch's FX/AOTAutograd caches on the quantiser: the Dynamo graph calls ``to_nvfp4`` by name, so untagged,a graph cached with the patch on is replayed with it off (the kill switch then still runs the kernel) and the- reverse. ``None`` removes our tag; other tags (e.g. the fp8 dispatcher's) are kept."""+ reverse. ``None`` removes our tag; other tags are kept. NVFP4 loads always set ``1`` / ``0``: pre-tag caches are+ untagged and may hold the patched graph, so an untagged "off" could replay the kernel."""try:import torch.compiler.config as _ccexcept Exception: # noqa: BLE001 - torch without compiler config: no persistent compile cache to split@@ -334,10 +337,14 @@ def install_nvfp4_act_quant_patch(logger: Any = None) -> bool:"""Swap ``NVFP4Tensor.to_nvfp4`` for the one-pass kernel after an on-device bit-identity check. Idempotent."""global _ORIGINALif not fast_act_quant_enabled():- _STATE["reason"] = f"{FAST_ACT_QUANT_ENV}=0"+ with _LOCK:+ _restore_original_locked()+ _STATE["reason"] = f"{FAST_ACT_QUANT_ENV}=0"+ _set_compile_cache_tag(_TAG_OFF)return Falsewith _LOCK:if _STATE["installed"]:+ _set_compile_cache_tag(_TAG_ON)return bool(_STATE["verified"])try:import torch@@ -345,6 +352,7 @@ def install_nvfp4_act_quant_patch(logger: Any = None) -> bool:if not torch.cuda.is_available():_STATE["reason"] = "cuda unavailable"+ _set_compile_cache_tag(_TAG_OFF)return False_ORIGINAL = NVFP4Tensor.to_nvfp4ok, reason = verify()@@ -355,7 +363,7 @@ def install_nvfp4_act_quant_patch(logger: Any = None) -> bool:if ok:NVFP4Tensor.to_nvfp4 = staticmethod(_patched_to_nvfp4)_STATE["installed"] = True- _set_compile_cache_tag("1")+ _set_compile_cache_tag(_TAG_ON if ok else _TAG_OFF)if logger is not None:try:logger.info(@@ -366,11 +374,21 @@ def install_nvfp4_act_quant_patch(logger: Any = None) -> bool:return ok+def _restore_original_locked() -> None:+ if _STATE["installed"] and _ORIGINAL is not None:+ from torchao.prototype.mx_formats.nvfp4_tensor import NVFP4Tensor+ NVFP4Tensor.to_nvfp4 = staticmethod(_ORIGINAL)+ _STATE["installed"] = False+ _STATE["verified"] = None++def uninstall_nvfp4_act_quant_patch() -> None:with _LOCK:- if _STATE["installed"] and _ORIGINAL is not None:- from torchao.prototype.mx_formats.nvfp4_tensor import NVFP4Tensor- NVFP4Tensor.to_nvfp4 = staticmethod(_ORIGINAL)- _STATE["installed"] = False+ _restore_original_locked()+ _set_compile_cache_tag(None)+++def reset_compile_cache_tag() -> None:+ """Per load: a non-NVFP4 load keeps the untagged key instead of inheriting the last NVFP4 load's tag."""+ with _LOCK:_set_compile_cache_tag(None)- _STATE["verified"] = Nonediff --git a/studio/backend/tests/test_diffusion_nvfp4_act_quant.py b/studio/backend/tests/test_diffusion_nvfp4_act_quant.pyindex 77be37b647b..4959c1ea6de 100644--- a/studio/backend/tests/test_diffusion_nvfp4_act_quant.py+++ b/studio/backend/tests/test_diffusion_nvfp4_act_quant.py@@ -114,7 +114,7 @@ def test_install_tags_the_compile_cache_and_uninstall_clears_it(monkeypatch):assert cc.cache_key_tag == "other=1"-def test_failed_verification_leaves_the_cache_untagged(monkeypatch):+def test_failed_verification_tags_the_cache_off(monkeypatch):cc = pytest.importorskip("torch.compiler.config")if not isinstance(getattr(cc, "cache_key_tag", None), str):pytest.skip("torch without compiler cache_key_tag")@@ -129,7 +129,70 @@ def test_failed_verification_leaves_the_cache_untagged(monkeypatch):monkeypatch.setattr(aq, "_ORIGINAL", None)monkeypatch.delenv(aq.FAST_ACT_QUANT_ENV, raising = False)assert aq.install_nvfp4_act_quant_patch() is False- assert cc.cache_key_tag == ""+ assert cc.cache_key_tag == "unsloth_nvfp4_act_quant=0"+++def _isolated_tag_state(monkeypatch, tag = ""):+ cc = pytest.importorskip("torch.compiler.config")+ if not isinstance(getattr(cc, "cache_key_tag", None), str):+ pytest.skip("torch without compiler cache_key_tag")+ nvfp4 = pytest.importorskip("torchao.prototype.mx_formats.nvfp4_tensor")+ monkeypatch.setattr(nvfp4.NVFP4Tensor, "to_nvfp4", nvfp4.NVFP4Tensor.__dict__["to_nvfp4"])+ monkeypatch.setattr(cc, "cache_key_tag", tag)+ monkeypatch.setattr(torch.cuda, "is_available", lambda: True)+ monkeypatch.setattr(aq, "verify", lambda: (True, "stub"))+ monkeypatch.setattr(+ aq, "_STATE", {"installed": False, "verified": None, "reason": "", "fallback": 0}+ )+ monkeypatch.setattr(aq, "_ORIGINAL", None)+ monkeypatch.delenv(aq.FAST_ACT_QUANT_ENV, raising = False)+ return cc, nvfp4.NVFP4Tensor+++def test_kill_switch_key_differs_from_the_legacy_untagged_key(monkeypatch):+ # Caches from before the tag are untagged and may hold the patched graph: "off" must not land on that key.+ cc, _ = _isolated_tag_state(monkeypatch, "other=1")+ monkeypatch.setenv(aq.FAST_ACT_QUANT_ENV, "0")+ assert aq.install_nvfp4_act_quant_patch() is False+ assert cc.cache_key_tag == "other=1;unsloth_nvfp4_act_quant=0"+ monkeypatch.delenv(aq.FAST_ACT_QUANT_ENV)+ assert aq.install_nvfp4_act_quant_patch() is True+ assert cc.cache_key_tag == "other=1;unsloth_nvfp4_act_quant=1"+++def test_kill_switch_after_install_restores_torchao(monkeypatch):+ cc, NVFP4Tensor = _isolated_tag_state(monkeypatch)+ original = NVFP4Tensor.to_nvfp4+ assert aq.install_nvfp4_act_quant_patch() is True+ assert NVFP4Tensor.to_nvfp4 is not original+ monkeypatch.setenv(aq.FAST_ACT_QUANT_ENV, "0")+ assert aq.install_nvfp4_act_quant_patch() is False+ assert NVFP4Tensor.to_nvfp4 is original+ assert cc.cache_key_tag == "unsloth_nvfp4_act_quant=0"+++def test_per_load_reset_drops_the_tag_for_a_non_nvfp4_load(monkeypatch):+ cc, NVFP4Tensor = _isolated_tag_state(monkeypatch, "other=1")+ assert aq.install_nvfp4_act_quant_patch() is True+ aq.reset_compile_cache_tag()+ assert cc.cache_key_tag == "other=1"+ assert aq.install_nvfp4_act_quant_patch() is True+ assert cc.cache_key_tag == "other=1;unsloth_nvfp4_act_quant=1"+++def test_load_pipeline_resets_the_tag_after_unload():+ import ast+ import pathlib++ src = pathlib.Path(aq.__file__).with_name("diffusion.py").read_text()+ fn = next(+ n+ for n in ast.walk(ast.parse(src))+ if isinstance(n, ast.FunctionDef) and n.name == "load_pipeline"+ )+ body = ast.get_source_segment(src, fn)+ assert "reset_compile_cache_tag()" in body+ assert body.index("self._unload_locked()") < body.index("reset_compile_cache_tag()")_CROSS_PROCESS_PROBE = """