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 image postprocess: convert to uint8 in row strips with one float32 copy each (#17091)

Daniel Hana7ff18127a98
diff --git a/studio/backend/core/inference/diffusion_postprocess.py b/studio/backend/core/inference/diffusion_postprocess.py
index a8c7be26abb..79ab3e83533 100644
--- a/studio/backend/core/inference/diffusion_postprocess.py
+++ b/studio/backend/core/inference/diffusion_postprocess.py
@@ -10,6 +10,8 @@ import os
from typing import Any, Optional
DEVICE_POSTPROCESS_ENV = "UNSLOTH_DIFFUSION_DEVICE_POSTPROCESS"
+STRIP_UINT8_ENV = "UNSLOTH_DIFFUSION_UINT8_STRIPS"
+_STRIP_BYTES = 32 << 20
_MARK = "_unsloth_device_postprocess"
NAN_IMAGE_MESSAGE = (
"The decoded image contains NaN values and would be saved as a blank image. The model or VAE overflowed at this "
@@ -77,10 +79,25 @@ def has_nan(image: Any) -> bool:
)
+def _strips_disabled() -> bool:
+ return (os.environ.get(STRIP_UINT8_ENV) or "").strip().lower() in ("0", "off", "false", "no")
+
+
def uint8_hwc(image: Any) -> Any:
"""Values must lie in [0, 1]: the uint8 cast of anything else is undefined."""
import torch
- return (image.float() * 255).round().to(torch.uint8).permute(0, 2, 3, 1).contiguous()
+
+ if _strips_disabled() or image.ndim != 4:
+ return (image.float() * 255).round().to(torch.uint8).permute(0, 2, 3, 1).contiguous()
+ batch, channels, height, width = image.shape
+ out = torch.empty((batch, height, width, channels), dtype = torch.uint8, device = image.device)
+ rows = max(1, _STRIP_BYTES // max(1, batch * channels * width * 4))
+ for start in range(0, height, rows):
+ piece = image[:, :, start : start + rows].to(torch.float32, copy = True)
+ piece.mul_(255).round_()
+ out[:, start : start + rows].copy_(piece.permute(0, 2, 3, 1))
+ del piece
+ return out
def install(pipe: Any, logger: Any = None) -> bool:
diff --git a/studio/backend/tests/test_diffusion_postprocess.py b/studio/backend/tests/test_diffusion_postprocess.py
index 3489b533261..7f9014f9816 100644
--- a/studio/backend/tests/test_diffusion_postprocess.py
+++ b/studio/backend/tests/test_diffusion_postprocess.py
@@ -30,6 +30,7 @@ class _Pipe:
@pytest.fixture(autouse = True)
def _env(monkeypatch):
monkeypatch.delenv(dp.DEVICE_POSTPROCESS_ENV, raising = False)
+ monkeypatch.delenv(dp.STRIP_UINT8_ENV, raising = False)
def _decoded(
@@ -74,6 +75,90 @@ def test_uint8_conversion_matches_numpy_bit_for_bit(dtype, channels_last, channe
assert np.array_equal(ours, stock)
+def _whole_batch(image):
+ return (image.float() * 255).round().to(torch.uint8).permute(0, 2, 3, 1).contiguous()
+
+
[email protected]("dtype", ["float32", "bfloat16", "float16"])
[email protected]("channels_last", [False, True])
[email protected]("strip_bytes", [1, 4096, 1 << 30])
+def test_strips_match_the_whole_batch_expression(dtype, channels_last, strip_bytes, monkeypatch):
+ """Every representable half value in [0, 1] (the rounding ties included), strips of one row, a few rows, all."""
+ monkeypatch.setattr(dp, "_STRIP_BYTES", strip_bytes)
+ if dtype == "float32":
+ image = _decoded(torch.float32, batch = 2, size = 37, channels = 4).mul(0.5).add(0.5).clamp(0, 1)
+ else:
+ bits = (
+ torch.arange(0, 1 << 16, dtype = torch.int32).to(torch.int16).view(getattr(torch, dtype))
+ )
+ values = bits[(bits >= 0) & (bits <= 1)]
+ count = 2 * 4 * 64 * 64
+ image = values.repeat(-(-count // values.numel()))[:count].reshape(2, 4, 64, 64)
+ if channels_last:
+ image = image.contiguous(memory_format = torch.channels_last)
+ ours = dp.uint8_hwc(image)
+ assert ours.is_contiguous() and ours.dtype == torch.uint8
+ assert torch.equal(ours, _whole_batch(image))
+ assert torch.equal(
+ dp.uint8_hwc(image[:, :3, 5:29]), _whole_batch(image[:, :3, 5:29])
+ ) # a non-contiguous view
+
+
+def test_strips_keep_one_float_strip_alive(monkeypatch):
+ import weakref
+
+ import torch.utils._pytree as pytree
+ from torch.utils._python_dispatch import TorchDispatchMode
+
+ size, refs, peak = {}, {}, [0]
+
+ def drop(key):
+ refs[key] -= 1
+ if not refs[key]:
+ del refs[key], size[key]
+
+ class _Live(TorchDispatchMode):
+ def __torch_dispatch__(
+ self,
+ func,
+ types,
+ args = (),
+ kwargs = None,
+ ):
+ known = {
+ t.untyped_storage().data_ptr()
+ for t in pytree.tree_leaves((args, kwargs))
+ if hasattr(t, "untyped_storage")
+ }
+ out = func(*args, **(kwargs or {}))
+ for t in pytree.tree_leaves(out):
+ if hasattr(t, "untyped_storage"):
+ key = t.untyped_storage().data_ptr()
+ if not key or (key in known and key not in size):
+ continue
+ if key not in size:
+ size[key], refs[key] = t.untyped_storage().nbytes(), 0
+ refs[key] += 1
+ weakref.finalize(t, drop, key)
+ peak[0] = max(peak[0], sum(size.values()))
+ return out
+
+ image = torch.rand(1, 4, 512, 512, dtype = torch.bfloat16)
+ plane = image.numel() * 4
+ monkeypatch.setattr(dp, "_STRIP_BYTES", plane // 8)
+ peaks = {}
+ for flag in ("0", "1"):
+ monkeypatch.setenv(dp.STRIP_UINT8_ENV, flag)
+ peak[0] = 0
+ with _Live():
+ out = dp.uint8_hwc(image)
+ peaks[flag] = peak[0]
+ assert torch.equal(out, _whole_batch(image))
+ del out
+ assert peaks["0"] >= 2 * plane
+ assert peaks["1"] <= image.numel() + plane // 8 + 4096
+
+
@needs_cuda
@pytest.mark.parametrize("dtype", ["float32", "bfloat16"])
@pytest.mark.parametrize("channels_last", [False, True])