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 diffusion: store chunked int8 W8A8 results straight into the output rows (#15533)

Daniel Han5541b47a5f60
diff --git a/studio/backend/core/inference/diffusion_native_quant.py b/studio/backend/core/inference/diffusion_native_quant.py
index ced05c97b04..4e5f4b436bd 100644
--- a/studio/backend/core/inference/diffusion_native_quant.py
+++ b/studio/backend/core/inference/diffusion_native_quant.py
@@ -279,6 +279,13 @@ def _w8a8_rows(x2: Any, rot_h: Any, weight_q: Any, weight_scale: Any, bias: Any)
return out.to(x2.dtype)
+def _w8a8_rows_into(
+ x2: Any, rot_h: Any, weight_q: Any, weight_scale: Any, bias: Any, out: Any
+) -> None:
+ """``_w8a8_rows`` stored straight into ``out`` (a row slice of the chunked output), no temporary chunk result."""
+ out.copy_(_w8a8_rows(x2, rot_h, weight_q, weight_scale, bias))
+
+
_FUSED_STATE: dict = {"fn": None, "failed": None}
@@ -303,7 +310,12 @@ def _fused_w8a8() -> Optional[Callable[..., Any]]:
return None
# Registered in eager, before any trace reads the handle.
_FUSED_STATE["row_major"] = _row_major_op()
+ # Every key exists before the first trace: older dynamo guards on len(_FUSED_STATE), so adding
+ # "calls" after the first call would recompile each compiled function once.
+ _FUSED_STATE.setdefault("calls", 0)
fn = torch.compile(_w8a8_rows, dynamic = True, fullgraph = True)
+ # One graph for every slice offset and chunk height (dynamic storage offset), written in place by inductor.
+ _FUSED_STATE["into"] = torch.compile(_w8a8_rows_into, dynamic = True, fullgraph = True)
_FUSED_STATE["fn"] = fn
return fn
@@ -313,6 +325,7 @@ def _fused_w8a8_failed(exc: BaseException) -> None:
_FUSED_STATE["failed"] = repr(exc)
_FUSED_STATE["fn"] = None
+ _FUSED_STATE["into"] = None
logging.getLogger(__name__).warning(
"diffusion.native_quant: the compiled int8 W8A8 linear failed (%s); eager kernels from here on "
"(set %s=0 to skip it)",
@@ -321,6 +334,14 @@ def _fused_w8a8_failed(exc: BaseException) -> None:
)
+def _autocast_on(x: Any) -> bool:
+ import torch
+ try:
+ return bool(torch.is_autocast_enabled(x.device.type))
+ except TypeError: # torch without the device_type argument: treat any autocast as on
+ return bool(torch.is_autocast_enabled() or torch.is_autocast_cpu_enabled())
+
+
def fused_w8a8_state() -> dict:
return {"calls": _FUSED_STATE.get("calls", 0), "failed": _FUSED_STATE["failed"]}
@@ -522,16 +543,31 @@ def native_linear_class():
if rows <= chunk or chunk < 2 * _INT_MM_MIN_ROWS:
out = fn(x2, rot_h, self.weight_q, self.weight_scale, bias)
else:
- # Allocated from the first chunk to keep the compiled dtype (autocast can differ from x2's).
- out = None
+ # Only the rotation matmul can change the dtype (autocast); without it the output is x2's dtype.
+ into = _FUSED_STATE.get("into")
+ if into is not None and (rot_h is None or not _autocast_on(x2)):
+ out = x2.new_empty(rows, self.out_features)
+ else:
+ into = out = None
start = 0
for part in torch.tensor_split(x2, -(-rows // chunk)):
- got = fn(part.detach(), rot_h, self.weight_q, self.weight_scale, bias)
- if out is None:
- out = got.new_empty(rows, self.out_features)
stop = start + part.shape[0]
- out[start:stop].copy_(got)
- del got
+ if into is not None:
+ into(
+ part.detach(),
+ rot_h,
+ self.weight_q,
+ self.weight_scale,
+ bias,
+ out[start:stop],
+ )
+ else:
+ got = fn(part.detach(), rot_h, self.weight_q, self.weight_scale, bias)
+ if out is None:
+ # Allocated from the first chunk to keep the compiled dtype (autocast can differ).
+ out = got.new_empty(rows, self.out_features)
+ out[start:stop].copy_(got)
+ del got
start = stop
except torch.cuda.OutOfMemoryError:
raise
diff --git a/studio/backend/tests/test_diffusion_native_quant_fused.py b/studio/backend/tests/test_diffusion_native_quant_fused.py
index 84621b4447e..a9b6baf85ca 100644
--- a/studio/backend/tests/test_diffusion_native_quant_fused.py
+++ b/studio/backend/tests/test_diffusion_native_quant_fused.py
@@ -268,3 +268,80 @@ def test_chunked_output_keeps_the_compiled_dtype(monkeypatch):
got = layer._forward_fused(x)
assert got.dtype == torch.float16
assert torch.equal(got, (x[:, :128] * 2).to(torch.float16))
+
+
+def test_chunks_are_stored_once_into_their_output_rows(monkeypatch):
+ # Each chunk is written in place into its rows of the one output: no chunk result, no second copy.
+ layer = _layer()
+ monkeypatch.setattr(nq, "_INT_MM_FUSED_CHUNK_ELEMS", 512 * 40)
+ writes = []
+
+ def into(x2, rot_h, wq, ws, bias, out):
+ writes.append((out.data_ptr(), out.shape[0], out.untyped_storage().data_ptr()))
+ out.copy_(x2[:, :128] * 2)
+
+ def fn(*_a):
+ raise AssertionError("the chunked path must not build a chunk result")
+
+ nq._FUSED_STATE.update(fn = fn, into = into)
+ x = torch.randn(100, 512, dtype = torch.bfloat16)
+ got = layer._forward_fused(x)
+ assert torch.equal(got, x[:, :128] * 2)
+ base = got.untyped_storage().data_ptr()
+ assert [w[2] for w in writes] == [base] * len(writes) and len(writes) == 3
+ step = got.element_size() * 128
+ assert [w[0] for w in writes] == [got.data_ptr() + step * r for r in (0, 34, 67)]
+ assert sum(w[1] for w in writes) == 100
+
+
+def test_rotation_under_autocast_keeps_the_returning_path(monkeypatch):
+ layer = _layer()
+ monkeypatch.setattr(nq, "_INT_MM_FUSED_CHUNK_ELEMS", 512 * 40)
+
+ def into(*_a):
+ raise AssertionError(
+ "autocast may change the rotated dtype; the output dtype must come from a chunk"
+ )
+
+ nq._FUSED_STATE.update(fn = lambda x2, *_a: (x2[:, :128] * 2).to(torch.float16), into = into)
+ x = torch.randn(100, 512, dtype = torch.float32)
+ with torch.autocast("cpu", dtype = torch.bfloat16):
+ got = layer._forward_fused(x)
+ assert got.dtype == torch.float16
+ assert torch.equal(got, (x[:, :128] * 2).to(torch.float16))
+
+
[email protected](not _int_mm_on_cpu(), reason = "torch._int_mm unavailable on CPU")
[email protected]("rot", [0, 256])
+def test_compiled_into_slice_is_one_graph_and_bit_identical(monkeypatch, rot):
+ from torch._dynamo.testing import CompileCounterWithBackend
+
+ torch._dynamo.reset()
+ counters = torch._dynamo.utils.counters
+ counters.clear()
+ layer = _layer(rot = rot)
+ cnt = CompileCounterWithBackend("aot_eager")
+ nq._FUSED_STATE["row_major"] = nq._row_major_op()
+ fn = torch.compile(nq._w8a8_rows, dynamic = True, fullgraph = True, backend = "aot_eager")
+ into = torch.compile(nq._w8a8_rows_into, dynamic = True, fullgraph = True, backend = cnt)
+ nq._FUSED_STATE.update(fn = fn, into = into, calls = 0) # as _fused_w8a8 leaves it
+ monkeypatch.setattr(nq, "_INT_MM_FUSED_CHUNK_ELEMS", 512 * 40)
+ with torch.no_grad():
+ for rows in (100, 130, 77):
+ x = torch.randn(rows, 512, dtype = torch.bfloat16)
+ rot_h = layer.rot_h if layer.rot_group else None
+ ref = nq._w8a8_rows(x, rot_h, layer.weight_q, layer.weight_scale, layer.bias.detach())
+ assert torch.equal(layer._forward_fused(x), ref)
+ # Every slice offset and chunk height reuses one graph: no recompile, no graph break.
+ assert cnt.frame_count == 1
+ assert not counters["graph_break"]
+ torch._dynamo.reset()
+
+
+def test_factory_creates_every_state_key_before_the_first_trace(monkeypatch):
+ # torch <= 2.6 dynamo guards on len(_FUSED_STATE): a key added after the first call recompiles.
+ import core.inference.diffusion_speed as sp
+
+ monkeypatch.setattr(sp, "torch_compile_runtime_available", lambda: True)
+ assert nq._fused_w8a8() is not None
+ assert {"fn", "into", "row_major", "calls", "failed"} <= set(nq._FUSED_STATE)