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 text encoders: keep the fp8 storage across a layerwise-cast forward instead of re-casting it (#17103)

Daniel Han14f6b6d570b6
diff --git a/studio/backend/core/inference/diffusion_precision.py b/studio/backend/core/inference/diffusion_precision.py
index f4355d6712d..0ed81d9bec1 100644
--- a/studio/backend/core/inference/diffusion_precision.py
+++ b/studio/backend/core/inference/diffusion_precision.py
@@ -701,6 +701,7 @@ def _cast_fp8(encoder: Any, target: Any) -> None:
# Keep nn.Embedding full precision: fp8 puts every prompt token on the coarse grid.
skip_modules_classes = (torch.nn.Embedding,),
)
+ _install_storage_restore(encoder)
# Module.dtype would report fp8 storage, which randn_tensor cannot take; shadow it on the ORIGINAL class, since a __class__ swap breaks output recording.
compute_dtype = getattr(target, "dtype", None)
@@ -714,6 +715,148 @@ def _cast_fp8(encoder: Any, target: Any) -> None:
pass
+TE_FP8_RESTORE_ENV = "UNSLOTH_TE_FP8_RESTORE_STORAGE"
+
+
+def te_fp8_restore_enabled() -> bool:
+ import os
+ return (os.environ.get(TE_FP8_RESTORE_ENV) or "").strip().lower() not in (
+ "0",
+ "off",
+ "false",
+ "no",
+ )
+
+
+def _floating_slots(module: Any) -> list:
+ out = []
+ for sub in module.modules():
+ for table in (sub._parameters, sub._buffers):
+ for name, value in table.items():
+ if value is not None and value.is_floating_point():
+ out.append((table, name, value))
+ return out
+
+
+def _is_compiling() -> bool:
+ import torch
+
+ compiler = getattr(torch, "compiler", None)
+ fn = getattr(compiler, "is_compiling", None) or getattr(torch._dynamo, "is_compiling", None)
+ return bool(fn()) if callable(fn) else False
+
+
+def _slot_version(value: Any) -> Any:
+ try:
+ return value._version
+ except Exception: # noqa: BLE001
+ return None
+
+
+def _restoring_hooks(hook: Any, stock_pre: Any, stock_post: Any) -> tuple:
+ """Put the kept fp8 tensors back after the forward instead of downcasting the compute copies (exact: every fp8
+ value is representable in bf16 / fp16 / fp32). A slot replaced or written in place during the forward takes the
+ stock downcast, and so does any traced forward: pointers and version counters are eager-only."""
+ import torch
+
+ kept: dict = {}
+
+ # Traced forwards run diffusers' stock body inline: calling ``stock_pre`` would add a frame, so a graph break.
+ def pre_forward(module: Any, *args: Any, **kwargs: Any) -> Any:
+ if _is_compiling():
+ module.to(dtype = hook.compute_dtype, non_blocking = hook.non_blocking)
+ return args, kwargs
+ if not te_fp8_restore_enabled() or module.training:
+ kept.pop(id(module), None)
+ return stock_pre(module, *args, **kwargs)
+ # ``module.to`` swaps a parameter's ``.data`` but replaces a buffer entry
+ stored = [
+ (table, name, value.data if isinstance(value, torch.nn.Parameter) else value)
+ for table, name, value in _floating_slots(module)
+ if value.dtype == hook.storage_dtype
+ ]
+ # Outside inference_mode so the compute copies keep a version counter for the in-place check.
+ with torch.inference_mode(False), torch.no_grad():
+ result = stock_pre(module, *args, **kwargs)
+ entries = []
+ for table, name, old in stored:
+ new = table.get(name)
+ if new is None:
+ continue
+ entries.append((table, name, old, new.data_ptr(), new.dtype, _slot_version(new)))
+ kept[id(module)] = entries
+ return result
+
+ def post_forward(module: Any, output: Any) -> Any:
+ if _is_compiling():
+ module.to(dtype = hook.storage_dtype, non_blocking = hook.non_blocking)
+ return output
+ entries = kept.pop(id(module), None)
+ if not entries or not te_fp8_restore_enabled():
+ return stock_post(module, output)
+ for table, name, old, ptr, dtype, version in entries:
+ current = table.get(name)
+ if (
+ current is None
+ or version is None
+ or current.data_ptr() != ptr
+ or current.dtype != dtype
+ or _slot_version(current) != version
+ ):
+ return stock_post(module, output)
+ for table, name, old, *_ in entries:
+ current = table[name]
+ if isinstance(current, torch.nn.Parameter):
+ current.data = old
+ else:
+ table[name] = old
+ if any(v.dtype == hook.compute_dtype for _t, _n, v in _floating_slots(module)):
+ return stock_post(module, output)
+ return output
+
+ return pre_forward, post_forward
+
+
+def _install_storage_restore(encoder: Any) -> int:
+ """Idempotent; returns the number of hooks changed."""
+ if not te_fp8_restore_enabled():
+ return 0
+ try:
+ from diffusers.hooks.layerwise_casting import LayerwiseCastingHook
+ except Exception: # noqa: BLE001 - diffusers without layerwise casting: nothing to change
+ return 0
+ import torch
+
+ # The traced path inlines these bodies; any other diffusers hook body keeps the stock hooks.
+ if LayerwiseCastingHook.pre_forward.__code__.co_names != (
+ "to",
+ "compute_dtype",
+ "non_blocking",
+ ) or LayerwiseCastingHook.post_forward.__code__.co_names != (
+ "to",
+ "storage_dtype",
+ "non_blocking",
+ ):
+ return 0
+ changed = 0
+ for module in encoder.modules():
+ registry = getattr(module, "_diffusers_hook", None)
+ for ref in getattr(registry, "_fn_refs", None) or ():
+ hook = getattr(getattr(ref, "pre_forward", None), "__self__", None)
+ if (
+ type(hook) is not LayerwiseCastingHook
+ or getattr(ref, "_unsloth_fp8_restore", False)
+ or hook.storage_dtype not in (torch.float8_e4m3fn, torch.float8_e5m2)
+ ):
+ continue
+ ref.pre_forward, ref.post_forward = _restoring_hooks(
+ hook, ref.pre_forward, ref.post_forward
+ )
+ ref._unsloth_fp8_restore = True
+ changed += 1
+ return changed
+
+
def _install_dtype_override(cls: type) -> None:
"""Shadow ``cls.dtype`` with a property preferring the per-instance compute-dtype
override ``_cast_fp8`` sets; instances without it keep the original behaviour. Class
diff --git a/studio/backend/tests/test_diffusion_te_fp8_restore.py b/studio/backend/tests/test_diffusion_te_fp8_restore.py
new file mode 100644
index 00000000000..51cb3d7bf09
--- /dev/null
+++ b/studio/backend/tests/test_diffusion_te_fp8_restore.py
@@ -0,0 +1,205 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Layerwise fp8 encoders keep their fp8 storage across a forward; outputs and bytes match diffusers' round trip."""
+
+from __future__ import annotations
+
+import types
+
+import pytest
+
+from core.inference import diffusion_precision as prec
+
+torch = pytest.importorskip("torch")
+pytest.importorskip("diffusers.hooks.layerwise_casting")
+
+
[email protected](autouse = True)
+def _env(monkeypatch):
+ monkeypatch.delenv(prec.TE_FP8_RESTORE_ENV, raising = False)
+
+
+class _Block(torch.nn.Module):
+ def __init__(self, width):
+ super().__init__()
+ self.up = torch.nn.Linear(width, 4 * width)
+ self.down = torch.nn.Linear(4 * width, width, bias = False)
+ self.register_buffer("scale", torch.full((width,), 0.5))
+
+ def forward(self, x):
+ return x + self.down(torch.nn.functional.gelu(self.up(x))) * self.scale
+
+
+class _Encoder(torch.nn.Module):
+ def __init__(
+ self,
+ width = 64,
+ depth = 3,
+ ):
+ super().__init__()
+ self.embed = torch.nn.Embedding(50, width)
+ self.blocks = torch.nn.ModuleList(_Block(width) for _ in range(depth))
+ self.norm = torch.nn.LayerNorm(width)
+
+ def forward(self, ids):
+ x = self.embed(ids)
+ for b in self.blocks:
+ x = b(x)
+ return self.norm(x)
+
+
+def _encoder(seed = 0):
+ torch.manual_seed(seed)
+ enc = _Encoder().to(torch.bfloat16).eval()
+ prec._cast_fp8(enc, types.SimpleNamespace(dtype = torch.bfloat16))
+ return enc
+
+
+def _fp8_casts(fn):
+ from torch.utils._python_dispatch import TorchDispatchMode
+
+ seen = []
+
+ class _Count(TorchDispatchMode):
+ def __torch_dispatch__(
+ self,
+ func,
+ types_,
+ args = (),
+ kwargs = None,
+ ):
+ kwargs = kwargs or {}
+ name = str(func)
+ if (name.startswith("aten.to.") or name.startswith("aten._to_copy")) and (
+ torch.float8_e4m3fn in args or kwargs.get("dtype") == torch.float8_e4m3fn
+ ):
+ seen.append(1)
+ return func(*args, **kwargs)
+
+ with _Count():
+ out = fn()
+ return out, len(seen)
+
+
+def _storage(enc):
+ return {
+ n: (p.data_ptr(), p.dtype, p.view(torch.uint8).clone()) for n, p in enc.named_parameters()
+ }
+
+
+def test_forward_keeps_the_fp8_tensors_and_matches_the_round_trip(monkeypatch):
+ ids = torch.randint(0, 50, (2, 7), generator = torch.Generator().manual_seed(1))
+ monkeypatch.setenv(prec.TE_FP8_RESTORE_ENV, "0")
+ stock = _encoder()
+ assert prec._install_storage_restore(stock) == 0
+ with torch.inference_mode():
+ ref, ref_casts = _fp8_casts(lambda: [stock(ids), stock(ids)])
+ monkeypatch.delenv(prec.TE_FP8_RESTORE_ENV)
+ enc = _encoder()
+ before = _storage(enc)
+ assert any(dtype == torch.float8_e4m3fn for _, dtype, _ in before.values())
+ with torch.inference_mode():
+ got, casts = _fp8_casts(lambda: [enc(ids), enc(ids)])
+ after = _storage(enc)
+ for a, b in zip(ref, got):
+ assert torch.equal(a, b)
+ assert ref_casts > 0 and casts == 0 # no downcast after any forward
+ for name, (ptr, dtype, raw) in before.items():
+ assert (
+ after[name][0] == ptr and after[name][1] == dtype and torch.equal(after[name][2], raw)
+ )
+ stock_after = _storage(stock)
+ for name in before:
+ assert torch.equal(stock_after[name][2], after[name][2])
+
+
+def test_install_is_idempotent_and_counts_each_hook():
+ enc = _encoder()
+ assert prec._install_storage_restore(enc) == 0 # _cast_fp8 already installed it
+ hooked = [
+ ref
+ for m in enc.modules()
+ for ref in getattr(getattr(m, "_diffusers_hook", None), "_fn_refs", None) or ()
+ if getattr(ref, "_unsloth_fp8_restore", False)
+ ]
+ assert len(hooked) == 3 * 2 # up and down per block; Embedding and LayerNorm are skipped
+
+
+def test_a_slot_replaced_during_the_forward_takes_the_stock_downcast():
+ enc = _encoder()
+ lin = enc.blocks[0].up
+ ref = lin._diffusers_hook._fn_refs[-1]
+ below = ref.forward
+
+ def swap(*a, **k):
+ out = below(*a, **k)
+ lin.weight.data = lin.weight.data.clone() # something else replaced the compute copy
+ return out
+
+ ref.forward = swap
+ stored = lin.weight.data_ptr()
+ with torch.inference_mode():
+ _, casts = _fp8_casts(lambda: enc(torch.randint(0, 50, (1, 5))))
+ assert lin.weight.dtype == torch.float8_e4m3fn and lin.weight.data_ptr() != stored
+ assert casts > 0
+
+
+def test_switch_off_at_runtime_uses_the_stock_cast(monkeypatch):
+ enc = _encoder()
+ ids = torch.randint(0, 50, (1, 5))
+ monkeypatch.setenv(prec.TE_FP8_RESTORE_ENV, "0")
+ with torch.inference_mode():
+ _, casts = _fp8_casts(lambda: enc(ids))
+ assert casts > 0
+ assert all(p.dtype == torch.float8_e4m3fn for n, p in enc.named_parameters() if "blocks" in n)
+
+
[email protected]("mode", ["inference", "no_grad"])
+def test_an_in_place_write_during_the_forward_is_kept(mode):
+ enc = _encoder()
+ lin = enc.blocks[0].up
+ ref = lin._diffusers_hook._fn_refs[-1]
+ below = ref.forward
+
+ def write(*a, **k):
+ lin.weight.add_(1.0)
+ return below(*a, **k)
+
+ ref.forward = write
+ before = lin.weight.float().clone()
+ ctx = torch.inference_mode() if mode == "inference" else torch.no_grad()
+ with ctx:
+ enc(torch.randint(0, 50, (1, 5)))
+ assert lin.weight.dtype == torch.float8_e4m3fn
+ assert float((lin.weight.float() - before).abs().max()) >= 0.5
+
+
+def _compiled_breaks(enc, xs):
+ torch._dynamo.reset()
+ torch._dynamo.utils.counters.clear()
+ compiled = torch.compile(enc, backend = "eager", dynamic = True)
+ with torch.no_grad():
+ outs = [compiled(x) for x in xs]
+ return outs, sum(torch._dynamo.utils.counters["graph_break"].values())
+
+
+def test_a_dynamic_compiled_encoder_traces_like_the_stock_hooks(monkeypatch):
+ pytest.importorskip("torch._dynamo")
+ xs = [
+ torch.randint(0, 50, (n, 5), generator = torch.Generator().manual_seed(n))
+ for n in (3, 5, 7, 3)
+ ]
+ monkeypatch.setenv(prec.TE_FP8_RESTORE_ENV, "0")
+ stock = _encoder()
+ ref, stock_breaks = _compiled_breaks(stock, xs)
+ monkeypatch.delenv(prec.TE_FP8_RESTORE_ENV)
+ enc = _encoder()
+ try:
+ got, breaks = _compiled_breaks(enc, xs)
+ finally:
+ torch._dynamo.reset()
+ for a, b in zip(ref, got):
+ assert torch.equal(a, b)
+ assert breaks == stock_breaks
+ assert all(p.dtype == torch.float8_e4m3fn for n, p in enc.named_parameters() if "blocks" in n)