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.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio diffusion: Automatic arms CFG-parallel on an idle card of the same model (#16680)
Daniel Han3ea5429339d5
diff --git a/studio/backend/core/inference/diffusion_multigpu.py b/studio/backend/core/inference/diffusion_multigpu.pyindex f97a2cabdf6..d8e6a48c8af 100644--- a/studio/backend/core/inference/diffusion_multigpu.py+++ b/studio/backend/core/inference/diffusion_multigpu.py@@ -53,6 +53,26 @@ def multigpu_mode() -> str:UNET_CFG_PARALLEL_ENV = "UNSLOTH_DIFFUSION_CFG_PARALLEL_UNET"+# Automatic (no gpu_ids) arms CFG-parallel on an idle card of the same model; 0 keeps the replica to explicit picks.+AUTO_CFG_PARALLEL_ENV = "UNSLOTH_DIFFUSION_CFG_PARALLEL_AUTO"+# A card counts as idle when no more than this is in use on it (driver + another process's context).+AUTO_CFG_PARALLEL_IDLE_USED_MIB = 1024+++def automatic_cfg_parallel_off() -> bool:+ return (os.environ.get(AUTO_CFG_PARALLEL_ENV) or "").strip().lower() in (+ "0",+ "off",+ "false",+ "no",+ )+++def _idle_card(probe: Any) -> bool:+ free, total = getattr(probe, "free_mib", None), getattr(probe, "total_mib", None)+ if free is None or total is None:+ return False+ return int(total) - int(free) <= AUTO_CFG_PARALLEL_IDLE_USED_MIBdef cfg_parallel_mode() -> str:@@ -198,8 +218,12 @@ def selection_scope(if selection is None:yield Nonereturn- # Only a CFG replica reads the recorded compile arguments; automatic placement never builds one.- if not selection.automatic or cfg_parallel_mode() == "force":+ # Only a CFG replica reads the recorded compile arguments; automatic placement builds one unless its lever is off.+ if (+ not selection.automatic+ or cfg_parallel_mode() == "force"+ or not automatic_cfg_parallel_off()+ ):install_compile_recorder()token = _SELECTION.set(selection)try:@@ -2862,6 +2886,13 @@ class CfgParallelRouter:t.numel() * t.element_size() for t in (*module.parameters(), *module.buffers())) // (1 << 20)free, total = self._secondary_free_total_mib()+ if getattr(self, "automatic_idle_only", False) and not _idle_card(+ DeviceProbe(ordinal = self.secondary.index, name = "", total_mib = total, free_mib = free)+ ):+ # Automatic borrowed this card because it was idle at load; something else took it since+ raise RuntimeError(+ f"{self.secondary} is no longer idle ({free} of {total} MiB free)"+ )reserve = _replica_reserve_mib(free, total)if free is not None and need_mib + reserve > free:raise RuntimeError(@@ -3168,8 +3199,9 @@ def cfg_parallel_decline(# A replica is a whole denoiser on one card, which a denoiser cut across cards cannot be.if is_layer_split(pipe):return "denoiser is split across cards (layer split)"- # A replica takes a whole denoiser's worth of another card; automatic placement only borrows one to avoid offload.- if selection.automatic and mode != "force":+ # A replica takes a whole denoiser's worth of another card: automatic placement borrows one only when it is the+ # same card model and idle at load (install_cfg_parallel keeps only those), or always under force.+ if selection.automatic and mode != "force" and automatic_cfg_parallel_off():return f"automatic GPU placement (select several cards or set {CFG_PARALLEL_ENV}=force)"from .diffusion_bg_compile import load_time_enabled as bg_compile_enabled@@ -3243,6 +3275,10 @@ def install_cfg_parallel(and probes[o].name == probes[primary.index].name]candidates = same if cfg_parallel_mode() != "force" else list(selection.secondaries)+ automatic = selection.automatic and cfg_parallel_mode() != "force"+ if automatic:+ # nothing else may live on a card Automatic borrows for a replica+ candidates = [o for o in candidates if _idle_card(probes.get(o))]try:placed = ((_PLACEMENTS.get(pipe) or {}).get("placement") or {}).values()except TypeError:@@ -3252,6 +3288,11 @@ def install_cfg_parallel(candidates = [o for o in candidates if f"cuda:{o}" not in occupied]if not candidates and occupied:reason = f"the only replica card ({', '.join(sorted(occupied))}) holds the split's components"+ elif not candidates and automatic and same:+ reason = (+ f"automatic GPU placement: no idle card for a replica (more than "+ f"{AUTO_CFG_PARALLEL_IDLE_USED_MIB} MiB in use; select several cards or set {CFG_PARALLEL_ENV}=force)"+ )elif not candidates:reason = "secondary card is a different model (bit-identity needs the same kernels)"else:@@ -3285,6 +3326,7 @@ def install_cfg_parallel(denoiser, primary = primary, secondary = f"cuda:{best}", logger = logger)router.inner = graph+ router.automatic_idle_only = automatictry:_CFG_ROUTERS[pipe] = routerexcept TypeError:diff --git a/studio/backend/tests/test_diffusion_auto_placement.py b/studio/backend/tests/test_diffusion_auto_placement.pyindex 835ec3f4f44..2da99bf3c50 100644--- a/studio/backend/tests/test_diffusion_auto_placement.py+++ b/studio/backend/tests/test_diffusion_auto_placement.py@@ -261,13 +261,15 @@ def test_a_fits_one_card_uses_one_card_and_no_cfg_parallel(monkeypatch):d = decide(monkeypatch, host, _sizes(dit = 3900, te = 1600))assert d.plan is d.one_card and d.plan.offload_policy == dm.OFFLOAD_NONEassert d.plan.secondary_ordinal is None and d.plan.layer_split is None- assert d.cfg_parallel is not None and "automatic" in d.cfg_parallel+ # Automatic now offers CFG-parallel on an idle card of the same model: declined here only because the fake+ # pipeline has no denoiser module (UNSLOTH_DIFFUSION_CFG_PARALLEL_AUTO=0 restores the automatic decline)+ assert d.cfg_parallel is not None and "no DiT denoiser" in d.cfg_parallelp = _placement(d)assert p["chosen"] == "one_card"assert p["summary"].startswith("placement: one card: everything resident on cuda:0")kinds = {r["kind"]: r["reason"] for r in p["rejected"]}assert kinds["companion_split"].startswith("not needed")- assert "automatic" in kinds["cfg_parallel"]+ assert "no DiT denoiser" in kinds["cfg_parallel"]assert set(host.mem_get_info_calls) <= {0}@@ -288,7 +290,7 @@ def test_b_companion_split_puts_the_text_encoder_on_the_second_card(monkeypatch)assert d.plan.offload_policy == dm.OFFLOAD_NONE and d.plan.secondary_ordinal == 1assert "text_encoder" in d.plan.secondary_componentsassert d.plan.layer_split is None- assert d.cfg_parallel is not None and "automatic" in d.cfg_parallel+ assert d.cfg_parallel is not None and "no DiT denoiser" in d.cfg_parallelp = _placement(d)assert p["chosen"] == "companion_split"assert "text_encoder" in p["summary"] and "on cuda:1" in p["summary"]diff --git a/studio/backend/tests/test_diffusion_multigpu.py b/studio/backend/tests/test_diffusion_multigpu.pyindex 60c749b1ace..7c8a5a6282d 100644--- a/studio/backend/tests/test_diffusion_multigpu.py+++ b/studio/backend/tests/test_diffusion_multigpu.py@@ -1879,11 +1879,14 @@ def test_automatic_load_splits_only_when_one_card_would_offload(monkeypatch):assert fits.secondary_ordinal is None-def test_automatic_placement_does_not_arm_cfg_parallel(monkeypatch):+def test_automatic_placement_arms_cfg_parallel_only_with_the_auto_lever(monkeypatch):class Pipe:transformer = _Dit()automatic = mg.MultiGpuSelection(primary = 0, secondaries = (1,), automatic = True)+ # default: past the automatic gate (install_cfg_parallel then keeps only idle cards of the same model)+ assert "CUDA" in mg.cfg_parallel_decline(Pipe(), offload_policy = "none", selection = automatic)+ monkeypatch.setenv(mg.AUTO_CFG_PARALLEL_ENV, "0")assert "automatic" in mg.cfg_parallel_decline(Pipe(), offload_policy = "none", selection = automatic)@@ -1918,14 +1921,20 @@ def test_begin_load_marks_an_unpicked_load_automatic(module_file):assert ast.unparse(value.orelse.orelse) == "[]"-def test_automatic_selection_leaves_module_compile_alone(monkeypatch):+def test_automatic_selection_leaves_module_compile_alone_without_the_auto_lever(monkeypatch):def original(self, *args, **kwargs):return selfmonkeypatch.setattr(torch.nn.Module, "compile", original)+ monkeypatch.setenv(mg.AUTO_CFG_PARALLEL_ENV, "0")automatic = mg.MultiGpuSelection(primary = 0, secondaries = (1,), automatic = True)with mg.selection_scope(automatic):assert torch.nn.Module.compile is original+ monkeypatch.delenv(mg.AUTO_CFG_PARALLEL_ENV)+ with mg.selection_scope(automatic):+ # Automatic may build a CFG replica, which re-applies the recorded compile arguments+ assert getattr(torch.nn.Module.compile, "_unsloth_recorder", False)+ monkeypatch.setattr(torch.nn.Module, "compile", original)with mg.selection_scope(mg.MultiGpuSelection(primary = 0, secondaries = (1,))):assert getattr(torch.nn.Module.compile, "_unsloth_recorder", False)diff --git a/studio/backend/tests/test_diffusion_unet_cfg_parallel.py b/studio/backend/tests/test_diffusion_unet_cfg_parallel.pyindex 199e1990b5c..a5ab5c0a36f 100644--- a/studio/backend/tests/test_diffusion_unet_cfg_parallel.py+++ b/studio/backend/tests/test_diffusion_unet_cfg_parallel.py@@ -224,3 +224,89 @@ def test_unet_compiled_whole_after_install_runs_whole_on_the_source():unet._compiled_call_impl = lambda *a, **k: unet.forward(*a, **k)_sdxl_loop(unet, torch.randn(1, 4, 8, 8), steps = 2)assert unet.calls == [2, 2] and replicas == []+++class _Dit(torch.nn.Module):+ def __init__(self):+ super().__init__()+ self.proj = torch.nn.Linear(4, 4)++ def forward(+ self,+ hidden_states,+ timestep = None,+ encoder_hidden_states = None,+ return_dict = False,+ ):+ return (self.proj(hidden_states),)+++def _automatic_install(+ monkeypatch,+ used_mib,+ names = ("Tesla T4", "Tesla T4"),+ env = None,+):+ class Pipe:+ transformer = _Dit()++ probes = {+ o: mg.DeviceProbe(ordinal = o, name = names[o], total_mib = 15360, free_mib = 15360 - used_mib[o])+ for o in (0, 1)+ }+ if env is not None:+ monkeypatch.setenv(mg.AUTO_CFG_PARALLEL_ENV, env)+ monkeypatch.setattr(mg, "_module_device", lambda m: torch.device("cuda", 0))+ monkeypatch.setattr(+ mg, "probe_devices", lambda ordinals, **kw: {o: probes[o] for o in ordinals}+ )+ monkeypatch.setattr(mg, "_hooks_present", lambda m: None)+ monkeypatch.setattr(mg, "is_layer_split", lambda p: False, raising = False)+ pipe = Pipe()+ try:+ with mg.selection_scope(mg.MultiGpuSelection(primary = 0, secondaries = (1,), automatic = True)):+ return mg.install_cfg_parallel(pipe, offload_policy = "none")+ finally:+ mg.uninstall_cfg_parallel(pipe)+++def test_automatic_arms_cfg_parallel_on_an_idle_card_of_the_same_model(monkeypatch):+ assert _automatic_install(monkeypatch, used_mib = (9000, 3)) is None+++def test_automatic_keeps_a_busy_second_card_free(monkeypatch):+ reason = _automatic_install(monkeypatch, used_mib = (9000, 4000))+ assert reason is not None and "no idle card" in reason+++def test_automatic_never_borrows_a_different_card_model(monkeypatch):+ reason = _automatic_install(monkeypatch, used_mib = (9000, 3), names = ("Tesla T4", "Tesla P4"))+ assert reason is not None and "different model" in reason+++def test_automatic_cfg_parallel_kill_switch(monkeypatch):+ reason = _automatic_install(monkeypatch, used_mib = (9000, 3), env = "0")+ assert reason is not None and "automatic GPU placement" in reason+++def test_automatic_selection_records_compile_arguments_for_a_replica(monkeypatch):+ calls = []+ monkeypatch.setattr(mg, "install_compile_recorder", lambda: calls.append(1) or True)+ with mg.selection_scope(mg.MultiGpuSelection(primary = 0, secondaries = (1,), automatic = True)):+ pass+ assert calls == [1]+ monkeypatch.setenv(mg.AUTO_CFG_PARALLEL_ENV, "0")+ with mg.selection_scope(mg.MultiGpuSelection(primary = 0, secondaries = (1,), automatic = True)):+ pass+ assert calls == [1]+++def test_automatic_replica_is_not_built_on_a_card_that_got_busy(monkeypatch):+ unet = UNet2DConditionModel()+ router, replicas = _router(unet)+ router.automatic_idle_only = True+ monkeypatch.setattr(router, "_secondary_free_total_mib", lambda: (9000, 15360))+ lat = torch.randn(1, 4, 8, 8)+ _sdxl_loop(unet, lat, steps = 2)+ assert replicas == [] and "no longer idle" in (router.disabled_reason or "")+ assert unet.calls[-1] == 2 # whole on the source from then on