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: refuse a single-file diffusion load that would exhaust host RAM instead of crashing (#14510)

Daniel Han1032b5f13b5a
diff --git a/studio/backend/core/inference/diffusion_comfy_block.py b/studio/backend/core/inference/diffusion_comfy_block.py
index cf6ceaad345..ce1931b8492 100644
--- a/studio/backend/core/inference/diffusion_comfy_block.py
+++ b/studio/backend/core/inference/diffusion_comfy_block.py
@@ -48,6 +48,11 @@ def untile_scales(tiled: Any, rows: int, blocks: int) -> Any:
f"tiled scales hold {flat.numel()} values, {rp * bp} expected for {rows}x{blocks}"
)
# tile (row // 128, block // 4) is 512 values: inner (row % 32, (row % 128) // 32, block % 4)
+ from .diffusion_single_file_converters import charge_host_ram
+
+ # the permuted copy, and while it is still live the trimmed copy when the block count is padded
+ trimmed = rows * blocks if blocks != bp else 0
+ charge_host_ram((rp * bp + trimmed) * flat.element_size())
v = flat.reshape(rp // 128, bp // 4, 32, 4, 4).permute(0, 3, 2, 1, 4).reshape(rp, bp)
return v[:rows, :blocks].contiguous()
@@ -59,6 +64,9 @@ def tile_scales(plain: Any) -> Any:
rows, blocks = plain.shape
rp, bp = _roundup(rows, 128), _roundup(blocks, 4)
raw = plain.view(torch.uint8) if plain.element_size() == 1 else plain
+ from .diffusion_single_file_converters import charge_host_ram
+
+ charge_host_ram(2 * rp * bp * raw.element_size()) # the padded buffer and its permuted copy
full = torch.zeros(rp, bp, dtype = raw.dtype, device = raw.device)
full[:rows, :blocks] = raw
out = full.reshape(rp // 128, 4, 32, bp // 4, 4).permute(0, 3, 2, 1, 4).reshape(-1).contiguous()
@@ -69,8 +77,22 @@ def swap_nibbles(packed: Any) -> Any:
"""High-first fp4 packing <-> low-first (``0xAB`` -> ``0xBA``)."""
import torch
+ from .diffusion_single_file_converters import charge_host_ram
+
u = packed.view(torch.uint8) if packed.dtype != torch.uint8 else packed
- return ((u << 4) | (u >> 4)).to(torch.uint8)
+ # One output (the source stays memory-mapped), filled in bounded row chunks: the expression form held
+ # the left shift, the right shift and their OR at once, three packed copies.
+ flat = u.reshape(u.shape[0], -1) if u.dim() > 1 else u.reshape(-1, 1)
+ row = max(1, int(flat.shape[1]))
+ chunk = max(1, min(int(flat.shape[0]), _DEQUANT_CHUNK_BYTES // row))
+ charge_host_ram(u.numel() + chunk * row)
+ out = torch.empty_like(flat)
+ for start in range(0, int(flat.shape[0]), chunk):
+ part = flat[start : start + chunk]
+ dst = out[start : start + chunk]
+ torch.bitwise_left_shift(part, 4, out = dst)
+ dst |= part >> 4
+ return out.reshape(u.shape)
def decode_layer(fmt: str, weight: Any, weight_scale: Any) -> tuple[Any, Any]:
@@ -96,19 +118,24 @@ def logical_cols(fmt: str, codes: Any) -> int:
return int(codes.shape[1]) * (2 if fmt == NVFP4 else 1)
-def dequant_block(
- fmt: str,
- codes: Any,
- scale: Any,
- *,
- tensor_scale: Any = None,
- pre_quant_scale: Any = None,
- dtype: Any = None,
-) -> Any:
- """Dense ``[N, K]`` weight; ``pre_quant_scale`` folds into the columns: ``(x * s) @ W.T == x @ (W * s).T``."""
+# Row chunks of a fallback block dequantization keep its float32 / int32 intermediates under this many bytes.
+_DEQUANT_CHUNK_BYTES = 16 << 20
+
+
+def _dequant_temp_bytes_per_row(fmt: str, cols: int, pre_quant: bool) -> int:
+ """Peak bytes of intermediates one row of ``_dequant_block_rows`` holds at once (``cols`` logical columns).
+
+ nvfp4: int32 codes (2 per packed byte: 2 * cols), two masked int32 index tensors and two float32 gathers
+ of cols / 2 each (8 * cols), the stacked float32 values (4 * cols), the scaled float32 product (4 * cols);
+ the masks and gathers are freed before the product, so the peak is codes + gathers + stack. mxfp8: float32
+ codes and their product (8 * cols). A pre-quant scale adds one float32 product."""
+ peak = 14 * cols if fmt == NVFP4 else 8 * cols
+ return peak + (4 * cols if pre_quant else 0)
+
+
+def _dequant_block_rows(fmt, codes, scale, tensor_scale, pre_quant_scale):
import torch
- dtype = dtype or torch.bfloat16
rows = int(codes.shape[0])
if fmt == NVFP4:
lut = torch.tensor(
@@ -116,11 +143,10 @@ def dequant_block(
)
c = codes.to(torch.int32)
values = torch.stack((lut[c & 0x0F], lut[c >> 4]), dim = -1).reshape(rows, -1, 16)
+ del c
step = scale.to(torch.float32)
if tensor_scale is not None:
- step = step * torch.as_tensor(
- tensor_scale, dtype = torch.float32, device = codes.device
- ).reshape(-1, 1)
+ step = step * tensor_scale
weight = (values * step.unsqueeze(-1)).reshape(rows, -1)
elif fmt == MXFP8:
exp = scale.view(torch.uint8).to(torch.float32) - _E8M0_BIAS
@@ -130,8 +156,50 @@ def dequant_block(
else:
raise ValueError(f"not a block-scaled ComfyUI format: {fmt!r}")
if pre_quant_scale is not None:
- weight = weight * pre_quant_scale.to(torch.float32).reshape(1, -1)
- return weight.to(dtype)
+ weight = weight * pre_quant_scale
+ return weight
+
+
+def dequant_block(
+ fmt: str,
+ codes: Any,
+ scale: Any,
+ *,
+ tensor_scale: Any = None,
+ pre_quant_scale: Any = None,
+ dtype: Any = None,
+) -> Any:
+ """Dense ``[N, K]`` weight; ``pre_quant_scale`` folds into the columns: ``(x * s) @ W.T == x @ (W * s).T``.
+
+ Dequantized in row chunks straight into the output, so the float32 intermediates stay bounded by
+ ``_DEQUANT_CHUNK_BYTES`` instead of several times the layer; every op is per row, so the result is
+ bit-identical to one pass."""
+ import torch
+
+ from .diffusion_single_file_converters import charge_host_ram
+
+ if fmt not in BLOCK_SIZES:
+ raise ValueError(f"not a block-scaled ComfyUI format: {fmt!r}")
+ dtype = dtype or torch.bfloat16
+ rows = int(codes.shape[0])
+ cols = logical_cols(fmt, codes)
+ per_row = _dequant_temp_bytes_per_row(fmt, cols, pre_quant_scale is not None)
+ chunk = max(1, min(rows, _DEQUANT_CHUNK_BYTES // max(per_row, 1)))
+ charge_host_ram(rows * cols * torch.empty((), dtype = dtype).element_size() + chunk * per_row)
+ ts = None
+ if tensor_scale is not None:
+ ts = torch.as_tensor(tensor_scale, dtype = torch.float32, device = codes.device).reshape(-1, 1)
+ pqs = None
+ if pre_quant_scale is not None:
+ pqs = pre_quant_scale.to(torch.float32).reshape(1, -1)
+ out = torch.empty((rows, cols), dtype = dtype, device = codes.device)
+ for start in range(0, rows, chunk):
+ stop = min(rows, start + chunk)
+ part_ts = ts if ts is None or ts.shape[0] == 1 else ts[start:stop]
+ out[start:stop] = _dequant_block_rows(
+ fmt, codes[start:stop], scale[start:stop], part_ts, pqs
+ ).to(dtype)
+ return out
def mx_quantize_activation(x: Any) -> tuple[Any, Any]:
@@ -403,6 +471,8 @@ def build_runtime_linear(
) -> Any:
import torch
+ from .diffusion_single_file_converters import charge_host_ram
+
rows = int(codes.shape[0])
if fmt == NVFP4:
from .diffusion_nvfp4_linear import nvfp4_linear_class
@@ -426,6 +496,8 @@ def build_runtime_linear(
# FlashInfer's activation global scale is the reciprocal of ComfyUI's decode-side input_scale.
a_gsf = (1.0 / in_scale).clone()
cls = nvfp4_linear_class()
+ if not codes.is_contiguous():
+ charge_host_ram(int(codes.numel()) * int(codes.element_size()))
return cls(
cols,
rows,
@@ -438,6 +510,8 @@ def build_runtime_linear(
activation_scales_baked = True,
)
if fmt == MXFP8:
+ if not codes.is_contiguous():
+ charge_host_ram(int(codes.numel()) * int(codes.element_size()))
return mxfp8_linear_class()(
int(codes.shape[1]),
rows,
diff --git a/studio/backend/core/inference/diffusion_comfy_quant.py b/studio/backend/core/inference/diffusion_comfy_quant.py
index 17d17a73e39..d03335e98fe 100644
--- a/studio/backend/core/inference/diffusion_comfy_quant.py
+++ b/studio/backend/core/inference/diffusion_comfy_quant.py
@@ -29,6 +29,7 @@ from dataclasses import dataclass, field
from typing import Any, Optional
from .diffusion_comfy_block import BLOCK_SIZES, MXFP8, NVFP4, tiled_scale_numel
+from .diffusion_single_file_converters import host_ram_budget_scope
COMFY_QUANT_SUFFIX = ".comfy_quant"
QUANT_METADATA_KEY = "_quantization_metadata"
@@ -442,11 +443,29 @@ def refuse_comfy_quant(path: Optional[str]) -> Optional[ComfyQuantScan]:
return scan
+def _nbytes(tensors: Any) -> int:
+ return sum(int(t.numel()) * int(t.element_size()) for t in tensors)
+
+
+def _charge_contiguous(tensor: Any) -> None:
+ """Check the copy ``tensor.contiguous()`` makes of a non-contiguous host tensor (a view costs nothing)."""
+ if not tensor.is_contiguous():
+ from .diffusion_single_file_converters import charge_host_ram
+ charge_host_ram(_nbytes([tensor]))
+
+
def _dequant(codes: Any, scale: Any, group: int, dtype: Any) -> Any:
"""``codes * scale`` in float32, the ConvRot rotation undone, cast to ``dtype``."""
import torch
+ from .diffusion_single_file_converters import charge_host_ram
+
rows = codes.shape[0]
+ # Peak, not just the output: the float32 codes and their float32 product are live together (8 bytes per
+ # element); ConvRot's batched matmul holds the product, a float32 copy of it and its float32 result (12,
+ # measured); last the product and the output.
+ out_size = torch.empty((), dtype = dtype).element_size()
+ charge_host_ram(codes.numel() * max(12 if group else 8, 4 + out_size))
weight = codes.to(torch.float32) * scale.to(torch.float32).reshape(-1, 1).expand(rows, 1)
if group:
from .diffusion_convrot import build_convrot_hadamard
@@ -482,7 +501,12 @@ def _dequant_parts(fmt: str, parts: list, dtype: Any) -> Any:
)
for codes, scale, extra in parts
]
- return dense[0] if len(dense) == 1 else torch.cat(dense)
+ if len(dense) == 1:
+ return dense[0]
+ from .diffusion_single_file_converters import charge_host_ram
+
+ charge_host_ram(_nbytes(dense))
+ return torch.cat(dense)
def _block_runtime_args(value: "_BlockWeight") -> Optional[tuple]:
@@ -491,6 +515,11 @@ def _block_runtime_args(value: "_BlockWeight") -> Optional[tuple]:
import torch
extras = [extra for _c, _s, extra in value.parts]
+ if len(value.parts) > 1:
+ from .diffusion_single_file_converters import charge_host_ram
+ charge_host_ram(
+ _nbytes([c for c, _s, _e in value.parts]) + _nbytes([s for _c, s, _e in value.parts])
+ )
codes = (
torch.cat([c for c, _s, _e in value.parts]) if len(value.parts) > 1 else value.parts[0][0]
)
@@ -534,6 +563,7 @@ def _int8_tensor(name: str, codes: Any, scale: Any, dtype: Any) -> Optional[Any]
"_tensor_data_names": ["zero_point", "qdata", "scale"],
}
stem = name.rsplit(".", 1)[0]
+ _charge_contiguous(codes)
tensors = {
f"{stem}._weight_qdata": codes.contiguous(),
f"{stem}._weight_scale": scale.to(torch.float32).reshape(rows, 1).contiguous(),
@@ -591,6 +621,7 @@ def _fp8_tensor(
"_tensor_data_names": ["qdata", "scale"],
}
stem = name.rsplit(".", 1)[0]
+ _charge_contiguous(codes)
tensors = {
f"{stem}._weight_qdata": codes.contiguous(),
f"{stem}._weight_scale": scale.to(torch.float32)
@@ -726,7 +757,13 @@ def _apply_key_map(state: dict, kept: list, key_map: Any) -> dict:
# float8: concatenation goes through uint8 (not implemented for float8 on every torch)
return take(value.view(torch.uint8), rows).view(value.dtype)
parts = [value[int(r) : int(r) + int(n)] for r, n in rows]
- return parts[0] if len(parts) == 1 else torch.cat(parts)
+ if len(parts) == 1:
+ return parts[0]
+ from .diffusion_single_file_converters import charge_host_ram
+
+ # a reordered selection (H3's [gate; value] fc1) is a full copy of the rows it joins
+ charge_host_ram(_nbytes(parts))
+ return torch.cat(parts)
converted: dict = {}
for key in list(state):
@@ -920,6 +957,7 @@ def load_comfy_prequant(
return model
+@host_ram_budget_scope
def load_comfy_quant_transformer(
transformer_cls: Any,
path: str,
@@ -1036,6 +1074,42 @@ def load_comfy_quant_transformer(
NVFP4: nvfp4_backend,
MXFP8: mxfp8_backend,
}
+ # Without a runtime (fp8 below sm_89) layers widen to ``dtype`` in host RAM: refuse before an OOM.
+ from .diffusion_single_file_converters import (
+ HostRamBudget,
+ HostRamShortfallError,
+ charge_cast,
+ charge_host_ram,
+ converted_host_bytes,
+ )
+
+ # Mirrors the source loop below: a layer is kept as codes only with a runtime for its format (fp16_keep
+ # merely defers the dtype choice; the layer is still expanded) and, for a block format, no key map.
+ # nvfp4 headers describe packed uint8 (K / 2 columns); the dense weight is N x K.
+ _widened = {
+ layer.name + ".weight": (
+ (2 if layer.format == NVFP4 else 1)
+ if not backends.get(layer.format)
+ or (layer.format in BLOCK_SIZES and key_map is not None)
+ else 0
+ )
+ for layer in scan.layers.values()
+ }
+ # The header estimate refuses early; the budget it activates is charged by every allocating helper
+ # below, so a layer the estimate cannot see (runtime filters, nibble swaps) still cannot OOM the host.
+ budget = HostRamBudget(
+ path, f"expanding its quantized weights to {str(dtype).replace('torch.', '')}", logger
+ )
+ budget.check(
+ converted_host_bytes(
+ path,
+ dtype,
+ keep_fp32 = keep_fp32 if fp16_keep else (),
+ dequantized = _widened.get,
+ keep_key = keep_key,
+ )
+ )
+ budget.activate()
sources: list = [] # (layer, codes, scale, block extras or None) kept for a runtime
dequantized = 0
for layer in scan.layers.values():
@@ -1078,10 +1152,12 @@ def load_comfy_quant_transformer(
continue
wanted_dtype = keep_dtype(key) if keep_dtype is not None else None
if wanted_dtype is not None:
+ charge_cast(value, wanted_dtype)
state[key] = value.to(wanted_dtype)
continue
if fp16_keep or value.dtype == dtype:
continue
+ charge_cast(value, dtype)
state[key] = value.to(dtype)
from accelerate import init_empty_weights
@@ -1146,14 +1222,15 @@ def load_comfy_quant_transformer(
out[name] = _BlockWeight(fmt, blocks)
continue
parts = [sources[i][1][r : r + n] for i, r, n in segments]
- # one segment (a split or renamed layer) is a row slice of a contiguous tensor: no copy
+ scale_parts = [
+ sources[i][2].reshape(-1, 1).expand(sources[i][1].shape[0], 1)[r : r + n]
+ for i, r, n in segments
+ ]
+ # one segment (a split or renamed layer) is a row slice of a contiguous tensor: no copy; a
+ # reorder (a stock converter swapping gate / proj halves) is a full copy of the kept codes
+ charge_host_ram((_nbytes(parts) if len(parts) > 1 else 0) + _nbytes(scale_parts))
codes = parts[0] if len(parts) == 1 else torch.cat(parts)
- scale = torch.cat(
- [
- sources[i][2].reshape(-1, 1).expand(sources[i][1].shape[0], 1)[r : r + n]
- for i, r, n in segments
- ]
- )
+ scale = torch.cat(scale_parts)
if name in wanted and tuple(wanted[name].shape) != tuple(codes.shape):
raise ValueError(
f"{name}: rebuilt as {tuple(codes.shape)}, the model expects {tuple(wanted[name].shape)}"
@@ -1174,12 +1251,18 @@ def load_comfy_quant_transformer(
try:
# Narrow tags first (full width is slow on a large DiT); anything unproven reruns at full width.
converted = _convert_tagged(_NARROW_TAG_COLUMNS if sources else None)
+ except HostRamShortfallError:
+ raise # a refusal, not an unproven tag: the full-width retry would only allocate more
except Exception: # noqa: BLE001 -- the full-width pass raises the real refusal
+ # Full-width float64 tags are views, but a converter that joins or splits rows materializes them
+ # (8 bytes per weight element) before any checked helper runs: check that before retrying.
+ charge_host_ram(8 * sum(int(codes.numel()) for _layer, codes, *_rest in sources))
converted = _convert_tagged(None)
del state
if fp16_keep:
for key, value in list(converted.items()):
if torch.is_tensor(value) and value.is_floating_point():
+ charge_cast(value, _dtype_for(key))
converted[key] = value.to(_dtype_for(key))
min_features = DEFAULT_MIN_LINEAR_FEATURES if min_features is None else int(min_features)
diff --git a/studio/backend/core/inference/diffusion_single_file_converters.py b/studio/backend/core/inference/diffusion_single_file_converters.py
index a91cdb6d059..6fd86c1b1ab 100644
--- a/studio/backend/core/inference/diffusion_single_file_converters.py
+++ b/studio/backend/core/inference/diffusion_single_file_converters.py
@@ -11,8 +11,10 @@ No module-level torch import: ``diffusion.py`` imports this on every load.
from __future__ import annotations
+import contextvars
+import os
import re
-from typing import Any
+from typing import Any, Optional
_CONTAINER_PREFIXES = ("model.diffusion_model.", "model.model.", "diffusion_model.")
@@ -335,6 +337,7 @@ def _cat_rows(first: Any, second: Any) -> Any:
"""Concatenate two row blocks, keeping a ``GGUFParameter``'s quant type (whole blocks per row)."""
import torch
+ charge_host_ram(first.numel() * first.element_size() + second.numel() * second.element_size())
out = torch.cat([first, second], dim = 0)
quant_type = getattr(first, "quant_type", None)
if quant_type is not None and getattr(out, "quant_type", None) is None:
@@ -349,6 +352,223 @@ CONVERTERS: dict = {
}
+_ST_ITEMSIZE = {
+ "F64": 8, "F32": 4, "F16": 2, "BF16": 2, "F8_E4M3": 1, "F8_E5M2": 1, "F8_E8M0": 1,
+ "F8_E4M3FNUZ": 1, "F8_E5M2FNUZ": 1,
+ "I64": 8, "I32": 4, "I16": 2, "I8": 1, "U8": 1, "BOOL": 1,
+} # fmt: skip
+_ST_FLOATS = ("F64", "F32", "F16", "BF16", "F8_E4M3", "F8_E5M2", "F8_E4M3FNUZ", "F8_E5M2FNUZ")
+HOST_RAM_CHECK_MIN_MIB = 1024
+_MIB = 1024 * 1024
+
+
+class HostRamShortfallError(RuntimeError):
+ """A single-file load whose converted weights would not fit in the host RAM left."""
+
+
+def _torch_dtype_tag(dtype: Any) -> str:
+ return {
+ "torch.float32": "F32",
+ "torch.float16": "F16",
+ "torch.bfloat16": "BF16",
+ }.get(str(dtype), "BF16")
+
+
+def converted_host_bytes(
+ path: str,
+ dtype: Any,
+ *,
+ keep_fp32: Any = (),
+ dequantized: Any = None,
+ keep_key: Any = None,
+) -> int:
+ """Anonymous host RAM bytes loading ``path`` at ``dtype`` writes, from the header alone.
+
+ ``keep_key(key)``: the loader's own key filter (a file bundling other components), so tensors it never
+ reads are not priced.
+
+ Tensors already at the target dtype stay memory-mapped (droppable page cache) and cost 0.
+ ``dequantized(key)``: None = not quantized, 0 / False = kept as codes, else the dense elements each
+ stored element expands to (True = 1; 2 for nvfp4, which packs two columns per byte) when widened
+ to ``dtype``. Unreadable header returns 0 (no claim)."""
+ from .diffusion_comfy_quant import _read_header
+
+ try:
+ header, _base = _read_header(str(path))
+ except Exception: # noqa: BLE001 -- the loader reports a bad file itself
+ return 0
+ header.pop("__metadata__", None)
+ target = _torch_dtype_tag(dtype)
+ keep = tuple(keep_fp32 or ())
+ total = 0
+ for key, meta in header.items():
+ if keep_key is not None and not keep_key(key):
+ continue
+ try:
+ stored = str(meta.get("dtype"))
+ numel = 1
+ for dim in meta.get("shape") or ():
+ numel *= int(dim)
+ except Exception: # noqa: BLE001
+ continue
+ verdict = dequantized(key) if dequantized is not None else None
+ if verdict is not None:
+ total += numel * int(verdict) * _ST_ITEMSIZE[target]
+ continue
+ if stored not in _ST_FLOATS:
+ continue
+ want = "F32" if keep and any(m in key.split(".") for m in keep) else target
+ if stored != want:
+ total += numel * _ST_ITEMSIZE[want]
+ return total
+
+
+class HostRamBudget:
+ """The host RAM check of one single-file load: an up-front header estimate, then a check before each
+ large allocation against what is free right now.
+
+ ``converted_host_bytes`` prices a load from the header before any read, but cannot see the per-layer
+ choices made later (runtime filters, nibble swaps, row reorders). Every allocating helper therefore
+ calls ``charge_host_ram(nbytes)`` (a no-op outside an active budget) before it allocates, and the load
+ is refused when that allocation plus the small-host reserve exceeds the host's LIVE available memory,
+ instead of the OOM that ends the whole server. Live, not a running total: buffers the load has
+ already freed are back in the next reading, and copies made where nothing checks still show up in
+ it. ``UNSLOTH_DIFFUSION_HOST_RAM_CHECK=0`` disables both checks."""
+
+ def __init__(
+ self,
+ path: str,
+ why: str,
+ logger: Any = None,
+ ) -> None:
+ from .diffusion_small_host import (
+ host_ram_check_disabled,
+ host_ram_mib,
+ host_reserve_mib,
+ )
+
+ self.path, self.why, self.logger = path, why, logger
+ self._token = None
+ self.available_mib: Optional[int] = None
+ self.reserve_mib = 0
+ self.armed = False
+ self.requested = (
+ 0 # only to arm a load that started under the floor; the check reads live memory
+ )
+ if host_ram_check_disabled():
+ return
+ try:
+ total, available = host_ram_mib()
+ except Exception: # noqa: BLE001 -- unreadable: no claim, as the small-host route does
+ return
+ if available is None:
+ return
+ self.available_mib = int(available)
+ self.reserve_mib = host_reserve_mib(total)
+ # Armed by the file size here, and by the widened estimate in ``check``: a 900 MiB nvfp4 file widens
+ # to 3.6 GiB of bf16. Only a load small on disk AND in its estimate is never checked.
+ try:
+ size_mib = os.path.getsize(str(path)) // _MIB
+ except OSError:
+ size_mib = HOST_RAM_CHECK_MIN_MIB
+ self.armed = size_mib >= HOST_RAM_CHECK_MIN_MIB
+
+ def _refuse_if_over(self, need_bytes: int, available_mib: int, at_least: bool) -> None:
+ from .diffusion_small_host import HOST_RAM_CHECK_ENV
+
+ need_mib = -(-int(need_bytes) // _MIB)
+ if need_mib + self.reserve_mib <= available_mib:
+ return
+ reserve = self.reserve_mib
+ name = os.path.basename(str(self.path))
+ message = (
+ f"Not enough system RAM to load {name}: {self.why} needs "
+ f"{'at least' if at_least else 'about'} {(need_mib + reserve) / 1024:.1f} GB of free host "
+ f"memory ({need_mib / 1024:.1f} GB of weights + {reserve / 1024:.1f} GB reserve) and "
+ f"{available_mib / 1024:.1f} GB is free. Close other applications, use a GGUF or a "
+ f"smaller quant of this model, or set {HOST_RAM_CHECK_ENV}=0 to try anyway."
+ )
+ if self.logger is not None:
+ self.logger.error("diffusion.single_file: refusing load: %s", message)
+ raise HostRamShortfallError(message)
+
+ def check(self, need_bytes: int) -> None:
+ """Up-front refusal from a header estimate, against free memory when the load started."""
+ if self.available_mib is None or -(-int(need_bytes) // _MIB) < HOST_RAM_CHECK_MIN_MIB:
+ return
+ self.armed = True
+ self._refuse_if_over(need_bytes, self.available_mib, at_least = False)
+
+ def charge(self, nbytes: int) -> None:
+ """Refuse before allocating ``nbytes`` when they and the reserve exceed live available memory."""
+ if self.available_mib is None or nbytes <= 0:
+ return
+ if not self.armed:
+ # A load small on disk and in its estimate can still write a lot (a runtime filter rejecting
+ # layers the estimate assumed kept): arm once the checked allocations reach the floor.
+ self.requested += int(nbytes)
+ if self.requested < HOST_RAM_CHECK_MIN_MIB * _MIB:
+ return
+ self.armed = True
+ from .diffusion_small_host import host_ram_mib
+
+ try:
+ available = host_ram_mib()[1]
+ except Exception: # noqa: BLE001 -- an unreadable reading makes no claim
+ return
+ if available is not None:
+ self._refuse_if_over(nbytes, int(available), at_least = True)
+
+ def activate(self) -> "HostRamBudget":
+ """Make this the budget the allocating helpers charge, until the enclosing
+ ``host_ram_budget_scope`` returns."""
+ if self.available_mib is not None: # check disabled / RAM unreadable: nothing is charged
+ _ACTIVE_BUDGET.set(self)
+ return self
+
+ def __enter__(self) -> "HostRamBudget":
+ self._token = _ACTIVE_BUDGET.set(self if self.available_mib is not None else None)
+ return self
+
+ def __exit__(self, *exc: Any) -> None:
+ _ACTIVE_BUDGET.reset(self._token)
+
+
+_ACTIVE_BUDGET: "contextvars.ContextVar[Optional[HostRamBudget]]" = contextvars.ContextVar(
+ "unsloth_single_file_host_ram_budget", default = None
+)
+
+
+def host_ram_budget_scope(fn: Any) -> Any:
+ """Run ``fn`` with no budget inherited and none left behind: a budget it ``activate()``s lives
+ exactly as long as the call."""
+ import functools
+
+ @functools.wraps(fn)
+ def wrapper(*args: Any, **kwargs: Any) -> Any:
+ token = _ACTIVE_BUDGET.set(None)
+ try:
+ return fn(*args, **kwargs)
+ finally:
+ _ACTIVE_BUDGET.reset(token)
+
+ return wrapper
+
+
+def charge_host_ram(nbytes: int) -> None:
+ """Check ``nbytes`` about to be allocated against the active ``HostRamBudget``, if any."""
+ budget = _ACTIVE_BUDGET.get()
+ if budget is not None and nbytes > 0:
+ budget.charge(nbytes)
+
+
+def charge_cast(value: Any, dtype: Any) -> None:
+ """Charge the copy ``value.to(dtype)`` makes; nothing when it is already ``dtype``."""
+ if getattr(value, "dtype", dtype) != dtype:
+ import torch
+ charge_host_ram(value.numel() * torch.empty((), dtype = dtype).element_size())
+
+
def load_original_layout_transformer(
transformer_cls: Any,
path: str,
@@ -359,9 +579,7 @@ def load_original_layout_transformer(
(Krea 2 on diffusers 0.40). ``sf_kwargs`` = the ``from_single_file`` kwargs. Cast like
``from_pretrained`` (``_keep_in_fp32_modules`` stay fp32); strict on keys and shapes."""
import torch
- from accelerate import init_empty_weights
from diffusers.loaders import single_file_model as sfm
- from safetensors.torch import load_file
kwargs = dict(sf_kwargs)
dtype = kwargs.pop("torch_dtype", None) or torch.bfloat16
@@ -381,6 +599,23 @@ def load_original_layout_transformer(
mapping_fn = CONVERTERS.get(transformer_cls.__name__) or entry.get("checkpoint_mapping_fn")
if mapping_fn is None:
raise ValueError(f"{transformer_cls.__name__} has no single-file converter")
+ keep = getattr(transformer_cls, "_keep_in_fp32_modules", None) or []
+ if isinstance(keep, str):
+ keep = [keep]
+ # Before any read: fp8 widened to bf16 (13B Krea 2: ~26 GB) used to OOM the whole app.
+ budget = HostRamBudget(
+ path, f"widening its weights to {str(dtype).replace('torch.', '')}", logger
+ )
+ budget.check(converted_host_bytes(path, dtype, keep_fp32 = keep))
+ with budget:
+ return _load_original_layout(transformer_cls, path, config, mapping_fn, keep, dtype, logger)
+
+
+def _load_original_layout(transformer_cls, path, config, mapping_fn, keep, dtype, logger) -> Any:
+ import torch
+ from accelerate import init_empty_weights
+ from safetensors.torch import load_file
+
with init_empty_weights():
model = transformer_cls.from_config(config)
wanted = model.state_dict()
@@ -396,9 +631,6 @@ def load_original_layout_transformer(
f"{name} does not match {transformer_cls.__name__}: {len(missing)} missing "
f"(e.g. {missing[:1]}), {len(unexpected)} unused (e.g. {unexpected[:1]})"
)
- keep = getattr(transformer_cls, "_keep_in_fp32_modules", None) or []
- if isinstance(keep, str):
- keep = [keep]
for key, value in converted.items():
want = torch.float32 if any(m in key.split(".") for m in keep) else dtype
if not value.is_floating_point():
@@ -408,6 +640,7 @@ def load_original_layout_transformer(
f"{key}: {tuple(value.shape)} in the file, {tuple(wanted[key].shape)} in the model"
)
if value.dtype != want:
+ charge_cast(value, want)
converted[key] = value.to(want)
model.load_state_dict(converted, strict = True, assign = True)
model.eval()
diff --git a/studio/backend/tests/test_diffusion_comfy_block.py b/studio/backend/tests/test_diffusion_comfy_block.py
index b20402430e4..afbebfaaa67 100644
--- a/studio/backend/tests/test_diffusion_comfy_block.py
+++ b/studio/backend/tests/test_diffusion_comfy_block.py
@@ -627,3 +627,379 @@ def test_mxfp8_e8m0_scales_are_priced_one_byte(tmp_path):
path = _layer_file(tmp_path, "mxfp8", rows = 4096, cols = 8192)
# 32 MiB of fp8 codes + 1 MiB of e8m0 block scales + the comfy_quant bytes, rounded up (35 at 2 bytes)
assert cq.comfy_resident_mib(path, keep_int8 = False, keep_fp8 = False, keep_mxfp8 = True) == 34
+
+
+def test_dequantized_nvfp4_is_priced_at_its_unpacked_width(block_file, monkeypatch):
+ """nvfp4 packs two columns per byte, so the header's numel is half the dense N x K the dequantization
+ allocates; the host RAM check must price the dense weight."""
+ import core.inference.diffusion_single_file_converters as conv
+
+ path, _tensors, expected = block_file("nvfp4")
+ seen = []
+ monkeypatch.setattr(conv.HostRamBudget, "check", lambda self, need: seen.append(need))
+ _load(path)
+ dense = sum(t.numel() for t in expected.values()) * 4 # float32 compute
+ assert seen and seen[0] >= dense
+
+
+def _tight_host(monkeypatch, headroom_mib):
+ """A host whose free RAM leaves ``headroom_mib`` above the small-host reserve; every byte priced."""
+ import core.inference.diffusion_single_file_converters as conv
+ import core.inference.diffusion_small_host as small_host
+
+ total = 32768
+ monkeypatch.setattr(conv, "HOST_RAM_CHECK_MIN_MIB", 0)
+ monkeypatch.delenv(small_host.HOST_RAM_CHECK_ENV, raising = False)
+ monkeypatch.setattr(
+ small_host,
+ "host_ram_mib",
+ lambda: (total, small_host.host_reserve_mib(total) + headroom_mib),
+ )
+ return conv
+
+
+def test_layers_the_runtime_filter_rejects_are_charged_as_dequantized(block_file, monkeypatch):
+ """A runtime for the format keeps only layers passing its filter (size, name exclusions, ...); the
+ rest are expanded to the compute dtype, each checked before its expansion."""
+ conv = _tight_host(monkeypatch, headroom_mib = 1 << 20)
+ seen = []
+ monkeypatch.setattr(conv.HostRamBudget, "charge", lambda self, n: seen.append(int(n)))
+ path, _tensors, _expected = block_file("mxfp8")
+ model = _load(path, dtype = torch.bfloat16, mxfp8_backend = "kept", min_features = 1 << 20)
+ assert model._unsloth_comfy_quant["dequantized"] == 8
+ # every bf16 to_q / to_k / to_v / to_out, checked for at least its dense size
+ assert sum(1 for n in seen if n >= DIM * DIM * 2) >= 8
+
+
+def test_kept_nvfp4_codes_are_charged_for_their_nibble_swapped_copy(block_file, monkeypatch):
+ """With an nvfp4 runtime the codes are kept, but decode_layer writes a nibble-swapped uint8 copy of
+ the packed weight (plus untiled scales): new host RAM, checked even though nothing is dequantized."""
+ conv = _tight_host(monkeypatch, headroom_mib = 1 << 20)
+ seen = []
+ monkeypatch.setattr(conv.HostRamBudget, "charge", lambda self, n: seen.append(int(n)))
+ path, tensors, _expected = block_file("nvfp4")
+ try:
+ _load(path, dtype = torch.bfloat16, nvfp4_backend = "kept")
+ except ImportError:
+ pass # no flashinfer here: the checks ran while decoding, before any runtime Linear is built
+ packed = tensors["blocks.0.out.weight"]
+ assert any(n >= packed.numel() * packed.element_size() for n in seen), seen
+
+
+def test_a_runtime_linear_checks_its_tiled_scale_buffer(block_file, monkeypatch):
+ """A kept mxfp8 layer re-tiles its scales for the runtime Linear (a zero-padded buffer and the
+ permuted copy it keeps): both are new host memory, checked before they are allocated."""
+ import core.inference.diffusion_single_file_converters as conv
+ import core.inference.diffusion_small_host as small_host
+
+ monkeypatch.setattr(conv, "HOST_RAM_CHECK_MIN_MIB", 0)
+ monkeypatch.delenv(small_host.HOST_RAM_CHECK_ENV, raising = False)
+ monkeypatch.setattr(small_host, "host_ram_mib", lambda: (1 << 20, 1 << 20))
+ seen = []
+ monkeypatch.setattr(conv.HostRamBudget, "charge", lambda self, n: seen.append(int(n)))
+ path, _tensors, _expected = block_file("mxfp8")
+ _load(path, dtype = torch.bfloat16, mxfp8_backend = "kept")
+ assert 2 * _ceil(DIM, 128) * _ceil(DIM // 32, 4) in seen
+
+
+class _Many(nn.Module):
+ """Many bias-free square Linears: enough layers that per-layer transients would add up."""
+
+ _keep_in_fp32_modules = None
+ _keys_to_ignore_on_load_unexpected = None
+ LAYERS, WIDTH = 48, 2048
+
+ def __init__(
+ self,
+ layers: int = LAYERS,
+ width: int = WIDTH,
+ ) -> None:
+ super().__init__()
+ self.layers = nn.ModuleList(nn.Linear(width, width, bias = False) for _ in range(layers))
+
+ @classmethod
+ def load_config(cls, repo, **_kwargs):
+ return {"layers": cls.LAYERS, "width": cls.WIDTH}
+
+ @staticmethod
+ def _get_signature_keys(_cls):
+ return {"layers", "width"}, set()
+
+ @classmethod
+ def from_config(cls, config):
+ return cls(**config)
+
+
+def _rss_anon_bytes():
+ import ctypes
+
+ try:
+ ctypes.CDLL("libc.so.6").malloc_trim(0) # hand freed heap back, so RssAnon is what is live
+ except OSError:
+ pass
+ with open("/proc/self/status") as status:
+ for line in status:
+ if line.startswith("RssAnon:"):
+ return int(line.split()[1]) * 1024
+ return None
+
+
+def test_a_many_layer_nvfp4_fallback_load_that_fits_is_not_refused(tmp_path, monkeypatch):
+ """No nvfp4 runtime: every layer is nibble-swapped, its scales untiled, then dequantized, and the
+ swapped codes and plain scales are freed again before the next layer. Free host RAM is modelled
+ from this process's own anonymous RSS, with room for the dense weights plus 10% and one chunk of
+ dequantization intermediates: the load fits and must not be refused for copies already released."""
+ import core.inference.diffusion_single_file_converters as conv
+ import core.inference.diffusion_small_host as small_host
+
+ if not torch.__config__.show() or _rss_anon_bytes() is None:
+ pytest.skip("needs /proc/self/status RssAnon")
+ layers, width = _Many.LAYERS, _Many.WIDTH
+ gen = torch.Generator().manual_seed(0)
+ tensors = {}
+ for i in range(layers):
+ stem = f"layers.{i}"
+ tensors[f"{stem}.weight"] = torch.randint(
+ 0, 256, (width, width // 2), dtype = torch.uint8, generator = gen
+ )
+ plain = torch.randint(56, 64, (width, width // 16), dtype = torch.uint8, generator = gen)
+ tensors[f"{stem}.weight_scale"] = _tile(plain).view(torch.float8_e4m3fn)
+ tensors[f"{stem}.weight_scale_2"] = torch.tensor(0.01)
+ tensors[f"{stem}.comfy_quant"] = _conf(format = "nvfp4")
+ path = _save(tmp_path / "many_nvfp4.safetensors", tensors)
+ del tensors
+ monkeypatch.setattr(
+ cq,
+ "_mapping",
+ lambda cls: (
+ lambda checkpoint = None, **_kw: checkpoint,
+ types.SimpleNamespace(
+ _should_convert_state_dict_to_diffusers = lambda a, b: False,
+ _get_mapping_function_kwargs = lambda fn, **kw: {},
+ ),
+ ),
+ )
+ dense = layers * width * width * 2 # bf16
+ total = 1 << 20
+ reserve = small_host.host_reserve_mib(total)
+ start = _rss_anon_bytes()
+ headroom = int(dense * 1.10) + getattr(cb, "_DEQUANT_CHUNK_BYTES", 16 << 20)
+ monkeypatch.setattr(conv, "HOST_RAM_CHECK_MIN_MIB", 0)
+ monkeypatch.delenv(small_host.HOST_RAM_CHECK_ENV, raising = False)
+ monkeypatch.setattr(
+ small_host,
+ "host_ram_mib",
+ lambda: (total, reserve + (headroom - (_rss_anon_bytes() - start)) // (1 << 20)),
+ )
+ model = cq.load_comfy_quant_transformer(
+ _Many,
+ path,
+ cq.refuse_comfy_quant(path),
+ {"torch_dtype": torch.bfloat16, "config": "base/repo"},
+ int8_backend = None,
+ nvfp4_backend = None,
+ family = "z-image",
+ )
+ assert model._unsloth_comfy_quant["dequantized"] == layers
+ assert model.layers[0].weight.dtype == torch.bfloat16
+
+
+def test_a_small_file_that_widens_past_the_floor_is_still_checked(block_file, monkeypatch):
+ """The check floor applies to what the load writes, not to the file: nvfp4 packs 8 dense float32
+ bytes into half a byte, so a file under the floor can still widen far past it."""
+ import os
+
+ conv = _tight_host(monkeypatch, headroom_mib = 1)
+ path, _tensors, _expected = block_file("nvfp4")
+ monkeypatch.setattr(conv, "HOST_RAM_CHECK_MIN_MIB", os.path.getsize(path) // (1 << 20) + 1)
+ with pytest.raises(conv.HostRamShortfallError, match = "needs about"):
+ _load(path) # float32: 8 MiB dense from a ~1 MiB file
+
+
+def _rss_anon_now():
+ with open("/proc/self/status") as status:
+ for line in status:
+ if line.startswith("RssAnon:"):
+ return int(line.split()[1]) * 1024
+ return None
+
+
[email protected]("fmt", ["nvfp4", "mxfp8"])
+def test_block_dequant_is_checked_for_its_peak_intermediates(monkeypatch, fmt):
+ """The fallback dequantization builds int32 / float32 intermediates several times the bf16 output; the
+ check before it must cover the measured peak, not only the output."""
+ import threading
+ import time
+
+ import core.inference.diffusion_single_file_converters as conv
+
+ if _rss_anon_bytes() is None:
+ pytest.skip("needs /proc/self/status RssAnon")
+ rows, cols = 4096, 4096
+ gen = torch.Generator().manual_seed(1)
+ if fmt == "nvfp4":
+ codes = torch.randint(0, 256, (rows, cols // 2), dtype = torch.uint8, generator = gen)
+ scale = torch.randint(56, 64, (rows, cols // 16), dtype = torch.uint8, generator = gen)
+ scale = scale.view(torch.float8_e4m3fn)
+ else:
+ codes = torch.randint(0, 120, (rows, cols), dtype = torch.uint8, generator = gen)
+ codes = codes.view(torch.float8_e4m3fn)
+ scale = torch.randint(120, 130, (rows, cols // 32), dtype = torch.uint8, generator = gen)
+ seen = []
+ monkeypatch.setattr(conv, "charge_host_ram", lambda n: seen.append(int(n)))
+ peak, stop = [0], [False]
+
+ def sample():
+ while not stop[0]:
+ peak[0] = max(peak[0], _rss_anon_now())
+ time.sleep(0.0005)
+
+ _rss_anon_bytes() # trim first, so the baseline is what is live
+ start = _rss_anon_now()
+ thread = threading.Thread(target = sample, daemon = True)
+ thread.start()
+ out = cb.dequant_block(fmt, codes, scale, tensor_scale = 0.01, dtype = torch.bfloat16)
+ stop[0] = True
+ thread.join()
+ growth = peak[0] - start
+ assert out.shape == (rows, cols)
+ assert seen and max(seen) >= 0.9 * growth, (seen, growth)
+
+
[email protected]("fmt", ["nvfp4", "mxfp8"])
+def test_chunked_block_dequant_is_bit_identical_to_one_pass(monkeypatch, fmt):
+ rows, cols = 300, 256
+ gen = torch.Generator().manual_seed(2)
+ if fmt == "nvfp4":
+ codes = torch.randint(0, 256, (rows, cols // 2), dtype = torch.uint8, generator = gen)
+ scale = torch.randint(40, 70, (rows, cols // 16), dtype = torch.uint8, generator = gen)
+ scale = scale.view(torch.float8_e4m3fn)
+ tensor_scale = torch.rand(rows, generator = gen) + 0.01 # per row, as a joined layer carries
+ else:
+ codes = torch.randint(0, 120, (rows, cols), dtype = torch.uint8, generator = gen)
+ codes = codes.view(torch.float8_e4m3fn)
+ scale = torch.randint(110, 140, (rows, cols // 32), dtype = torch.uint8, generator = gen)
+ tensor_scale = None
+ pqs = torch.rand(cols, generator = gen) + 0.5
+ # the pre-chunking formula, in one pass
+ if fmt == "nvfp4":
+ lut = torch.tensor(cb._E2M1 + tuple(-v for v in cb._E2M1), dtype = torch.float32)
+ c = codes.to(torch.int32)
+ values = torch.stack((lut[c & 0x0F], lut[c >> 4]), dim = -1).reshape(rows, -1, 16)
+ step = scale.to(torch.float32) * tensor_scale.to(torch.float32).reshape(-1, 1)
+ weight = (values * step.unsqueeze(-1)).reshape(rows, -1)
+ else:
+ exp = scale.view(torch.uint8).to(torch.float32) - cb._E8M0_BIAS
+ weight = (
+ codes.to(torch.float32).reshape(rows, -1, 32) * torch.exp2(exp).unsqueeze(-1)
+ ).reshape(rows, -1)
+ want = (weight * pqs.reshape(1, -1)).to(torch.bfloat16)
+ for chunk_bytes in (1, 7 * 4096, 1 << 30): # one row per chunk, uneven chunks, one pass
+ monkeypatch.setattr(cb, "_DEQUANT_CHUNK_BYTES", chunk_bytes, raising = False)
+ got = cb.dequant_block(
+ fmt, codes, scale, tensor_scale = tensor_scale, pre_quant_scale = pqs, dtype = torch.bfloat16
+ )
+ assert torch.equal(got, want), chunk_bytes
+
+
[email protected]("kind", ["int8_convrot", "fp8"])
+def test_int8_fp8_dequant_is_checked_for_its_float32_peak(monkeypatch, kind):
+ """int8 / fp8 dequantization holds float32 codes and their float32 product together (and ConvRot's
+ float32 matmul result); the check before it must cover the measured peak, not only the output."""
+ import threading
+ import time
+
+ import core.inference.diffusion_single_file_converters as conv
+
+ if _rss_anon_bytes() is None:
+ pytest.skip("needs /proc/self/status RssAnon")
+ rows, cols = 4096, 4096
+ gen = torch.Generator().manual_seed(3)
+ if kind == "int8_convrot":
+ codes = torch.randint(-127, 128, (rows, cols), dtype = torch.int8, generator = gen)
+ scale, group = torch.rand(rows, 1, generator = gen) / 127.0, 256
+ else:
+ codes = (torch.randn(rows, cols, generator = gen) * 50).to(torch.float8_e4m3fn)
+ scale, group = torch.tensor([0.01]), 0
+ seen = []
+ monkeypatch.setattr(conv, "charge_host_ram", lambda n: seen.append(int(n)))
+ peak, stop = [0], [False]
+
+ def sample():
+ while not stop[0]:
+ peak[0] = max(peak[0], _rss_anon_now())
+ time.sleep(0.0005)
+
+ _rss_anon_bytes()
+ start = _rss_anon_now()
+ thread = threading.Thread(target = sample, daemon = True)
+ thread.start()
+ out = cq._dequant(codes, scale, group, torch.bfloat16)
+ stop[0] = True
+ thread.join()
+ growth = peak[0] - start
+ assert out.shape == (rows, cols) and out.dtype == torch.bfloat16
+ assert seen and max(seen) >= 0.9 * growth, (seen, growth)
+
+
+def test_a_load_under_the_floor_is_checked_once_its_allocations_reach_it(block_file, monkeypatch):
+ """File and estimate both under the floor (the estimate assumed the mxfp8 runtime keeps every layer),
+ but the runtime filter rejects them all and they are dequantized: once those allocations reach the
+ floor the check must run."""
+ import os
+
+ conv = _tight_host(monkeypatch, headroom_mib = 0)
+ path, _tensors, _expected = block_file("mxfp8")
+ monkeypatch.setattr(conv, "HOST_RAM_CHECK_MIN_MIB", os.path.getsize(path) // (1 << 20) + 1)
+ with pytest.raises(conv.HostRamShortfallError, match = "needs at least"):
+ _load(path, dtype = torch.bfloat16, mxfp8_backend = "kept", min_features = 1 << 20)
+
+
+def test_swap_nibbles_is_bit_identical_and_checked_for_its_peak(monkeypatch):
+ import threading
+ import time
+
+ import core.inference.diffusion_single_file_converters as conv
+
+ gen = torch.Generator().manual_seed(4)
+ small = torch.randint(0, 256, (37, 19), dtype = torch.uint8, generator = gen)
+ for chunk_bytes in (1, 64, 1 << 30):
+ monkeypatch.setattr(cb, "_DEQUANT_CHUNK_BYTES", chunk_bytes, raising = False)
+ assert torch.equal(cb.swap_nibbles(small), ((small << 4) | (small >> 4)).to(torch.uint8))
+ monkeypatch.undo()
+ if _rss_anon_bytes() is None:
+ pytest.skip("needs /proc/self/status RssAnon")
+ packed = torch.randint(0, 256, (8192, 8192), dtype = torch.uint8, generator = gen)
+ seen = []
+ monkeypatch.setattr(conv, "charge_host_ram", lambda n: seen.append(int(n)))
+ peak, stop = [0], [False]
+
+ def sample():
+ while not stop[0]:
+ peak[0] = max(peak[0], _rss_anon_now())
+ time.sleep(0.0005)
+
+ _rss_anon_bytes()
+ start = _rss_anon_now()
+ thread = threading.Thread(target = sample, daemon = True)
+ thread.start()
+ out = cb.swap_nibbles(packed)
+ stop[0] = True
+ thread.join()
+ growth = peak[0] - start
+ assert out.shape == packed.shape
+ assert seen and max(seen) >= 0.9 * growth, (seen, growth)
+
+
+def test_untiling_padded_blocks_checks_both_live_copies(monkeypatch):
+ """With a block count that is not a multiple of 4 the permuted padded buffer and the trimmed copy are
+ live together; both are checked before either is made."""
+ import core.inference.diffusion_single_file_converters as conv
+
+ rows, blocks = 200, 6
+ plain = torch.randint(0, 255, (rows, blocks), dtype = torch.uint8)
+ tiled = cb.tile_scales(plain)
+ seen = []
+ monkeypatch.setattr(conv, "charge_host_ram", lambda n: seen.append(int(n)))
+ assert torch.equal(cb.untile_scales(tiled, rows, blocks), plain)
+ assert seen == [_ceil(rows, 128) * _ceil(blocks, 4) + rows * blocks]
diff --git a/studio/backend/tests/test_diffusion_single_file_host_ram.py b/studio/backend/tests/test_diffusion_single_file_host_ram.py
new file mode 100644
index 00000000000..c3ce4d19c23
--- /dev/null
+++ b/studio/backend/tests/test_diffusion_single_file_host_ram.py
@@ -0,0 +1,220 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""A single-file DiT widened on load beyond free host RAM is refused before widening (it used to OOM
+the app); files already at the compute dtype stay memory-mapped and are never refused."""
+
+from __future__ import annotations
+
+import re
+import sys
+from pathlib import Path
+
+import pytest
+import torch
+
+from core.inference import diffusion_comfy_quant as cq
+from core.inference import diffusion_single_file_converters as conv
+from core.inference import diffusion_small_host as small_host
+
+sys.path.insert(0, str(Path(__file__).resolve().parent))
+from test_diffusion_single_file_krea2_hunyuanimage import ( # noqa: E402
+ KREA2_CFG,
+ _class,
+ _tiny,
+ krea2_original,
+)
+
+safetensors_torch = pytest.importorskip("safetensors.torch")
+
+_LINEAR = re.compile(r"^blocks\.\d+\.(attn\.(wq|wk|wv|wo|gate)|mlp\.(gate|up|down))\.weight$")
+_KWARGS = {"torch_dtype": torch.bfloat16, "config": "krea/Krea-2-Turbo", "subfolder": "transformer"}
+
+
+def _write(tmp_path, kind):
+ model = _tiny("Krea2Transformer2DModel", KREA2_CFG)
+ tensors = {}
+ for key, value in krea2_original(model.state_dict()).items():
+ if kind != "bf16" and _LINEAR.match(key):
+ if kind == "fp8_scaled":
+ scale = value.abs().max().clamp_min(1e-8) / 448.0
+ tensors[key] = (value / scale).to(torch.float8_e4m3fn)
+ tensors[key[: -len(".weight")] + ".scale_weight"] = scale.reshape(1).float()
+ else:
+ tensors[key] = value.to(torch.float8_e4m3fn)
+ else:
+ tensors[key] = value.to(torch.bfloat16).contiguous()
+ if kind == "fp8_scaled":
+ tensors["scaled_fp8"] = torch.zeros(0, dtype = torch.float8_e4m3fn)
+ path = tmp_path / f"krea2_{kind}.safetensors"
+ safetensors_torch.save_file(tensors, str(path))
+ widened = sum(
+ v.numel() * 2 for k, v in tensors.items() if v.dtype == torch.float8_e4m3fn and v.numel()
+ )
+ return path, widened
+
+
+def krea2(monkeypatch):
+ cls = _class("Krea2Transformer2DModel")
+ monkeypatch.setattr(cls, "load_config", classmethod(lambda c, *a, **k: dict(KREA2_CFG)))
+ # The tiny model widens a few KB; price every byte so the real check runs on it.
+ monkeypatch.setattr(conv, "HOST_RAM_CHECK_MIN_MIB", 0, raising = False)
+ monkeypatch.delenv(small_host.HOST_RAM_CHECK_ENV, raising = False)
+ return cls
+
+
+def _host(
+ monkeypatch,
+ available_mib,
+ total_mib = 32768,
+):
+ monkeypatch.setattr(small_host, "host_ram_mib", lambda: (total_mib, available_mib))
+
+
+def _no_read(monkeypatch):
+ def boom(*a, **k):
+ raise AssertionError("the weights were read before the host RAM check")
+
+ monkeypatch.setattr(safetensors_torch, "load_file", boom)
+
+
+def test_fp8_file_widened_past_free_host_ram_is_refused_before_reading(
+ tmp_path, monkeypatch, krea2
+):
+ path, _ = _write(tmp_path, "fp8")
+ _host(monkeypatch, available_mib = 2048) # under the 3 GB reserve alone
+ _no_read(monkeypatch)
+ with pytest.raises(RuntimeError, match = r"Not enough system RAM to load krea2_fp8"):
+ conv.load_original_layout_transformer(krea2, str(path), dict(_KWARGS))
+
+
+def test_fp8_scaled_comfy_file_without_fp8_runtime_is_refused(tmp_path, monkeypatch, krea2):
+ path, _ = _write(tmp_path, "fp8_scaled")
+ scan = cq.refuse_comfy_quant(str(path))
+ assert scan is not None and scan.legacy_scaled_fp8
+ _host(monkeypatch, available_mib = 2048)
+ with pytest.raises(RuntimeError, match = "expanding its quantized weights"):
+ cq.load_comfy_quant_transformer(
+ krea2, str(path), scan, dict(_KWARGS), int8_backend = None, fp8_backend = None
+ )
+
+
+def test_same_files_load_when_the_host_has_room(tmp_path, monkeypatch, krea2):
+ _host(monkeypatch, available_mib = 64 * 1024)
+ path, _ = _write(tmp_path, "fp8")
+ model = conv.load_original_layout_transformer(krea2, str(path), dict(_KWARGS))
+ assert model.transformer_blocks[0].attn.to_q.weight.dtype == torch.bfloat16
+ path, _ = _write(tmp_path, "fp8_scaled")
+ scan = cq.refuse_comfy_quant(str(path))
+ model = cq.load_comfy_quant_transformer(
+ krea2, str(path), scan, dict(_KWARGS), int8_backend = None, fp8_backend = None
+ )
+ assert model.transformer_blocks[0].attn.to_q.weight.dtype == torch.bfloat16
+
+
+def test_bf16_file_stays_mapped_and_is_never_refused(tmp_path, monkeypatch, krea2):
+ """A bf16 file at a bf16 compute dtype writes no new host memory (only the fp32-kept norms)."""
+ path, _ = _write(tmp_path, "bf16")
+ need = conv.converted_host_bytes(
+ str(path), torch.bfloat16, keep_fp32 = krea2._keep_in_fp32_modules
+ )
+ sizes = path.stat().st_size
+ assert need < sizes // 10
+ monkeypatch.setattr(conv, "HOST_RAM_CHECK_MIN_MIB", 2) # its few KB stay under any real floor
+ _host(monkeypatch, available_mib = 0)
+ conv.load_original_layout_transformer(krea2, str(path), dict(_KWARGS))
+
+
+def test_widened_bytes_count_the_fp8_weights_at_bf16(tmp_path):
+ path, widened = _write(tmp_path, "fp8")
+ need = conv.converted_host_bytes(str(path), torch.bfloat16)
+ assert need == widened
+ # fp32 compute (CPU) widens the bf16 tensors too
+ assert conv.converted_host_bytes(str(path), torch.float32) > 2 * widened
+
+
+def test_kill_switch_and_unreadable_ram_never_refuse(tmp_path, monkeypatch, krea2):
+ path, _ = _write(tmp_path, "fp8")
+ _host(monkeypatch, available_mib = 1)
+ monkeypatch.setenv(small_host.HOST_RAM_CHECK_ENV, "0")
+ conv.load_original_layout_transformer(krea2, str(path), dict(_KWARGS))
+ monkeypatch.delenv(small_host.HOST_RAM_CHECK_ENV)
+ _host(monkeypatch, available_mib = None)
+ conv.load_original_layout_transformer(krea2, str(path), dict(_KWARGS))
+
+
+def _spy_need(monkeypatch):
+ """The header estimate each load checks up front, recorded."""
+ seen = []
+ real = conv.HostRamBudget.check
+
+ def spy(self, need_bytes):
+ seen.append(need_bytes)
+ return real(self, need_bytes)
+
+ monkeypatch.setattr(conv.HostRamBudget, "check", spy)
+ return seen
+
+
+def test_fp16_pipeline_counts_the_deferred_dequantization(tmp_path, monkeypatch, krea2):
+ """fp16 with ``_keep_in_fp32_modules`` defers the dtype choice until after key conversion, but
+ with no fp8 runtime (always the case off bf16) every fp8 layer is still expanded to fp16."""
+ path, widened = _write(tmp_path, "fp8_scaled")
+ scan = cq.refuse_comfy_quant(str(path))
+ seen = _spy_need(monkeypatch)
+ _host(monkeypatch, available_mib = 64 * 1024)
+ model = cq.load_comfy_quant_transformer(
+ krea2,
+ str(path),
+ scan,
+ {**_KWARGS, "torch_dtype": torch.float16},
+ int8_backend = None,
+ fp8_backend = None,
+ )
+ assert model.transformer_blocks[0].attn.to_q.weight.dtype == torch.float16
+ # Everything else in the file is bf16, widened to fp16 (or fp32 for the kept norms) as well.
+ keep = krea2._keep_in_fp32_modules
+ rest = sum(
+ v.numel() * (4 if any(m in k.split(".") for m in keep) else 2)
+ for k, v in safetensors_torch.load_file(str(path)).items()
+ if v.dtype == torch.bfloat16
+ )
+ assert seen and seen[0] >= widened + rest
+
+
+def test_fnuz_float8_weights_are_priced_as_widened(tmp_path):
+ """ROCm FNUZ float8 tensors are widened by ``value.to(want)`` like any other float8."""
+ model = _tiny("Krea2Transformer2DModel", KREA2_CFG)
+ tensors = {}
+ for key, value in krea2_original(model.state_dict()).items():
+ if _LINEAR.match(key):
+ tensors[key] = value.to(torch.float8_e4m3fnuz)
+ else:
+ tensors[key] = value.to(torch.bfloat16).contiguous()
+ path = tmp_path / "krea2_fnuz.safetensors"
+ safetensors_torch.save_file(tensors, str(path))
+ widened = sum(v.numel() * 2 for v in tensors.values() if v.dtype == torch.float8_e4m3fnuz)
+ assert conv.converted_host_bytes(str(path), torch.bfloat16) == widened
+
+
[email protected]("kind", ["fp8", "fp8_scaled"])
+def test_kill_switch_charges_nothing(tmp_path, monkeypatch, krea2, kind):
+ """``UNSLOTH_DIFFUSION_HOST_RAM_CHECK=0`` installs no budget, so no helper charges one."""
+ path, _ = _write(tmp_path, kind)
+ charged = []
+ monkeypatch.setattr(conv.HostRamBudget, "charge", lambda self, n: charged.append(n))
+ monkeypatch.setenv(small_host.HOST_RAM_CHECK_ENV, "0")
+ _host(monkeypatch, available_mib = 1)
+ if kind == "fp8":
+ conv.load_original_layout_transformer(krea2, str(path), dict(_KWARGS))
+ else:
+ cq.load_comfy_quant_transformer(
+ krea2,
+ str(path),
+ cq.refuse_comfy_quant(str(path)),
+ dict(_KWARGS),
+ int8_backend = None,
+ fp8_backend = None,
+ )
+ assert charged == []
diff --git a/studio/backend/tests/test_video_comfy_quant.py b/studio/backend/tests/test_video_comfy_quant.py
index 2abda5d8a0e..68028862659 100644
--- a/studio/backend/tests/test_video_comfy_quant.py
+++ b/studio/backend/tests/test_video_comfy_quant.py
@@ -742,3 +742,234 @@ def test_offload_only_int8_is_priced_dense_for_a_resident_plan(monkeypatch, tmp_
monkeypatch.setattr(vid, "comfy_fp8_backend", lambda *a, **k: None)
assert vid._video_comfy_resident_mib(fam, "b", None, path, scan) == 3
assert vid._video_comfy_resident_mib(fam, "b", None, path, scan, offload = True) == 2
+
+
+def _record_host_ram_checks(monkeypatch):
+ """Every pre-allocation host RAM check a load makes, by size, on a host with room for all of them."""
+ import core.inference.diffusion_single_file_converters as conv
+ import core.inference.diffusion_small_host as small_host
+
+ monkeypatch.setattr(conv, "HOST_RAM_CHECK_MIN_MIB", 0)
+ monkeypatch.delenv(small_host.HOST_RAM_CHECK_ENV, raising = False)
+ monkeypatch.setattr(small_host, "host_ram_mib", lambda: (1 << 20, 1 << 20))
+ seen = []
+ monkeypatch.setattr(conv.HostRamBudget, "charge", lambda self, n: seen.append(int(n)))
+ return seen
+
+
+def test_a_key_map_row_reorder_is_checked_before_it_is_copied(h3like_file, monkeypatch):
+ """MiniMax-H3's fc1 swaps its [gate; value] halves, so the kept int8 codes are rebuilt with
+ torch.cat: a full copy of the layer that must be checked against free host RAM first."""
+ seen = _record_host_ram_checks(monkeypatch)
+ path, _dense, tensors = h3like_file
+ _load_h3like(path, int8_backend = "native")
+ fc1 = tensors["fc1.weight"]
+ assert fc1.numel() * fc1.element_size() in seen
+
+
+def test_a_stock_converter_row_reorder_of_kept_codes_is_checked(h3like_file, monkeypatch):
+ """No key map: a diffusers-style converter that swaps a gated layer's halves (Mochi's mlp_x.w1) makes
+ the loader rebuild the kept int8 codes with torch.cat, a full copy checked before it is made."""
+
+ def convert(checkpoint = None, **_kwargs):
+ out = {}
+ for key, value in checkpoint.items():
+ if key == "attn.qkv.weight":
+ for part, chunk in zip(("to_q", "to_k", "to_v"), value.chunk(3)):
+ out[f"attn.{part}.weight"] = chunk
+ elif key == "fc1.weight":
+ gate, val = value.chunk(2)
+ out["ff.proj.weight"] = torch.cat([val, gate])
+ else:
+ out[key] = value
+ return out
+
+ monkeypatch.setattr(
+ cq,
+ "_mapping",
+ lambda cls: (
+ convert,
+ types.SimpleNamespace(
+ _should_convert_state_dict_to_diffusers = lambda a, b: set(a) != set(b),
+ _get_mapping_function_kwargs = lambda fn, **kw: {},
+ ),
+ ),
+ )
+ seen = _record_host_ram_checks(monkeypatch)
+ path, _dense, tensors = h3like_file
+ model = cq.load_comfy_quant_transformer(
+ _H3Like,
+ path,
+ cq.refuse_comfy_quant(path),
+ {"torch_dtype": torch.bfloat16, "config": "base/repo"},
+ family = "minimax-h3",
+ int8_backend = "native",
+ keep_dtype = lambda key: torch.float32 if key.startswith("head.") else None,
+ )
+ assert model._unsloth_comfy_quant["int8"] == 4
+ fc1 = tensors["fc1.weight"]
+ assert any(n >= fc1.numel() * fc1.element_size() for n in seen), seen
+
+
+def test_a_host_ram_refusal_in_the_narrow_pass_is_not_retried_at_full_width(
+ h3like_file, monkeypatch
+):
+ """The narrow-tag conversion pass retries at full width on any failure it cannot prove, but a host RAM
+ refusal is final: the full-width float64 tags (and a converter's unchecked joins over them) would only
+ allocate more."""
+ import core.inference.diffusion_single_file_converters as conv
+ import core.inference.diffusion_small_host as small_host
+
+ calls = []
+
+ def convert(checkpoint = None, **_kwargs):
+ calls.append(1)
+ out = {}
+ for key, value in checkpoint.items():
+ if key == "attn.qkv.weight":
+ for part, chunk in zip(("to_q", "to_k", "to_v"), value.chunk(3)):
+ out[f"attn.{part}.weight"] = chunk
+ elif key == "fc1.weight":
+ gate, val = value.chunk(2)
+ out["ff.proj.weight"] = torch.cat([val, gate])
+ else:
+ out[key] = value
+ return out
+
+ monkeypatch.setattr(
+ cq,
+ "_mapping",
+ lambda cls: (
+ convert,
+ types.SimpleNamespace(
+ _should_convert_state_dict_to_diffusers = lambda a, b: set(a) != set(b),
+ _get_mapping_function_kwargs = lambda fn, **kw: {},
+ ),
+ ),
+ )
+ monkeypatch.setattr(conv, "HOST_RAM_CHECK_MIN_MIB", 0)
+ monkeypatch.delenv(small_host.HOST_RAM_CHECK_ENV, raising = False)
+ monkeypatch.setattr(small_host, "host_ram_mib", lambda: (1 << 20, 1 << 20))
+ path, _dense, tensors = h3like_file
+ fc1_bytes = tensors["fc1.weight"].numel()
+
+ def charge(self, n):
+ if n >= fc1_bytes: # the kept fc1 reorder does not fit
+ raise conv.HostRamShortfallError("Not enough system RAM to load h3like.safetensors")
+
+ monkeypatch.setattr(conv.HostRamBudget, "charge", charge)
+ with pytest.raises(conv.HostRamShortfallError):
+ cq.load_comfy_quant_transformer(
+ _H3Like,
+ path,
+ cq.refuse_comfy_quant(path),
+ {"torch_dtype": torch.bfloat16, "config": "base/repo"},
+ family = "minimax-h3",
+ int8_backend = "native",
+ )
+ assert len(calls) == 1 # refused in the narrow pass, never converted again at full width
+
+
+def test_the_up_front_estimate_skips_tensors_the_key_filter_never_reads(tmp_path, monkeypatch):
+ """A bundled checkpoint (LTX-2.3 / LTX-2.5) is read through ``keep_key``: only the DiT. Its VAE stored in
+ float32 must not be priced as widened to the compute dtype and refuse a DiT load that fits."""
+ import core.inference.diffusion_single_file_converters as conv
+ import core.inference.diffusion_small_host as small_host
+
+ torch.manual_seed(3)
+ dense = _H3Like()
+ tensors = {"head.weight": dense.head.weight.detach(), "head.bias": dense.head.bias.detach()}
+ for name, w in (("attn.to_q", dense.attn.to_q.weight), ("ff.proj", dense.ff.proj.weight)):
+ q, s = _int8(w.detach())
+ tensors[f"{name}.weight"], tensors[f"{name}.weight_scale"] = q, s
+ tensors[f"{name}.comfy_quant"] = _conf(format = "int8_tensorwise")
+ tensors["attn.to_k.weight"] = dense.attn.to_k.weight.detach()
+ tensors["attn.to_v.weight"] = dense.attn.to_v.weight.detach()
+ tensors["vae.decoder.weight"] = torch.zeros(2048, 2048) # 16 MiB fp32, 8 MiB widened to bf16
+ path = _save(tmp_path / "bundled.safetensors", tensors)
+ monkeypatch.setattr(
+ cq,
+ "_mapping",
+ lambda cls: (
+ lambda checkpoint = None, **_kw: checkpoint,
+ types.SimpleNamespace(
+ _should_convert_state_dict_to_diffusers = lambda a, b: False,
+ _get_mapping_function_kwargs = lambda fn, **kw: {},
+ ),
+ ),
+ )
+ monkeypatch.setattr(conv, "HOST_RAM_CHECK_MIN_MIB", 0)
+ monkeypatch.delenv(small_host.HOST_RAM_CHECK_ENV, raising = False)
+ total = 1 << 20
+ monkeypatch.setattr(
+ small_host, "host_ram_mib", lambda: (total, small_host.host_reserve_mib(total) + 4)
+ )
+ model = cq.load_comfy_quant_transformer(
+ _H3Like,
+ path,
+ cq.refuse_comfy_quant(path),
+ {"torch_dtype": torch.bfloat16, "config": "base/repo"},
+ int8_backend = None,
+ keep_key = lambda key: not key.startswith("vae."),
+ )
+ assert model.attn.to_q.weight.dtype == torch.bfloat16
+
+
+def test_a_full_width_tag_retry_that_does_not_fit_is_refused_before_converting(
+ h3like_file, monkeypatch
+):
+ """The narrow-tag pass failing for an ordinary reason retries at full float64 width, which a converter
+ can materialize at 8 bytes per weight element before any checked helper runs: that peak is checked
+ first, and a retry that does not fit is refused without calling the converter again."""
+ import core.inference.diffusion_single_file_converters as conv
+ import core.inference.diffusion_small_host as small_host
+
+ calls = []
+
+ def convert(checkpoint = None, **_kwargs):
+ calls.append(1)
+ if len(calls) == 1:
+ raise ValueError("narrow tags could not be proven")
+ out = {}
+ for key, value in checkpoint.items():
+ if key == "attn.qkv.weight":
+ for part, chunk in zip(("to_q", "to_k", "to_v"), value.chunk(3)):
+ out[f"attn.{part}.weight"] = chunk
+ elif key == "fc1.weight":
+ out["ff.proj.weight"] = value
+ else:
+ out[key] = value
+ return out
+
+ monkeypatch.setattr(
+ cq,
+ "_mapping",
+ lambda cls: (
+ convert,
+ types.SimpleNamespace(
+ _should_convert_state_dict_to_diffusers = lambda a, b: set(a) != set(b),
+ _get_mapping_function_kwargs = lambda fn, **kw: {},
+ ),
+ ),
+ )
+ monkeypatch.setattr(conv, "HOST_RAM_CHECK_MIN_MIB", 0)
+ monkeypatch.delenv(small_host.HOST_RAM_CHECK_ENV, raising = False)
+ monkeypatch.setattr(small_host, "host_ram_mib", lambda: (1 << 20, 1 << 20))
+ path, _dense, tensors = h3like_file
+ tagged = tensors["attn.qkv.weight"].numel() + tensors["fc1.weight"].numel()
+
+ def charge(self, n):
+ if n >= 8 * tagged: # the full-width tags do not fit
+ raise conv.HostRamShortfallError("Not enough system RAM to load h3like.safetensors")
+
+ monkeypatch.setattr(conv.HostRamBudget, "charge", charge)
+ with pytest.raises(conv.HostRamShortfallError):
+ cq.load_comfy_quant_transformer(
+ _H3Like,
+ path,
+ cq.refuse_comfy_quant(path),
+ {"torch_dtype": torch.bfloat16, "config": "base/repo"},
+ family = "minimax-h3",
+ int8_backend = "native",
+ )
+ assert len(calls) == 1 # refused before the full-width conversion ran