Skip to content

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.

Studio FLUX.3 manual cast: keep LoRA adapters at the fp32 compute dtype and out of the bf16 fold (#17201)

Daniel Han1185624523ea
diff --git a/studio/backend/core/inference/diffusion_lora_fuse.py b/studio/backend/core/inference/diffusion_lora_fuse.py
index 40689555a42..086e0a0c4ca 100644
--- a/studio/backend/core/inference/diffusion_lora_fuse.py
+++ b/studio/backend/core/inference/diffusion_lora_fuse.py
@@ -16,6 +16,8 @@ from __future__ import annotations
import os
from typing import Any, Optional
+from .diffusion_manual_cast import lora_compute_dtype
+
LORA_FUSE_ENV = "UNSLOTH_DIFFUSION_LORA_FUSE"
BACKUP_ENV = "UNSLOTH_DIFFUSION_LORA_FUSE_BACKUP"
HOST_GUARD_ENV = "UNSLOTH_DIFFUSION_LORA_FUSE_HOST_GUARD"
@@ -65,7 +67,10 @@ def _plan(denoisers: list) -> Optional[list]:
for a in active
):
return None # DoRA / LoRA bias change more than the weight
- weight = getattr(layer.get_base_layer(), "weight", None)
+ base = layer.get_base_layer()
+ if lora_compute_dtype(base) is not None:
+ return None # manual cast: folding into bf16 storage would round the fp32 update
+ weight = getattr(base, "weight", None)
if (
not isinstance(weight, torch.Tensor)
or type(weight.data) is not torch.Tensor # quantised / GGUF / torchao subclasses
diff --git a/studio/backend/core/inference/diffusion_manual_cast.py b/studio/backend/core/inference/diffusion_manual_cast.py
index a803d5ba937..5976292c62c 100644
--- a/studio/backend/core/inference/diffusion_manual_cast.py
+++ b/studio/backend/core/inference/diffusion_manual_cast.py
@@ -2,7 +2,7 @@
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
"""Linear / Embedding weights stay at stored half dtype and upcast exactly per call. UNSLOTH_STUDIO_MANUAL_CAST=0
-disables."""
+disables. LoRA adapters on them stay at compute dtype, unfused (UNSLOTH_STUDIO_MANUAL_CAST_LORA=0 disables)."""
from __future__ import annotations
@@ -11,6 +11,8 @@ from typing import Any, Optional
MANUAL_CAST_ENV = "UNSLOTH_STUDIO_MANUAL_CAST"
MANUAL_CAST_ATTR = "_unsloth_manual_cast"
+MANUAL_CAST_LORA_ENV = "UNSLOTH_STUDIO_MANUAL_CAST_LORA"
+_PEFT_PATCHED = "_unsloth_manual_cast_lora"
_CLASSES: dict[str, Any] = {}
@@ -19,6 +21,68 @@ def manual_cast_disabled() -> bool:
return (os.environ.get(MANUAL_CAST_ENV) or "").strip().lower() in ("0", "off", "false", "no")
+def manual_cast_lora_disabled() -> bool:
+ return (os.environ.get(MANUAL_CAST_LORA_ENV) or "").strip().lower() in (
+ "0",
+ "off",
+ "false",
+ "no",
+ )
+
+
+def lora_compute_dtype(base: Any) -> Any:
+ if not _CLASSES or type(base) not in (_CLASSES["linear"], _CLASSES["embedding"]):
+ return None
+ dtype = getattr(base, "_unsloth_compute_dtype", None)
+ weight = getattr(base, "weight", None)
+ if dtype is None or weight is None or weight.dtype == dtype or manual_cast_lora_disabled():
+ return None
+ return dtype
+
+
+def _patch_peft_adapter_dtype() -> None:
+ """PEFT casts adapters to the base weight dtype (bf16 GEMMs, rounded fp32 files); use compute dtype instead."""
+ try:
+ from peft.tuners.tuners_utils import BaseTunerLayer
+ except Exception: # noqa: BLE001 -- no PEFT, no adapters to place
+ return
+ original = BaseTunerLayer.__dict__.get("_move_adapter_to_device_of_base_layer")
+ if original is None or getattr(original, _PEFT_PATCHED, False):
+ return
+ import torch
+
+ def _move_adapter_to_device_of_base_layer(
+ self,
+ adapter_name,
+ device = None,
+ ):
+ base = self.get_base_layer()
+ dtype = lora_compute_dtype(base)
+ if dtype is None:
+ return original(self, adapter_name, device)
+ if device is None:
+ device = base.weight.device
+ meta = torch.device("meta")
+ for name in (*self.adapter_layer_names, *self.other_param_names):
+ layer = getattr(self, name, None)
+ if not hasattr(layer, "keys") or adapter_name not in layer.keys():
+ continue
+ item = layer[adapter_name]
+ if not isinstance(item, (torch.nn.Module, torch.Tensor)):
+ continue
+ tensors = item.parameters() if isinstance(item, torch.nn.Module) else (item,)
+ if any(t.device == meta for t in tensors):
+ continue
+ if isinstance(item, torch.nn.Module) or item.is_floating_point():
+ layer[adapter_name] = item.to(device, dtype = dtype)
+ else:
+ layer[adapter_name] = item.to(device)
+
+ setattr(_move_adapter_to_device_of_base_layer, _PEFT_PATCHED, True)
+ _move_adapter_to_device_of_base_layer.__wrapped__ = original
+ BaseTunerLayer._move_adapter_to_device_of_base_layer = _move_adapter_to_device_of_base_layer
+
+
def _classes() -> tuple[Any, Any]:
if not _CLASSES:
import torch
@@ -74,6 +138,7 @@ def apply_manual_cast_(module: Any, compute_dtype: Any) -> int:
import torch
linear_cls, embedding_cls = _classes()
+ _patch_peft_adapter_dtype()
half = (torch.bfloat16, torch.float16)
keep = _keep_fp32_patterns(module)
first_owner = _first_float_owner(module, keep)
diff --git a/studio/backend/tests/test_diffusion_manual_cast_lora.py b/studio/backend/tests/test_diffusion_manual_cast_lora.py
new file mode 100644
index 00000000000..c4610289699
--- /dev/null
+++ b/studio/backend/tests/test_diffusion_manual_cast_lora.py
@@ -0,0 +1,138 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""LoRA on a manual-cast (bf16 stored, fp32 compute) denoiser keeps fp32 adapters and is never fused."""
+
+from __future__ import annotations
+
+import copy
+import os
+import pathlib
+
+import pytest
+
+torch = pytest.importorskip("torch")
+pytest.importorskip("peft")
+
+from torch.utils._python_dispatch import TorchDispatchMode # noqa: E402
+
+from core.inference import diffusion_lora_fuse as lora_fuse # noqa: E402
+from core.inference import diffusion_manual_cast as mc # noqa: E402
+
+LORA_ENV = "UNSLOTH_STUDIO_MANUAL_CAST_LORA"
+TARGET = "1"
+
+
+def test_imports_this_tree():
+ here = pathlib.Path(__file__).resolve().parents[1]
+ assert pathlib.Path(mc.__file__).resolve().is_relative_to(here)
+
+
+class _Net(torch.nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.layers = torch.nn.ModuleList([torch.nn.Linear(32, 32) for _ in range(3)])
+
+ def forward(self, x):
+ for layer in self.layers:
+ x = layer(x)
+ return x
+
+
+def _models():
+ torch.manual_seed(0)
+ ref = _Net().eval()
+ with torch.no_grad():
+ for p in ref.parameters():
+ p.data = p.data.to(torch.bfloat16).float()
+ head = copy.deepcopy(ref).to(torch.bfloat16)
+ mc.apply_manual_cast_(head, torch.float32)
+ assert type(head.layers[1]) is not torch.nn.Linear # swapped for the manual-cast twin
+ return ref, head
+
+
+def _lora_sd():
+ g = torch.Generator().manual_seed(1)
+ a = torch.randn(4, 32, generator = g) * 0.1
+ b = torch.randn(32, 4, generator = g) * 0.1
+ return a, b
+
+
+def _inject(model, low_cpu_mem_usage):
+ from peft import LoraConfig, inject_adapter_in_model, set_peft_model_state_dict
+
+ a, b = _lora_sd()
+ cfg = LoraConfig(r = 4, lora_alpha = 4, target_modules = [f"layers.{TARGET}"])
+ kwargs = {"low_cpu_mem_usage": True} if low_cpu_mem_usage else {}
+ inject_adapter_in_model(cfg, model, adapter_name = "px", **kwargs)
+ sd = {
+ f"layers.{TARGET}.lora_A.weight": a.clone(),
+ f"layers.{TARGET}.lora_B.weight": b.clone(),
+ }
+ set_peft_model_state_dict(model, sd, adapter_name = "px", **kwargs)
+ return model.layers[int(TARGET)], a, b
+
+
+class _MatmulDtypes(TorchDispatchMode):
+ def __init__(self):
+ super().__init__()
+ self.dtypes = []
+
+ def __torch_dispatch__(
+ self,
+ func,
+ types,
+ args = (),
+ kwargs = None,
+ ):
+ if func in (torch.ops.aten.mm.default, torch.ops.aten.addmm.default):
+ self.dtypes.append({a.dtype for a in args if isinstance(a, torch.Tensor)})
+ return func(*args, **(kwargs or {}))
+
+
[email protected]("low_cpu_mem_usage", [False, True])
+def test_adapter_keeps_fp32_values_and_gemms(monkeypatch, low_cpu_mem_usage):
+ monkeypatch.delenv(LORA_ENV, raising = False)
+ ref, head = _models()
+ ref_layer, _, _ = _inject(ref, low_cpu_mem_usage)
+ layer, a, b = _inject(head, low_cpu_mem_usage)
+ assert layer.base_layer.weight.dtype == torch.bfloat16
+ assert layer.lora_A["px"].weight.dtype == torch.float32
+ assert layer.lora_B["px"].weight.dtype == torch.float32
+ assert torch.equal(layer.lora_A["px"].weight.detach(), a)
+ assert torch.equal(layer.lora_B["px"].weight.detach(), b)
+ x = torch.randn(2, 5, 32, generator = torch.Generator().manual_seed(2))
+ cap = _MatmulDtypes()
+ with torch.no_grad(), cap:
+ out = head(x)
+ assert cap.dtypes and all(d == {torch.float32} for d in cap.dtypes), cap.dtypes
+ with torch.no_grad():
+ want = ref(x)
+ assert out.dtype == torch.float32
+ torch.testing.assert_close(out, want, atol = 1e-6, rtol = 1e-6)
+ assert ref_layer.lora_A["px"].weight.dtype == torch.float32
+
+
+def test_kill_switch_restores_stored_dtype_adapters(monkeypatch):
+ monkeypatch.setenv(LORA_ENV, "0")
+ _ref, head = _models()
+ layer, _a, _b = _inject(head, False)
+ assert layer.lora_A["px"].weight.dtype == torch.bfloat16
+
+
+def test_plain_bf16_model_unchanged(monkeypatch):
+ monkeypatch.delenv(LORA_ENV, raising = False)
+ _models() # installs the PEFT placement hook
+ torch.manual_seed(0)
+ plain = _Net().to(torch.bfloat16)
+ layer, _a, _b = _inject(plain, False)
+ assert layer.lora_A["px"].weight.dtype == torch.bfloat16
+
+
+def test_fuse_declines_manual_cast_layers(monkeypatch):
+ monkeypatch.delenv(LORA_ENV, raising = False)
+ _ref, head = _models()
+ _inject(head, False)
+ assert lora_fuse._plan([head]) is None
+ monkeypatch.setenv(LORA_ENV, "0")
+ assert lora_fuse._plan([head]) is not None