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 LTX-2.5: use two CUDA cards, the sidecar text encoder priced on its own card (#17077)

Daniel Haneff80d82e4b7
diff --git a/studio/backend/core/inference/diffusion_multigpu.py b/studio/backend/core/inference/diffusion_multigpu.py
index 0e4f9321714..97a0a7e32b4 100644
--- a/studio/backend/core/inference/diffusion_multigpu.py
+++ b/studio/backend/core/inference/diffusion_multigpu.py
@@ -17,7 +17,7 @@ import time
import types
import weakref
from collections import OrderedDict
-from typing import Any, Callable, Iterator, Optional, Sequence
+from typing import Any, Callable, Iterator, Mapping, Optional, Sequence
MULTIGPU_ENV = "UNSLOTH_DIFFUSION_MULTIGPU"
CFG_PARALLEL_ENV = "UNSLOTH_DIFFUSION_CFG_PARALLEL"
@@ -924,8 +924,11 @@ def refine_plan_for_multigpu(
pipe: Any,
plan: Any,
logger: Any = None,
+ *,
+ card_reserve_mib: Optional[Mapping[int, int]] = None,
) -> Any:
"""Post-load: an offloading plan becomes a resident split when the LOADED components can be shared by the cards.
+ ``card_reserve_mib`` (ordinal -> MiB): memory a sidecar process holds on a card, uncounted by the loaded sizes.
No-op without a selection, for explicit offload modes, a plan already resident (unless forced) or split, unified memory
or an unknown budget. When no component assignment fits, a layer split (diffusion_layer_split_plan) is tried before
@@ -1001,7 +1004,13 @@ def refine_plan_for_multigpu(
secondary = best_secondary(selection, mode = mode)
if secondary is None:
return one_card_plan("no second card")
- sec_limit = secondary_resident_limit_mib(secondary, mode)
+ reserve = {int(o): max(0, int(m)) for o, m in (card_reserve_mib or {}).items()}
+
+ def card_limit(ordinal: int) -> Optional[int]:
+ limit = secondary_resident_limit_mib(ordinal, mode)
+ return None if limit is None else int(limit) - reserve.get(int(ordinal), 0)
+
+ sec_limit = card_limit(secondary)
if sec_limit is None:
return one_card_plan(f"free memory of cuda:{secondary} is unknown")
from .diffusion_memory import _fast_device_budget_mib
@@ -1019,6 +1028,7 @@ def refine_plan_for_multigpu(
# refuse a split that is lighter than the plan it replaces (the text encoder then streamed from host memory
# beside an idle second card).
primary_limit = max(int(primary_limit), int(budget))
+ primary_limit = int(primary_limit) - reserve.get(primary, 0)
measured_headroom = plan.estimates.get("measured_runtime_headroom_mib")
flat_headroom = (
plan.estimates.get("calibrated_headroom_mib")
@@ -1054,7 +1064,7 @@ def refine_plan_for_multigpu(
selection = selection,
sizes = sizes,
primary_limit_mib = int(primary_limit),
- secondary_limit_mib = lambda o: secondary_resident_limit_mib(o, mode),
+ secondary_limit_mib = card_limit,
headroom_mib = headroom,
overhead_mib = overhead,
logger = logger,
@@ -1109,6 +1119,7 @@ def refine_plan_for_multigpu(
if layer_force:
return layer_split_or_plan()
move_denoisers = _secondary_runs_denoiser(pipe, selection, secondary, sizes, logger)
+ encoders_limit = encoder_card_limit_mib(secondary)
trials = component_assignment_trials(
sizes,
headroom_mib = headroom,
@@ -1116,7 +1127,9 @@ def refine_plan_for_multigpu(
primary_limit_mib = int(primary_limit),
secondary_limit_mib = int(sec_limit),
move_denoisers = move_denoisers,
- encoders_only_limit_mib = encoder_card_limit_mib(secondary),
+ encoders_only_limit_mib = (
+ None if encoders_limit is None else int(encoders_limit) - reserve.get(int(secondary), 0)
+ ),
)
winner = next((t for t in trials if t.fits), None)
moved = winner.moved if winner is not None else None
diff --git a/studio/backend/core/inference/video.py b/studio/backend/core/inference/video.py
index a4626a7d6fa..854b11de0db 100644
--- a/studio/backend/core/inference/video.py
+++ b/studio/backend/core/inference/video.py
@@ -4733,9 +4733,28 @@ def _video_offload_vram_floor_mib(
return None
-# Families whose text encoder runs outside ``pipe.components`` (a sidecar worker on the primary): a multi-GPU split
-# cannot move it, so the companion split the planner priced with it would leave it on the primary beside the DiT.
+# Text encoder runs in a sidecar worker outside ``pipe.components``: a split cannot move it.
_VIDEO_SIDECAR_ENCODER_FAMILIES = frozenset({"ltx-2.5"})
+# "0" keeps LTX-2.5 on one card under a multi-GPU selection.
+LTX25_MULTI_GPU_ENV = "UNSLOTH_LTX25_MULTI_GPU"
+
+
+def _video_sidecar_multigpu(fam: Any) -> bool:
+ """Sidecar-encoder family may use two cards: lever on, multi-card selection active, CUDA (not ROCm)."""
+ if getattr(fam, "name", None) not in _VIDEO_SIDECAR_ENCODER_FAMILIES:
+ return False
+ if (os.environ.get(LTX25_MULTI_GPU_ENV) or "").strip().lower() in ("0", "off", "false", "no"):
+ return False
+ from .diffusion_multigpu import _rocm_torch, current_selection
+
+ return current_selection() is not None and not _rocm_torch()
+
+
+def _video_sidecar_worker_card(fam: Any, plan: Any) -> Optional[int]:
+ secondary = getattr(plan, "secondary_ordinal", None)
+ if secondary is None or not _video_sidecar_multigpu(fam):
+ return None
+ return int(secondary)
def _video_single_card_for_sidecar(
@@ -4743,30 +4762,110 @@ def _video_single_card_for_sidecar(
plan: Any,
logger: Any = None,
) -> Any:
- """The single-card plan in place of a companion split for a sidecar-encoder family; any other plan unchanged."""
+ """Single-card plan for a sidecar-encoder split, unless the partner can also hold the worker's context."""
if getattr(fam, "name", None) not in _VIDEO_SIDECAR_ENCODER_FAMILIES:
return plan
fallback = getattr(plan, "fallback_plan", None)
- if getattr(plan, "secondary_ordinal", None) is None or fallback is None:
+ secondary = getattr(plan, "secondary_ordinal", None)
+ if secondary is None or fallback is None:
return plan
+ why = f"the {fam.name} text encoder runs in a sidecar a split cannot move"
+ if _video_sidecar_multigpu(fam):
+ from .diffusion_multigpu import secondary_resident_limit_mib
+ from .video_ltx25 import LTX25_WORKER_RESIDENT_GB
+
+ need = (getattr(plan, "estimates", None) or {}).get("multigpu_secondary_required_mib")
+ limit = secondary_resident_limit_mib(int(secondary), getattr(plan, "requested_mode", None))
+ context = int(LTX25_WORKER_RESIDENT_GB * 1024)
+ if need is not None and limit is not None and int(need) + context <= int(limit):
+ if logger is not None:
+ logger.info(
+ "video.multigpu: the %s text encoder worker runs on cuda:%s with the split (%d MiB of %d MiB)",
+ fam.name,
+ secondary,
+ int(need) + context,
+ int(limit),
+ )
+ return plan
+ why = f"cuda:{secondary} cannot also hold the {fam.name} text encoder worker"
if logger is not None:
- logger.info(
- "video.multigpu: one card (the %s text encoder runs in a sidecar a split cannot move)",
- fam.name,
- )
+ logger.info("video.multigpu: one card (%s)", why)
return fallback
+def _video_sidecar_card_reserve_mib(pipe: Any, plan: Any = None) -> Optional[dict[int, int]]:
+ """``{ordinal: MiB}`` peak the sidecar encoder holds, unseen by ``_loaded_component_mib``; None = unpriceable.
+ On the primary a host-kept encoder reuses the denoise headroom (encode runs first). Waits for the worker's load
+ report and raises its load error here (the message is read once)."""
+ client = getattr(pipe, "_unsloth_ltx25_encoder", None)
+ config = getattr(client, "config", None) or {}
+ device = str(config.get("device") or "")
+ if client is None or not device.startswith("cuda"):
+ return None
+ info = client.wait_ready(getattr(client, "cancel_event", None))
+ try:
+ import torch
+
+ from .video_ltx25 import LTX25_WORKER_RESIDENT_GB
+ from .video_ltx25_te_worker import ENCODE_MARGIN_MIB
+
+ ordinal = torch.device(device).index
+ ordinal = int(ordinal if ordinal is not None else torch.cuda.current_device())
+ weights = int(info.get("weights_mib") or 0)
+ if weights <= 0:
+ return None
+ if info.get("resident"):
+ need = weights
+ else:
+ stream = info.get("stream_need_mib")
+ need = int(stream) if stream else weights + ENCODE_MARGIN_MIB
+ from .diffusion_multigpu import current_selection
+
+ selection = current_selection()
+ if selection is not None and int(selection.primary) == ordinal:
+ estimates = getattr(plan, "estimates", None) or {}
+ flat = (
+ estimates.get("calibrated_headroom_mib")
+ or estimates.get("calibrated_split_headroom_mib")
+ or estimates.get("runtime_headroom_mib")
+ )
+ headroom = int(estimates.get("measured_runtime_headroom_mib") or flat or 0)
+ need = max(0, need - headroom)
+ return {ordinal: int(need + LTX25_WORKER_RESIDENT_GB * 1024)}
+ except Exception as exc: # noqa: BLE001 -- unpriced: one card, the worker's load error surfaces later
+ logger.info("video.multigpu: the sidecar encoder could not be priced (%s)", exc)
+ return None
+
+
def _video_refine_for_multigpu(
fam: Any,
pipe: Any,
plan: Any,
logger: Any = None,
) -> Any:
- """``refine_plan_for_multigpu``, declined for a sidecar-encoder family (its loaded sizes omit the encoder)."""
- if getattr(fam, "name", None) in _VIDEO_SIDECAR_ENCODER_FAMILIES:
+ """``refine_plan_for_multigpu``; sidecar families only under ``_video_sidecar_multigpu``, charged for the worker."""
+ if getattr(fam, "name", None) not in _VIDEO_SIDECAR_ENCODER_FAMILIES:
+ return refine_plan_for_multigpu(pipe, plan, logger)
+ if not _video_sidecar_multigpu(fam):
return plan
- return refine_plan_for_multigpu(pipe, plan, logger)
+ if (
+ getattr(plan, "secondary_ordinal", None) is not None
+ or getattr(plan, "layer_split", None) is not None
+ ):
+ return refine_plan_for_multigpu(pipe, plan, logger, card_reserve_mib = {})
+ from .diffusion_layer_split_plan import layer_split_mode
+
+ if (
+ getattr(plan, "offload_policy", None) == "none"
+ and multigpu_mode() != "force"
+ and layer_split_mode() != "force"
+ ):
+ # resident: nothing is priced, so do not wait for the worker
+ return refine_plan_for_multigpu(pipe, plan, logger, card_reserve_mib = {})
+ reserve = _video_sidecar_card_reserve_mib(pipe, plan)
+ if reserve is None:
+ return plan
+ return refine_plan_for_multigpu(pipe, plan, logger, card_reserve_mib = reserve)
def _video_split_card_floors(pipe: Any) -> Optional[tuple]:
@@ -9660,6 +9759,16 @@ class VideoBackend:
stale_encoder, self._ltx25_pending_encoder = self._ltx25_pending_encoder, None
if stale_encoder is not None:
_stop_ltx25_encoder(stale_encoder[1])
+ worker_card = _video_sidecar_worker_card(fam, plan)
+ if worker_card is not None:
+ from .diffusion_multigpu import secondary_safe_budget_mib
+ worker_device = f"cuda:{worker_card}"
+ worker_budget = secondary_safe_budget_mib(worker_card)
+ else:
+ worker_device = str(target.torch_device)
+ worker_budget = (getattr(plan, "estimates", None) or {}).get(
+ "safe_device_budget_mib"
+ )
ltx25_client = start_text_encoder(
repo = _base_local_dir or fetch_base,
# The plan's commit when the worker reads the hub id (a staged dir already is that commit).
@@ -9667,12 +9776,13 @@ class VideoBackend:
hf_token = hf_token,
cache_dir = hub_cache_dir(),
local_files_only = local_files_only,
- device = str(target.torch_device),
+ device = worker_device,
dtype = str(dtype).replace("torch.", ""),
resident = encoder_resident_for_plan(plan),
- budget_mib = (getattr(plan, "estimates", None) or {}).get("safe_device_budget_mib"),
+ budget_mib = worker_budget,
te_quant = ltx25_te_quant_scheme(text_encoder_quant),
base_repo = base,
+ bind_device = _video_sidecar_multigpu(fam),
)
# Installed only while this load is current: a load superseded during the start must not overwrite the
# newer load's worker (whose token-scoped cleanup could then never find it).
diff --git a/studio/backend/core/inference/video_ltx25.py b/studio/backend/core/inference/video_ltx25.py
index 2eedd924be2..43c2841e6bf 100644
--- a/studio/backend/core/inference/video_ltx25.py
+++ b/studio/backend/core/inference/video_ltx25.py
@@ -1228,6 +1228,7 @@ class Ltx25TextEncoderClient:
self._cmd: Any = None
self._resp: Any = None
self._ready = False
+ self._ready_error: Optional[BaseException] = None
self._seq = 0
# Request the worker is still computing (a cancel abandons it).
self._inflight: Optional[int] = None
@@ -1273,6 +1274,7 @@ class Ltx25TextEncoderClient:
spawn_on_lifetime_thread(proc.start)
self._proc = proc
self._ready = False
+ self._ready_error = None
try:
from utils.process_lifetime import adopt_pid
adopt_pid(proc.pid)
@@ -1345,7 +1347,14 @@ class Ltx25TextEncoderClient:
def wait_ready(self, cancel: Optional[threading.Event] = None) -> dict:
if self._ready:
return self.info
- msg = self._get(cancel, "loading the Gemma 4 encoder")
+ if getattr(self, "_ready_error", None) is not None:
+ # The worker sends its load error once: a second caller (a placement preview read it first) gets the same one.
+ raise self._ready_error
+ try:
+ msg = self._get(cancel, "loading the Gemma 4 encoder")
+ except TextEncoderWorkerError as exc:
+ self._ready_error = exc
+ raise
if msg.get("type") != "ready":
raise TextEncoderWorkerError(
f"Unexpected reply from the text encoder worker: {msg.get('type')}"
@@ -1358,6 +1367,7 @@ class Ltx25TextEncoderClient:
def close(self) -> None:
proc, self._proc = self._proc, None
self._ready = False
+ self._ready_error = None
self._inflight = None
self._cache.clear()
if proc is None:
@@ -1615,6 +1625,7 @@ def start_text_encoder(
budget_mib: Optional[int] = None,
te_quant: Optional[str] = None,
base_repo: Optional[str] = None,
+ bind_device: bool = False,
) -> Ltx25TextEncoderClient:
"""Check the sidecar (a named refusal before any weight is read), then spawn the encoder worker so the Gemma 4
load overlaps the DiT load. ``base_repo`` is the upstream pack id (``repo`` may be its local snapshot); an int8
@@ -1656,10 +1667,25 @@ def start_text_encoder(
share = user_budget_reserve_share()
if share > 0:
client.config["vram_reserve_share"] = share
+ if bind_device:
+ # by UUID: a spawned child may enumerate cards in another order
+ client.config.update(bind_device = True, device_uuid = _cuda_device_uuid(device))
client.start()
return client
+def _cuda_device_uuid(device: str) -> Optional[str]:
+ try:
+ import torch
+
+ index = torch.device(device).index
+ if torch.device(device).type != "cuda" or index is None:
+ return None
+ return str(torch.cuda.get_device_properties(index).uuid)
+ except Exception: # noqa: BLE001 -- the worker then binds the ordinal as given
+ return None
+
+
def attach_to_pipeline(
pipe: Any,
client: Ltx25TextEncoderClient,
diff --git a/studio/backend/core/inference/video_ltx25_te_worker.py b/studio/backend/core/inference/video_ltx25_te_worker.py
index 552b7a37ed9..db4ce951e6d 100644
--- a/studio/backend/core/inference/video_ltx25_te_worker.py
+++ b/studio/backend/core/inference/video_ltx25_te_worker.py
@@ -1258,11 +1258,30 @@ def _no_context() -> Any:
return contextlib.nullcontext()
+def _bind_device(config: dict) -> None:
+ """Make the configured card current (not cuda:0), re-resolving the ordinal by the server's card UUID."""
+ device = str(config.get("device") or "")
+ if not config.get("bind_device") or not device.startswith("cuda"):
+ return
+ import torch
+
+ index = torch.device(device).index or 0
+ uuid = config.get("device_uuid")
+ if uuid:
+ for i in range(torch.cuda.device_count()):
+ if str(torch.cuda.get_device_properties(i).uuid) == uuid:
+ index = i
+ break
+ config["device"] = f"cuda:{index}"
+ torch.cuda.set_device(index)
+
+
def run_text_encoder_worker(*, cmd_queue: Any, resp_queue: Any, config: dict) -> None:
if _BACKEND_PATH not in sys.path:
sys.path.insert(0, _BACKEND_PATH)
try:
_activate_sidecar(config.get("venv_dir") or "")
+ _bind_device(config)
tokenizer, model = _load(config)
import transformers
diff --git a/studio/backend/tests/test_diffusion_multigpu.py b/studio/backend/tests/test_diffusion_multigpu.py
index 2c048205f91..1aefcc7d816 100644
--- a/studio/backend/tests/test_diffusion_multigpu.py
+++ b/studio/backend/tests/test_diffusion_multigpu.py
@@ -1781,26 +1781,195 @@ def test_force_mode_refines_a_resident_plan(monkeypatch):
assert refined.fallback_plan is plan
-def test_ltx25_sidecar_encoder_keeps_the_single_card_plan(monkeypatch):
+def _ltx25_split(single, **estimates):
+ return dataclasses.replace(
+ single,
+ offload_policy = dm.OFFLOAD_NONE,
+ secondary_ordinal = 1,
+ fallback_plan = single,
+ estimates = {**single.estimates, **estimates},
+ )
+
+
+def test_ltx25_sidecar_encoder_keeps_one_card_without_the_lever(monkeypatch):
import types as _types
from core.inference import video as vid
single = _plan()
- split = dataclasses.replace(
- single, offload_policy = dm.OFFLOAD_NONE, secondary_ordinal = 1, fallback_plan = single
- )
+ split = _ltx25_split(single, multigpu_secondary_required_mib = 9000)
ltx25 = _types.SimpleNamespace(name = "ltx-2.5")
wan = _types.SimpleNamespace(name = "wan2.2")
- assert vid._video_single_card_for_sidecar(ltx25, split) is single
- assert vid._video_single_card_for_sidecar(wan, split) is split
- assert vid._video_single_card_for_sidecar(ltx25, single) is single
refined = []
monkeypatch.setattr(
- vid, "refine_plan_for_multigpu", lambda pipe, plan, logger = None: refined.append(1) or split
+ vid,
+ "refine_plan_for_multigpu",
+ lambda pipe, plan, logger = None, **kw: refined.append(kw) or split,
)
+ monkeypatch.setattr(mg, "secondary_resident_limit_mib", lambda o, mode: 13600)
+ # no selection: one card, whatever the lever says
+ assert vid._video_single_card_for_sidecar(ltx25, split) is single
+ assert vid._video_single_card_for_sidecar(wan, split) is split
+ assert vid._video_single_card_for_sidecar(ltx25, single) is single
assert vid._video_refine_for_multigpu(ltx25, object(), single) is single
- assert vid._video_refine_for_multigpu(wan, object(), single) is split and refined == [1]
+ assert vid._video_refine_for_multigpu(wan, object(), single) is split and refined == [{}]
+ monkeypatch.setenv(vid.LTX25_MULTI_GPU_ENV, "0")
+ refined.clear()
+ with mg.selection_scope(mg.make_selection(0, [0, 1])):
+ assert vid._video_single_card_for_sidecar(ltx25, split) is single
+ assert vid._video_sidecar_worker_card(ltx25, split) is None
+ assert vid._video_refine_for_multigpu(ltx25, object(), single) is single
+ assert refined == []
+
+
+def test_ltx25_split_keeps_the_worker_on_the_partner_when_it_fits(monkeypatch):
+ import types as _types
+
+ from core.inference import video as vid
+
+ single = _plan()
+ ltx25 = _types.SimpleNamespace(name = "ltx-2.5")
+ monkeypatch.setattr(mg, "secondary_resident_limit_mib", lambda o, mode: 13600)
+ fits = _ltx25_split(single, multigpu_secondary_required_mib = 13600 - 1024)
+ short = _ltx25_split(single, multigpu_secondary_required_mib = 13600 - 1023)
+ unpriced = _ltx25_split(single)
+ with mg.selection_scope(mg.make_selection(0, [0, 1])):
+ assert vid._video_single_card_for_sidecar(ltx25, fits) is fits
+ assert vid._video_sidecar_worker_card(ltx25, fits) == 1
+ assert vid._video_single_card_for_sidecar(ltx25, short) is single
+ assert vid._video_single_card_for_sidecar(ltx25, unpriced) is single
+ assert vid._video_sidecar_worker_card(ltx25, single) is None
+ monkeypatch.setattr(mg, "_rocm_torch", lambda: True)
+ assert vid._video_single_card_for_sidecar(ltx25, fits) is single
+ assert vid._video_sidecar_worker_card(ltx25, fits) is None
+
+
+class _FakeEncoderClient:
+ def __init__(self, device, info):
+ self.config = {"device": device}
+ self._info = info
+ self.waits = 0
+
+ def wait_ready(self, cancel = None):
+ self.waits += 1
+ if isinstance(self._info, Exception):
+ raise self._info
+ return self._info
+
+
+def test_ltx25_worker_reserve_prices_its_card():
+ from core.inference import video as vid
+
+ def reserve(
+ device,
+ info,
+ plan = None,
+ ):
+ pipe = _types_ns(_unsloth_ltx25_encoder = _FakeEncoderClient(device, info))
+ return vid._video_sidecar_card_reserve_mib(pipe, plan)
+
+ assert reserve("cuda:0", {"resident": True, "weights_mib": 13000}) == {0: 13000 + 1024}
+ assert reserve(
+ "cuda:1", {"resident": False, "weights_mib": 13000, "stream_need_mib": 6000}
+ ) == {1: 6000 + 1024}
+ assert reserve("cuda:0", {"resident": False, "weights_mib": 13000}) == {0: 13000 + 4096 + 1024}
+ # on the primary a non-resident encode reuses the denoise headroom; resident weights and the partner never do
+ plan = _types_ns(estimates = {"runtime_headroom_mib": 5000})
+ streamed = {"resident": False, "weights_mib": 13000, "stream_need_mib": 6000}
+ with mg.selection_scope(mg.make_selection(0, [0, 1])):
+ assert reserve("cuda:0", streamed, plan) == {0: 1000 + 1024}
+ assert reserve(
+ "cuda:0", {"resident": False, "weights_mib": 16, "stream_need_mib": 4112}, plan
+ ) == {0: 1024}
+ assert reserve("cuda:0", {"resident": True, "weights_mib": 13000}, plan) == {
+ 0: 13000 + 1024
+ }
+ assert reserve("cuda:1", streamed, plan) == {1: 6000 + 1024}
+ assert reserve("cuda:0", streamed, plan) == {0: 6000 + 1024}
+ assert reserve("cpu", {"resident": True, "weights_mib": 13000}) is None
+ assert reserve("cuda:0", {"resident": True}) is None
+ with pytest.raises(RuntimeError, match = "worker died"):
+ reserve("cuda:0", RuntimeError("worker died"))
+ assert vid._video_sidecar_card_reserve_mib(_types_ns()) is None
+
+
+def _types_ns(**kw):
+ import types as _types
+ return _types.SimpleNamespace(**kw)
+
+
+def test_ltx25_refinement_is_charged_for_the_worker(monkeypatch):
+ """A companion split that fits without the worker's charge must not fit with it."""
+ from core.inference import diffusion_layer_split_plan as lsp
+ from core.inference import video as vid
+
+ plan = _plan()
+ assert plan.offload_policy != dm.OFFLOAD_NONE
+ sizes = {"transformer": (9000, "dit"), "connectors": (3000, "other"), "vae": (300, "other")}
+ monkeypatch.setattr(dm, "_loaded_component_mib", lambda pipe: sizes)
+ monkeypatch.setattr(mg, "secondary_resident_limit_mib", lambda o, mode: 12750)
+ monkeypatch.setattr(mg, "best_secondary", lambda selection, probes = None, **_: 1)
+ monkeypatch.setattr(mg, "encoder_card_limit_mib", lambda o: 12750)
+ limits = []
+
+ def layer_split(pipe, plan, *, primary_limit_mib, secondary_limit_mib, **kw):
+ limits.append((primary_limit_mib, secondary_limit_mib(1)))
+ return plan
+
+ monkeypatch.setattr(lsp, "refine_plan_for_layer_split", layer_split)
+ ltx25 = _types_ns(name = "ltx-2.5")
+ with mg.selection_scope(mg.make_selection(0, [0, 1])):
+ free = mg.refine_plan_for_multigpu(object(), plan)
+ assert free.secondary_ordinal == 1 and free.offload_policy == dm.OFFLOAD_NONE
+ budget = int(plan.estimates["safe_device_budget_mib"])
+ unreserved = (
+ budget
+ if dm.plan_keeps_transformer_resident(plan)
+ else int(budget * mg._RESIDENT_FRACTION)
+ )
+ worker = _FakeEncoderClient("cuda:0", {"resident": True, "weights_mib": unreserved})
+ charged = vid._video_refine_for_multigpu(
+ ltx25, _types_ns(_unsloth_ltx25_encoder = worker), plan
+ )
+ assert charged is plan and worker.waits == 1
+ assert limits[-1] == (unreserved - unreserved - 1024, 12750)
+ partner = _FakeEncoderClient("cuda:1", {"resident": True, "weights_mib": 12000})
+ assert (
+ vid._video_refine_for_multigpu(ltx25, _types_ns(_unsloth_ltx25_encoder = partner), plan)
+ is plan
+ )
+ assert limits[-1] == (unreserved, 12750 - 12000 - 1024)
+ small = _FakeEncoderClient("cuda:1", {"resident": True, "weights_mib": 100})
+ split = vid._video_refine_for_multigpu(ltx25, _types_ns(_unsloth_ltx25_encoder = small), plan)
+ assert split.secondary_ordinal == 1
+ unpriced = _FakeEncoderClient("cuda:0", {"resident": True})
+ assert (
+ vid._video_refine_for_multigpu(ltx25, _types_ns(_unsloth_ltx25_encoder = unpriced), plan)
+ is plan
+ )
+ resident = dataclasses.replace(plan, offload_policy = dm.OFFLOAD_NONE)
+ idle = _FakeEncoderClient("cuda:0", {"resident": True, "weights_mib": 1})
+ kept = vid._video_refine_for_multigpu(
+ ltx25, _types_ns(_unsloth_ltx25_encoder = idle), resident
+ )
+ assert kept is resident and idle.waits == 0
+
+
+def test_refinement_without_a_reserve_is_unchanged(monkeypatch):
+ plan = _plan()
+ sizes = {
+ "transformer": (9000, "dit"),
+ "text_encoder": (8000, "text_encoder"),
+ "vae": (300, "other"),
+ }
+ monkeypatch.setattr(dm, "_loaded_component_mib", lambda pipe: sizes)
+ monkeypatch.setattr(mg, "secondary_resident_limit_mib", lambda o, mode: 12750)
+ monkeypatch.setattr(mg, "best_secondary", lambda selection, probes = None, **_: 1)
+ with mg.selection_scope(mg.make_selection(0, [0, 1])):
+ a = mg.refine_plan_for_multigpu(object(), plan)
+ b = mg.refine_plan_for_multigpu(object(), plan, card_reserve_mib = {})
+ c = mg.refine_plan_for_multigpu(object(), plan, card_reserve_mib = {1: 0, 5: 99999})
+ assert a == b == c and a.secondary_components == ("text_encoder", "vae")
def _fake_cuda_host(
diff --git a/studio/backend/tests/test_video_ltx25_multigpu.py b/studio/backend/tests/test_video_ltx25_multigpu.py
new file mode 100644
index 00000000000..6269d0d977a
--- /dev/null
+++ b/studio/backend/tests/test_video_ltx25_multigpu.py
@@ -0,0 +1,110 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""LTX-2.5 sidecar encoder binds its own card (ordinal + UUID); CPU only, torch.cuda faked."""
+
+from __future__ import annotations
+
+import pickle
+import types
+
+import pytest
+import torch
+
+from core.inference import video_ltx25 as L
+from core.inference import video_ltx25_te_worker as W
+
+
+def _fake_cards(monkeypatch, uuids):
+ chosen = []
+ monkeypatch.setattr(torch.cuda, "device_count", lambda: len(uuids))
+ monkeypatch.setattr(
+ torch.cuda, "get_device_properties", lambda i: types.SimpleNamespace(uuid = uuids[i])
+ )
+ monkeypatch.setattr(torch.cuda, "set_device", lambda i: chosen.append(i))
+ return chosen
+
+
+def test_worker_binds_the_card_the_server_named(monkeypatch):
+ chosen = _fake_cards(monkeypatch, ["GPU-a", "GPU-b"])
+ config = {"device": "cuda:1", "bind_device": True, "device_uuid": "GPU-b"}
+ W._bind_device(config)
+ assert chosen == [1] and config["device"] == "cuda:1"
+
+
+def test_worker_resolves_the_card_by_uuid_when_its_order_differs(monkeypatch):
+ # child enumerates cards in another order: the UUID wins
+ chosen = _fake_cards(monkeypatch, ["GPU-b", "GPU-a"])
+ config = {"device": "cuda:1", "bind_device": True, "device_uuid": "GPU-b"}
+ W._bind_device(config)
+ assert chosen == [0] and config["device"] == "cuda:0"
+ config = {"device": "cuda:1", "bind_device": True, "device_uuid": "GPU-z"}
+ W._bind_device(config)
+ assert chosen[-1] == 1 and config["device"] == "cuda:1"
+
+
+def test_worker_binds_nothing_without_the_lever(monkeypatch):
+ chosen = _fake_cards(monkeypatch, ["GPU-a", "GPU-b"])
+ for config in (
+ {"device": "cuda:1"},
+ {"device": "cuda:1", "bind_device": False, "device_uuid": "GPU-b"},
+ {"device": "cpu", "bind_device": True},
+ {"device": "mps", "bind_device": True},
+ ):
+ before = dict(config)
+ W._bind_device(config)
+ assert config == before
+ assert chosen == []
+
+
[email protected]("bind", [False, True])
+def test_start_text_encoder_hands_the_card_to_the_worker(monkeypatch, bind):
+ monkeypatch.setattr(L, "ensure_text_encoder_sidecar", lambda: "/nonexistent/.venv_t5_510")
+ monkeypatch.setattr(L.Ltx25TextEncoderClient, "start", lambda self: None)
+ monkeypatch.setattr(L, "_cuda_device_uuid", lambda device: f"uuid-of-{device}")
+ client = L.start_text_encoder(
+ repo = "Lightricks/LTX-2.5-Diffusers",
+ hf_token = None,
+ cache_dir = None,
+ local_files_only = True,
+ device = "cuda:1",
+ dtype = "bfloat16",
+ resident = True,
+ budget_mib = 12000,
+ bind_device = bind,
+ )
+ assert client.config["device"] == "cuda:1" and client.config["budget_mib"] == 12000
+ if bind:
+ assert client.config["bind_device"] is True
+ assert client.config["device_uuid"] == "uuid-of-cuda:1"
+ else:
+ assert "bind_device" not in client.config and "device_uuid" not in client.config
+ assert pickle.loads(pickle.dumps(client.config)) == client.config
+
+
+def test_cuda_device_uuid_is_none_off_cuda():
+ assert L._cuda_device_uuid("cpu") is None
+ assert L._cuda_device_uuid("cuda") is None
+ assert L._cuda_device_uuid("not a device") is None
+
+
+def test_a_load_error_read_by_a_placement_preview_reaches_the_load(monkeypatch):
+ import queue
+
+ client = L.Ltx25TextEncoderClient(
+ repo = "r",
+ hf_token = None,
+ cache_dir = None,
+ local_files_only = True,
+ device = "cuda:1",
+ dtype = "bfloat16",
+ resident = False,
+ venv_dir = "/x",
+ )
+ client._cmd, client._resp = queue.Queue(), queue.Queue()
+ client._proc = types.SimpleNamespace(is_alive = lambda: False, exitcode = 1)
+ client._resp.put({"type": "error", "error": "encoder not in the cache", "cache_miss": True})
+ for _ in range(2): # the preview swallows the first, the load's own wait must still see it
+ with pytest.raises(L.TextEncoderWorkerError) as err:
+ client.wait_ready()
+ assert "not in the cache" in str(err.value) and err.value.cache_miss