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: budget a pre-cast fp8 text encoder at the size it actually loads (#8218)

Daniel Hanf12ab6bb7fc6
diff --git a/studio/backend/core/inference/diffusion_te_prequant.py b/studio/backend/core/inference/diffusion_te_prequant.py
index f755e5531a1..72ca0543447 100644
--- a/studio/backend/core/inference/diffusion_te_prequant.py
+++ b/studio/backend/core/inference/diffusion_te_prequant.py
@@ -44,6 +44,52 @@ TE_PREQUANT_SCHEMES = ("fp8",)
# Components the pipeline-assembly injection covers (text_encoder_4 is family-assembled separately, see diffusion_hidream.py).
TE_PREQUANT_COMPONENTS = ("text_encoder", "text_encoder_2", "text_encoder_3")
+# Fraction of a bf16 text encoder a PRE-CAST fp8 checkpoint occupies, for memory budgeting.
+#
+# fp8 storage is one byte per parameter against bf16's two, so the floor is 0.5, but the cast
+# deliberately keeps modules dense: nn.Embedding tables, the norms in
+# DEFAULT_SKIP_MODULES_PATTERN, the encoder's own _keep_in_fp32_modules (T5's ``wo``) and an
+# lm_head tied to the input embedding. Measured from Hub file metadata over every published
+# artifact (2026-08-07), as hosted checkpoint bytes over the bf16-EQUIVALENT dense bytes of the
+# same component (an fp32-stored encoder is halved first, since the pipeline loads it bf16):
+#
+# FLUX.2-dev text_encoder Mistral-24B 24,683,130,873 / 48,022,800,560 = 0.514
+# HiDream-I1-Full text_encoder_4 Llama-3.1-8B 8,555,963,320 / 16,060,556,376 = 0.533
+# Qwen-Image text_encoder Qwen2.5-VL-7B 8,839,210,073 / 16,584,414,544 = 0.533
+# LTX-2 text_encoder Gemma3-12B 13,205,302,695 / 24,374,720,836 = 0.542
+# Krea-2-Turbo text_encoder Qwen3-4B 4,831,262,424 / 8,875,715,136 = 0.544
+# Z-Image-Turbo text_encoder Qwen3-4B 4,411,751,967 / 8,044,982,000 = 0.548
+# Lumina-Image-2.0 text_encoder Gemma2-2B 3,204,501,909 / 5,228,699,608 = 0.613
+# FLUX.1-schnell text_encoder_2 T5-XXL 5,900,818,800 / 9,524,648,584 = 0.620
+#
+# The small encoders sit highest: their embedding tables are a large share of the parameters and
+# stay dense. 0.65 is the observed maximum rounded up, so this OVER-states every measured
+# encoder rather than under-stating any. It is a memory budget, and an under-estimate is the
+# expensive direction: it lets an oversized load through to the OS killer.
+TE_PREQUANT_BUDGET_SCALE = 0.65
+
+
+def te_prequant_budget_scale(fam: Any, *, te_quant_mode: Optional[str], target: Any) -> float:
+ """Scale to apply to a family's bf16 text-encoder size when budgeting memory for this pick:
+ ``TE_PREQUANT_BUDGET_SCALE`` when the load takes its encoder PRE-CAST from a hosted fp8
+ checkpoint, else 1.0.
+
+ Keyed on ``te_prequant_sources`` -- the same pure resolver the download plan and the load
+ itself use, so a budget can never disagree with them about what gets loaded -- and NOT on
+ ``text_encoder_quant`` alone. That distinction is the conservative one: the runtime cast
+ (``quantize_text_encoders``) runs *after* pipeline assembly has already materialised the
+ dense encoder, so its steady state is fp8 but its peak is bf16, and the peak is what a
+ budget has to cover. Only the pre-cast path is fp8-sized end to end.
+
+ Best-effort like the rest of this module: anything unresolvable returns 1.0, i.e. today's
+ bf16 budget."""
+ try:
+ sources = te_prequant_sources(fam, te_quant_mode = te_quant_mode, target = target)
+ except Exception: # noqa: BLE001 -- an unresolvable pre-cast just means the dense encoder
+ return 1.0
+ return TE_PREQUANT_BUDGET_SCALE if sources else 1.0
+
+
# Bases whose text-encoder weights are VERIFIED byte-identical (every shard LFS sha256 compared on 2026-07-18), so one hosted artifact serves them all. The validator accepts a base_model_id from the same group; anything else keeps the strict refusal.
_TE_EQUIVALENT_BASES: tuple[frozenset[str], ...] = (
# Qwen2.5-VL-7B text encoder: 4 shards, 16,584,414,544 bytes, identical sha256 set.
diff --git a/studio/backend/core/inference/video.py b/studio/backend/core/inference/video.py
index e8718bcb2e4..e771949ff82 100644
--- a/studio/backend/core/inference/video.py
+++ b/studio/backend/core/inference/video.py
@@ -1298,79 +1298,108 @@ class VideoBackend:
device_memory = snapshot_device_memory(target)
components = fam.bf16_components_gb
mib_per_gb = 1000.0**3 / (1024.0 * 1024.0)
- if kind == "pipeline":
- model_dense_mib = (
- int(sum(components) * mib_per_gb * dtype_scale) if components is not None else None
- )
- companion_mib = None
- else:
+ # bf16_components_gb is (transformer, text_encoder, vae) at bf16. When this pick takes its
+ # encoder PRE-CAST from a hosted fp8 checkpoint, the bf16 entry over-states what is loaded
+ # by ~11 GB for ltx-2's Gemma3-12B, which drags every budget below with it. The VAE is
+ # never quantised (quantize_text_encoders touches text encoders only, and vae_force_fp32
+ # families widen it), so only components[1] is scaled.
+ from .diffusion_te_prequant import te_prequant_budget_scale
+
+ te_scale = te_prequant_budget_scale(fam, te_quant_mode = text_encoder_quant, target = target)
+ transformer_mib: Optional[int] = None
+ if kind != "pipeline":
checkpoint_path = self._resolve_checkpoint_path(repo_id, gguf_filename, hf_token)
size_mib = file_size_mib(str(checkpoint_path))
- model_dense_mib = None
if kind == "gguf":
transformer_mib = estimate_gguf_resident_mib(size_mib)
else:
transformer_mib = estimate_safetensors_dense_mib(size_mib)
if transformer_mib is not None:
transformer_mib = int(transformer_mib * dtype_scale)
- companion_mib = (
- int((components[1] + components[2]) * mib_per_gb * dtype_scale)
- if components is not None
- else None
- )
- # Budget ALL weights: companions stay resident, so budgeting the transformer alone lets auto pick OFFLOAD_NONE and OOM.
- model_dense_mib = (
- transformer_mib + (companion_mib or 0) if transformer_mib is not None else None
- )
runtime_mib = estimate_video_runtime_mib(
width = fam.resolution_presets[0][0],
height = fam.resolution_presets[0][1],
num_frames = fam.default_num_frames,
)
- plan = plan_diffusion_memory(
- target = target,
- device_memory = device_memory,
- model_dense_mib = model_dense_mib,
- runtime_headroom_mib = runtime_mib,
- companion_dense_mib = companion_mib,
- requested_mode = normalize_memory_mode(memory_mode),
- )
- # Parity with the image dense-quant path: the bf16-table plan can force offload a quantised DiT would not need, so re-plan with the scheme factor and keep resident if it fits.
- bf16_plan = plan
- quant_replanned = False
- if (
- kind == "pipeline"
- and plan.offload_policy != "none"
- and normalize_transformer_quant(transformer_quant) is not None
- and dense_transformer_supported(target)
- and components is not None
- ):
- scheme_preview = select_transformer_quant_scheme(
- target, transformer_quant, family = fam.name
- )
- factor = _QUANT_STEADY_FACTOR.get(scheme_preview) if scheme_preview else None
- if factor is not None:
- quant_mib = int(
- (components[0] * factor + components[1] + components[2]) * mib_per_gb
+
+ def _plan_for_te_scale(scale: float, *, log: bool) -> tuple[Any, Any, bool]:
+ """``(plan, bf16_plan, quant_replanned)`` for a text-encoder budget of ``scale`` x
+ its bf16 size. Pure and cheap (``plan_diffusion_memory`` is arithmetic), so the
+ dense-encoder plan can be rebuilt below if the pre-cast injection does not land."""
+ text_encoder_gb = components[1] * scale if components is not None else 0.0
+ companions_gb = text_encoder_gb + components[2] if components is not None else 0.0
+ if log and scale != 1.0 and components is not None:
+ logger.info(
+ "video.te_prequant_budget: budgeting the pre-cast %s text encoder at %.2f of "
+ "bf16 (%.1f GB instead of %.1f GB)",
+ text_encoder_quant,
+ scale,
+ text_encoder_gb,
+ components[1],
+ )
+ if kind == "pipeline":
+ model_dense_mib = (
+ int((components[0] + companions_gb) * mib_per_gb * dtype_scale)
+ if components is not None
+ else None
)
- replanned = plan_diffusion_memory(
- target = target,
- device_memory = device_memory,
- model_dense_mib = quant_mib,
- runtime_headroom_mib = runtime_mib,
- companion_dense_mib = None,
- requested_mode = normalize_memory_mode(memory_mode),
+ companion_mib = None
+ else:
+ companion_mib = (
+ int(companions_gb * mib_per_gb * dtype_scale)
+ if components is not None
+ else None
+ )
+ # Budget ALL weights: companions stay resident, so budgeting the transformer alone lets auto pick OFFLOAD_NONE and OOM.
+ model_dense_mib = (
+ transformer_mib + (companion_mib or 0) if transformer_mib is not None else None
+ )
+ planned = plan_diffusion_memory(
+ target = target,
+ device_memory = device_memory,
+ model_dense_mib = model_dense_mib,
+ runtime_headroom_mib = runtime_mib,
+ companion_dense_mib = companion_mib,
+ requested_mode = normalize_memory_mode(memory_mode),
+ )
+ # Parity with the image dense-quant path: the bf16-table plan can force offload a quantised DiT would not need, so re-plan with the scheme factor and keep resident if it fits.
+ dense_plan = planned
+ replanned_for_quant = False
+ if (
+ kind == "pipeline"
+ and planned.offload_policy != "none"
+ and normalize_transformer_quant(transformer_quant) is not None
+ and dense_transformer_supported(target)
+ and components is not None
+ ):
+ scheme_preview = select_transformer_quant_scheme(
+ target, transformer_quant, family = fam.name
)
- if replanned.offload_policy == "none":
- logger.info(
- "video.transformer_quant: %s fits resident (%d MiB steady); "
- "dropping the bf16 plan's '%s' offload",
- scheme_preview,
- quant_mib,
- plan.offload_policy,
+ factor = _QUANT_STEADY_FACTOR.get(scheme_preview) if scheme_preview else None
+ if factor is not None:
+ quant_mib = int((components[0] * factor + companions_gb) * mib_per_gb)
+ replanned = plan_diffusion_memory(
+ target = target,
+ device_memory = device_memory,
+ model_dense_mib = quant_mib,
+ runtime_headroom_mib = runtime_mib,
+ companion_dense_mib = None,
+ requested_mode = normalize_memory_mode(memory_mode),
)
- plan = replanned
- quant_replanned = True
+ if replanned.offload_policy == "none":
+ if log:
+ logger.info(
+ "video.transformer_quant: %s fits resident (%d MiB steady); "
+ "dropping the bf16 plan's '%s' offload",
+ scheme_preview,
+ quant_mib,
+ planned.offload_policy,
+ )
+ planned = replanned
+ replanned_for_quant = True
+ return planned, dense_plan, replanned_for_quant
+
+ plan, bf16_plan, quant_replanned = _plan_for_te_scale(te_scale, log = True)
# ── build the pipeline.
pipeline_cls = getattr(diffusers, fam.pipeline_class)
@@ -1385,17 +1414,27 @@ class VideoBackend:
# A hosted pre-cast fp8 text encoder skips the dense TE download (for LTX Gemma3-27B, ~50 GB). The cast re-applies idempotently.
from .diffusion_te_prequant import te_prequant_pipe_kwargs
- pipe_kwargs.update(
- te_prequant_pipe_kwargs(
- fam,
- repo_id if kind == "pipeline" else base,
- te_quant_mode = text_encoder_quant,
- target = target,
- dtype = dtype,
- hf_token = hf_token,
- logger = logger,
- )
+ te_injected = te_prequant_pipe_kwargs(
+ fam,
+ repo_id if kind == "pipeline" else base,
+ te_quant_mode = text_encoder_quant,
+ target = target,
+ dtype = dtype,
+ hf_token = hf_token,
+ logger = logger,
)
+ pipe_kwargs.update(te_injected)
+ # The fp8-sized budget is valid only once the pre-cast encoder is actually in hand. Injection is best-effort
+ # (an unreachable / corrupt / base-mismatched checkpoint falls back to the dense encoder), and a dense encoder
+ # under an fp8 budget under-states the resident requirement by ~11 GB for ltx-2, which is the direction that
+ # OOMs. Placement is applied post-assembly (apply_memory_plan below), so re-plan at bf16 here, exactly as the
+ # dense-quant fallback below restores bf16_plan.
+ if te_scale != 1.0 and not te_injected:
+ logger.warning(
+ "video.te_prequant_budget: no pre-cast encoder was injected; re-planning "
+ "memory at the dense bf16 text-encoder size"
+ )
+ plan, bf16_plan, quant_replanned = _plan_for_te_scale(1.0, log = False)
# Injection is best-effort (a missing checkpoint falls back to the dense encoder), but the scoped pre-download already dropped those
# shards and from_pretrained cannot re-fetch from a local snapshot dir, so top them up here. ltx23 never reaches this: it gets the hub id.
missing_dense = [c for c in (_te_prequant_skipped or ()) if c not in pipe_kwargs]
diff --git a/studio/backend/tests/test_diffusion_te_prequant.py b/studio/backend/tests/test_diffusion_te_prequant.py
index 4553d68d40a..50d6242a01c 100644
--- a/studio/backend/tests/test_diffusion_te_prequant.py
+++ b/studio/backend/tests/test_diffusion_te_prequant.py
@@ -602,3 +602,88 @@ def test_builder_metadata_survives_weights_only_load(tmp_path):
if not isinstance(torch.__version__, str):
with pytest.raises(Exception):
torch.load(bad_path, weights_only = True, map_location = "cpu")
+
+
+# ── memory budgeting ─────────────────────────────────────────────────────────
+# Hosted checkpoint bytes over bf16-equivalent dense bytes, read from Hub file metadata on
+# 2026-08-07. The budget constant is a CEILING over these, so it can never under-state a
+# pre-cast encoder; PR #8213 gates a hard load refusal on the number this feeds.
+_MEASURED_FP8_RATIOS = {
+ "flux.2-dev/text_encoder": (24_683_130_873, 48_022_800_560),
+ "hidream-i1-full/text_encoder_4": (8_555_963_320, 16_060_556_376),
+ "qwen-image/text_encoder": (8_839_210_073, 16_584_414_544),
+ "ltx-2/text_encoder": (13_205_302_695, 24_374_720_836),
+ "krea-2-turbo/text_encoder": (4_831_262_424, 8_875_715_136),
+ "z-image-turbo/text_encoder": (4_411_751_967, 8_044_982_000),
+ "lumina-image-2.0/text_encoder": (3_204_501_909, 5_228_699_608),
+ "flux.1-schnell/text_encoder_2": (5_900_818_800, 9_524_648_584),
+}
+
+
+def test_budget_scale_over_states_every_measured_artifact():
+ worst = max(fp8 / dense for fp8, dense in _MEASURED_FP8_RATIOS.values())
+ # Conservative by construction: budget at or above the largest realized artifact...
+ assert tpq.TE_PREQUANT_BUDGET_SCALE >= worst
+ # ...and still below bf16, or the fix does nothing.
+ assert tpq.TE_PREQUANT_BUDGET_SCALE < 1.0
+ # fp8 storage is one byte per parameter against bf16's two, so nothing can come in under 0.5.
+ assert min(fp8 / dense for fp8, dense in _MEASURED_FP8_RATIOS.values()) > 0.5
+
+
+def test_budget_scale_applies_only_when_a_pre_cast_checkpoint_resolves(monkeypatch):
+ import core.inference.diffusion_precision as precision
+
+ monkeypatch.setattr(precision, "te_quant_supported", lambda target, mode: True)
+ hosted = _fam(te_prequant_repos = (("fp8", "text_encoder", "org/hosted"),))
+ assert (
+ tpq.te_prequant_budget_scale(hosted, te_quant_mode = "fp8", target = _target())
+ == tpq.TE_PREQUANT_BUDGET_SCALE
+ )
+ # No hosted checkpoint: the encoder is downloaded dense and cast in place AFTER assembly, so
+ # its peak is bf16 and the budget must stay bf16.
+ assert tpq.te_prequant_budget_scale(_fam(), te_quant_mode = "fp8", target = _target()) == 1.0
+ # Not requested, or a scheme with no hosted artifact.
+ for mode in (None, "", "off", "int8", "fp8_dynamic", "nvfp4"):
+ assert tpq.te_prequant_budget_scale(hosted, te_quant_mode = mode, target = _target()) == 1.0
+
+
+def test_budget_scale_is_bf16_when_the_device_cannot_quantise(monkeypatch):
+ import core.inference.diffusion_precision as precision
+
+ hosted = _fam(te_prequant_repos = (("fp8", "text_encoder", "org/hosted"),))
+ monkeypatch.setattr(precision, "te_quant_supported", lambda target, mode: False)
+ assert tpq.te_prequant_budget_scale(hosted, te_quant_mode = "fp8", target = _target()) == 1.0
+
+
+def test_budget_scale_fails_open_to_bf16(monkeypatch):
+ # An unresolvable pick keeps today's (larger) budget rather than guessing small.
+ def _boom(*args, **kwargs):
+ raise RuntimeError("hub down")
+
+ monkeypatch.setattr(tpq, "te_prequant_sources", _boom)
+ assert tpq.te_prequant_budget_scale(_fam(), te_quant_mode = "fp8", target = _target()) == 1.0
+
+
+def test_shipped_video_and_image_families_resolve_the_scale(monkeypatch):
+ import core.inference.diffusion_precision as precision
+ from core.inference.diffusion_families import detect_family
+ from core.inference.video_families import detect_video_family
+
+ monkeypatch.setattr(precision, "te_quant_supported", lambda target, mode: True)
+ scale = tpq.TE_PREQUANT_BUDGET_SCALE
+ # ltx-2 hosts its Gemma3-12B encoder pre-cast; the Wan families do not.
+ for repo, expected in (
+ ("Lightricks/LTX-2", scale),
+ ("Wan-AI/Wan2.2-TI2V-5B-Diffusers", 1.0),
+ ("Wan-AI/Wan2.2-T2V-A14B-Diffusers", 1.0),
+ ):
+ fam = detect_video_family(repo)
+ assert tpq.te_prequant_budget_scale(fam, te_quant_mode = "fp8", target = _target()) == (
+ expected
+ ), repo
+ assert (
+ tpq.te_prequant_budget_scale(
+ detect_family("Qwen/Qwen-Image"), te_quant_mode = "fp8", target = _target()
+ )
+ == scale
+ )
diff --git a/studio/backend/tests/test_video_backend.py b/studio/backend/tests/test_video_backend.py
index f4a400dd256..dc172cb3ce7 100644
--- a/studio/backend/tests/test_video_backend.py
+++ b/studio/backend/tests/test_video_backend.py
@@ -2441,3 +2441,206 @@ def test_attention_trim_skipped_for_static_shape_and_off_tiers(fake_runtime, mon
assert status["loaded"] is True, mode
assert calls == [], mode
assert "hunyuan_attn_trim" not in status["speed_optims"], mode
+
+
+# ── text-encoder budgeting ───────────────────────────────────────────────────
+# The plan sizes companions from the family's bf16 (transformer, text_encoder, vae) table. A pick
+# that takes its encoder PRE-CAST from a hosted fp8 checkpoint loads roughly half that encoder, and
+# for ltx-2 the encoder is Gemma3-12B at 24.4 GB, so budgeting it at bf16 over-states the resident
+# requirement by ~11 GB. PR #8213 gates a hard unified-memory refusal on model_dense_mib, which
+# turns that over-estimate from a conservative offload choice into a refused load that would fit.
+_MIB_PER_GB = 1000.0**3 / (1024.0 * 1024.0)
+
+
+def _capture_plan(monkeypatch):
+ """Record every plan_diffusion_memory call's kwargs, keeping the real planner."""
+ import core.inference.video as video_mod
+
+ calls = []
+ real = video_mod.plan_diffusion_memory
+
+ def _spy(**kwargs):
+ calls.append(kwargs)
+ return real(**kwargs)
+
+ monkeypatch.setattr(video_mod, "plan_diffusion_memory", _spy)
+ return calls
+
+
+def _allow_te_prequant(monkeypatch, *, injects = True):
+ """Make the pre-cast encoder resolvable (device-gated on CUDA in real life) without any IO.
+
+ Injection itself needs the Hub and a real transformers class, so it is stubbed either way;
+ ``injects=False`` models the fallback (unreachable / corrupt / base-mismatched checkpoint),
+ where the load ends up with the dense encoder and the budget must return to bf16."""
+ import core.inference.diffusion_precision as precision
+ import core.inference.diffusion_te_prequant as tpq
+
+ # These tests are about the BUDGET the plan is built from, not about the cast. The CPU stub
+ # pipeline carries no encoder the quantiser can cast, and the strict default refuses an
+ # explicit precision it cannot honour, so keep the legacy silent fallback here.
+ monkeypatch.setenv("UNSLOTH_DIFFUSION_ALLOW_PRECISION_FALLBACK", "1")
+ monkeypatch.setattr(precision, "te_quant_supported", lambda target, mode: True)
+ injected = {"text_encoder": object()} if injects else {}
+ monkeypatch.setattr(tpq, "te_prequant_pipe_kwargs", lambda *a, **k: dict(injected))
+ return tpq.TE_PREQUANT_BUDGET_SCALE
+
+
+def test_gguf_plan_budgets_a_pre_cast_text_encoder_at_its_real_size(
+ fake_runtime, monkeypatch, tmp_path
+):
+ from core.inference.video_families import detect_video_family
+
+ scale = _allow_te_prequant(monkeypatch)
+ transformer_gb, text_encoder_gb, vae_gb = detect_video_family(
+ "Lightricks/LTX-2"
+ ).bf16_components_gb
+
+ calls = _capture_plan(monkeypatch)
+ backend = VideoBackend()
+ (tmp_path / "model.gguf").write_bytes(b"weights")
+ backend.load_pipeline(
+ str(tmp_path),
+ gguf_filename = "model.gguf",
+ base_repo = "Lightricks/LTX-2",
+ family_override = "ltx-2",
+ text_encoder_quant = "fp8",
+ )
+ quant_companion = calls[0]["companion_dense_mib"]
+ quant_dense = calls[0]["model_dense_mib"]
+
+ calls.clear()
+ backend = VideoBackend()
+ backend.load_pipeline(
+ str(tmp_path),
+ gguf_filename = "model.gguf",
+ base_repo = "Lightricks/LTX-2",
+ family_override = "ltx-2",
+ )
+ bf16_companion = calls[0]["companion_dense_mib"]
+ bf16_dense = calls[0]["model_dense_mib"]
+
+ # The encoder is scaled...
+ assert quant_companion == int((text_encoder_gb * scale + vae_gb) * _MIB_PER_GB)
+ # ...the VAE is NOT: nothing on this path quantises it, and the Wan families widen it to fp32.
+ assert quant_companion - int(text_encoder_gb * scale * _MIB_PER_GB) == int(vae_gb * _MIB_PER_GB)
+ assert bf16_companion == int((text_encoder_gb + vae_gb) * _MIB_PER_GB)
+ # The saving reaches model_dense_mib, which is the number PR #8213 refuses on.
+ assert bf16_dense - quant_dense == bf16_companion - quant_companion
+ # ~11 GB for Gemma3-12B, so this is worth a whole offload tier rather than rounding noise.
+ assert (bf16_dense - quant_dense) / _MIB_PER_GB > 8.0
+ # The transformer term is untouched by a TEXT-ENCODER quant.
+ assert bf16_dense - bf16_companion == quant_dense - quant_companion
+
+
+def test_pipeline_plan_budgets_a_pre_cast_text_encoder_at_its_real_size(fake_runtime, monkeypatch):
+ from core.inference.video_families import detect_video_family
+
+ scale = _allow_te_prequant(monkeypatch)
+ transformer_gb, text_encoder_gb, vae_gb = detect_video_family(
+ "Lightricks/LTX-2"
+ ).bf16_components_gb
+
+ calls = _capture_plan(monkeypatch)
+ VideoBackend().load_pipeline(
+ "Lightricks/LTX-2", model_kind = "pipeline", text_encoder_quant = "fp8"
+ )
+ assert calls[0]["model_dense_mib"] == int(
+ (transformer_gb + text_encoder_gb * scale + vae_gb) * _MIB_PER_GB
+ )
+ # The pipeline kind budgets one total, so companion_dense_mib stays None as before.
+ assert calls[0]["companion_dense_mib"] is None
+
+
+def test_plan_returns_to_bf16_when_the_pre_cast_encoder_does_not_inject(fake_runtime, monkeypatch):
+ # The source resolves (so the budget shrinks) but the checkpoint cannot be loaded -- an
+ # unreachable Hub, a corrupt artifact, a base-model mismatch. Assembly falls back to the dense
+ # encoder, so the plan must be rebuilt at bf16 before placement is applied; leaving the fp8
+ # budget in place under-states ltx-2's resident requirement by ~8.5 GB and can pick resident.
+ from core.inference.video_families import detect_video_family
+
+ components = detect_video_family("Lightricks/LTX-2").bf16_components_gb
+ _allow_te_prequant(monkeypatch, injects = False)
+
+ calls = _capture_plan(monkeypatch)
+ VideoBackend().load_pipeline(
+ "Lightricks/LTX-2", model_kind = "pipeline", text_encoder_quant = "fp8"
+ )
+ assert calls[0]["model_dense_mib"] < int(sum(components) * _MIB_PER_GB)
+ assert calls[-1]["model_dense_mib"] == int(sum(components) * _MIB_PER_GB)
+
+
+def test_plan_keeps_the_bf16_budget_without_a_hosted_pre_cast_encoder(fake_runtime, monkeypatch):
+ # Wan requests fp8 the same way, but hosts no pre-cast checkpoint: the encoder is downloaded
+ # dense and cast in place AFTER assembly, so its PEAK is bf16 and the budget must not shrink.
+ from core.inference.video_families import detect_video_family
+
+ _allow_te_prequant(monkeypatch)
+ components = detect_video_family("Wan-AI/Wan2.2-TI2V-5B-Diffusers").bf16_components_gb
+
+ calls = _capture_plan(monkeypatch)
+ VideoBackend().load_pipeline(
+ "Wan-AI/Wan2.2-TI2V-5B-Diffusers", model_kind = "pipeline", text_encoder_quant = "fp8"
+ )
+ assert calls[0]["model_dense_mib"] == int(sum(components) * _MIB_PER_GB)
+
+
+def test_plan_is_unchanged_when_no_text_encoder_quant_is_requested(fake_runtime, monkeypatch):
+ # The whole change is inert on a default load: every family keeps its bf16-table budget, so no
+ # existing decision on any device moves.
+ from core.inference.video_families import _FAMILIES
+
+ _allow_te_prequant(monkeypatch)
+ calls = _capture_plan(monkeypatch)
+ for fam in _FAMILIES:
+ if fam.bf16_components_gb is None or fam.name == "wan2.2-t2v-a14b":
+ continue
+ calls.clear()
+ VideoBackend().load_pipeline(fam.base_repo, model_kind = "pipeline")
+ assert calls[0]["model_dense_mib"] == int(
+ sum(fam.bf16_components_gb) * _MIB_PER_GB
+ ), fam.name
+
+
+def test_dense_quant_replan_uses_the_scaled_text_encoder(fake_runtime, monkeypatch):
+ # The transformer-quant re-plan rebuilds the total from the table; it must carry the same
+ # scaled encoder, or it re-introduces the over-estimate the first plan just dropped.
+ import core.inference.video as video_mod
+ from core.inference.diffusion_auto_policy import _QUANT_STEADY_FACTOR
+ from core.inference.video_families import detect_video_family
+
+ scale = _allow_te_prequant(monkeypatch)
+ transformer_gb, text_encoder_gb, vae_gb = detect_video_family(
+ "Lightricks/LTX-2"
+ ).bf16_components_gb
+ monkeypatch.setattr(video_mod, "dense_transformer_supported", lambda target: True)
+ monkeypatch.setattr(
+ video_mod, "select_transformer_quant_scheme", lambda target, mode, family = None: "int8"
+ )
+ monkeypatch.setattr(video_mod, "quantize_transformer", lambda *a, **k: None)
+ # Force the first plan to offload so the re-plan branch runs.
+ import dataclasses
+
+ real = video_mod.plan_diffusion_memory
+ calls = []
+
+ def _spy(**kwargs):
+ calls.append(kwargs)
+ return dataclasses.replace(real(**kwargs), offload_policy = "model")
+
+ monkeypatch.setattr(video_mod, "plan_diffusion_memory", _spy)
+ monkeypatch.setattr(
+ video_mod, "apply_memory_plan", lambda pipe, plan, device = None, logger = None: ("model", True)
+ )
+
+ VideoBackend().load_pipeline(
+ "Lightricks/LTX-2",
+ model_kind = "pipeline",
+ transformer_quant = "int8",
+ text_encoder_quant = "fp8",
+ )
+ assert len(calls) == 2, "the dense-quant re-plan did not run"
+ assert calls[1]["model_dense_mib"] == int(
+ (transformer_gb * _QUANT_STEADY_FACTOR["int8"] + text_encoder_gb * scale + vae_gb)
+ * _MIB_PER_GB
+ )