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: move torchao int8 weights back to the GPU after an oversized request streams pinned groups (#12617)

Daniel Hanb9df859e5332
diff --git a/studio/backend/core/inference/diffusion_memory.py b/studio/backend/core/inference/diffusion_memory.py
index 95f8e7ad9b1..0c739dedbb4 100644
--- a/studio/backend/core/inference/diffusion_memory.py
+++ b/studio/backend/core/inference/diffusion_memory.py
@@ -2397,6 +2397,18 @@ def refine_plan_from_loaded_weights(
return plan
+def _placed_on(tensor: Any, device_type: str, is_torchao: Callable[[Any], bool]) -> bool:
+ """torchao subclasses are judged by inner tensors: after a streamed offload the wrapper can report the wrong device."""
+ if is_torchao(tensor):
+ try:
+ names, _ = tensor.__tensor_flatten__()
+ inner = [getattr(tensor, n) for n in names]
+ return all(getattr(t, "device", tensor.device).type == device_type for t in inner)
+ except Exception: # noqa: BLE001 - unflattenable: move it, the swap is idempotent
+ return False
+ return tensor.device.type == device_type
+
+
def _keep_groups_resident(
module: Any,
room_mib: int,
@@ -2477,7 +2489,7 @@ def _keep_groups_resident(
continue
cpu = getattr(group, "cpu_param_dict", None) or {}
for t in tensors:
- if t.device.type == onload.type:
+ if _placed_on(t, onload.type, is_torchao):
continue
moved = cpu.get(t, t).to(onload)
if is_torchao(t):
diff --git a/studio/backend/tests/test_diffusion_measured_placement.py b/studio/backend/tests/test_diffusion_measured_placement.py
index 734c2b070e6..bfa5ffd9516 100644
--- a/studio/backend/tests/test_diffusion_measured_placement.py
+++ b/studio/backend/tests/test_diffusion_measured_placement.py
@@ -496,6 +496,69 @@ def test_generate_releases_and_restores_resident_groups():
assert "pipe._unsloth_measured_reserve = (" in src
+def test_torchao_groups_stay_on_device_after_release_and_restore(monkeypatch):
+ torch, _ = _cuda_offload_model()
+ pytest.importorskip("torchao")
+ from diffusers.hooks import apply_group_offloading
+ from torchao.quantization import Int8DynamicActivationInt8WeightConfig, quantize_
+
+ monkeypatch.delenv("UNSLOTH_DIFFUSION_PARTIAL_RESIDENT", raising = False)
+ cfg = Int8DynamicActivationInt8WeightConfig(set_inductor_config = False)
+ if not hasattr(cfg, "version"):
+ pytest.skip(
+ "torchao predates versioned configs; the v2 int8 layout this test pins is unavailable"
+ )
+ cfg.version = 2
+ torch.manual_seed(0)
+ net = (
+ torch.nn.Sequential(
+ torch.nn.Linear(256, 512),
+ torch.nn.Sequential(*[torch.nn.Linear(512, 512) for _ in range(3)]),
+ )
+ .cuda()
+ .to(torch.bfloat16)
+ )
+ quantize_(net[1], cfg)
+ x = torch.randn(64, 256, device = "cuda", dtype = torch.bfloat16)
+ with torch.no_grad():
+ ref = net(x)
+ net.to("cpu")
+ kwargs = dict(
+ onload_device = torch.device("cuda"),
+ offload_device = torch.device("cpu"),
+ offload_type = "block_level",
+ num_blocks_per_group = 1,
+ use_stream = True,
+ record_stream = True,
+ non_blocking = True,
+ )
+ apply_group_offloading(net, **dm._torchao_group_offload_kwargs(net, kwargs, [0]))
+ pipe = types.SimpleNamespace(transformer = net, components = {"transformer": net})
+ assert dm._keep_groups_resident(net, 1024, "cuda") > 0
+ with torch.no_grad():
+ assert torch.equal(net(x), ref)
+ restore = dm.release_resident_groups(pipe, 1024)
+ assert restore is not None
+ for _ in range(2):
+ assert torch.equal(net(x), ref)
+ restore()
+ for lin in net[1]:
+ # torchao 0.14 (torch <= 2.9) keeps the v1 layout, nesting its int8 data one subclass deeper
+ assert set(_inner_devices(lin.weight)) == {"cuda"}
+ assert torch.equal(net(x), ref)
+
+
+def _inner_devices(tensor):
+ names, _ = tensor.__tensor_flatten__()
+ out = []
+ for name in names:
+ inner = getattr(tensor, name)
+ out += (
+ _inner_devices(inner) if hasattr(inner, "__tensor_flatten__") else [inner.device.type]
+ )
+ return out
+
+
def test_eager_offload_hooks_install_is_idempotent():
go = pytest.importorskip("diffusers.hooks.group_offloading")
dm.install_group_offload_hooks_eager()