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: skip the cuDNN benchmark search for the MiniMax-H3 audio VAE on A100 / B200 / RTX PRO 6000 (first render up to a minute faster, 25-29 GiB lower peak) (#12040)

Daniel Han3a092d82127d
diff --git a/studio/backend/core/inference/diffusion_speed.py b/studio/backend/core/inference/diffusion_speed.py
index 7acaabbf63a..fbd5f0d9093 100644
--- a/studio/backend/core/inference/diffusion_speed.py
+++ b/studio/backend/core/inference/diffusion_speed.py
@@ -108,6 +108,50 @@ def fp16_accumulation_scope(value: bool) -> Iterator[None]:
)
+_CUDNN_BENCH_LOCK = threading.RLock()
+_cudnn_bench_scopes: list = []
+_cudnn_bench_base: Optional[bool] = None
+
+
+def _read_cudnn_benchmark(cudnn: Any) -> bool:
+ with _CUDNN_BENCH_LOCK:
+ if _cudnn_bench_scopes:
+ return bool(_cudnn_bench_base)
+ return bool(cudnn.benchmark)
+
+
+def _write_cudnn_benchmark(cudnn: Any, value: Any) -> None:
+ global _cudnn_bench_base
+ with _CUDNN_BENCH_LOCK:
+ if _cudnn_bench_scopes:
+ _cudnn_bench_base = bool(value)
+ else:
+ cudnn.benchmark = bool(value)
+
+
+@contextmanager
+def cudnn_benchmark_scope(value: bool) -> Iterator[None]:
+ """Hold ``cudnn.benchmark`` at ``value`` for the body, then restore the latest process value."""
+ global _cudnn_bench_base
+ import torch
+
+ cudnn = torch.backends.cudnn
+ token = object()
+ with _CUDNN_BENCH_LOCK:
+ if not _cudnn_bench_scopes:
+ _cudnn_bench_base = bool(cudnn.benchmark)
+ _cudnn_bench_scopes.append((token, bool(value)))
+ cudnn.benchmark = bool(value)
+ try:
+ yield
+ finally:
+ with _CUDNN_BENCH_LOCK:
+ _cudnn_bench_scopes[:] = [e for e in _cudnn_bench_scopes if e[0] is not token]
+ cudnn.benchmark = (
+ _cudnn_bench_scopes[-1][1] if _cudnn_bench_scopes else bool(_cudnn_bench_base)
+ )
+
+
def snapshot_backend_flags() -> Optional[dict]:
"""Capture the process-wide torch backend flags this layer may mutate, for restore on unload. None
without torch. Each flag is read defensively: a build missing one still captures the rest."""
@@ -126,7 +170,7 @@ def snapshot_backend_flags() -> Optional[dict]:
if hasattr(cudnn, "allow_tf32"):
state["cudnn_tf32"] = bool(cudnn.allow_tf32)
if hasattr(cudnn, "benchmark"):
- state["cudnn_benchmark"] = bool(cudnn.benchmark)
+ state["cudnn_benchmark"] = _read_cudnn_benchmark(cudnn)
inductor_cfg = _inductor_config()
if inductor_cfg is not None:
for attr, key in _INDUCTOR_FLAGS:
@@ -183,7 +227,11 @@ def restore_backend_flags(state: Optional[dict]) -> None:
pass
cudnn = getattr(torch.backends, "cudnn", None)
_set(cudnn, "allow_tf32", "cudnn_tf32")
- _set(cudnn, "benchmark", "cudnn_benchmark")
+ if cudnn is not None and "cudnn_benchmark" in state and hasattr(cudnn, "benchmark"):
+ try:
+ _write_cudnn_benchmark(cudnn, state["cudnn_benchmark"])
+ except Exception: # noqa: BLE001 - best-effort per-flag restore
+ pass
inductor_cfg = _inductor_config()
for attr, key in _INDUCTOR_FLAGS:
_set(inductor_cfg, attr, key)
@@ -1195,7 +1243,7 @@ def _enable_cudnn_benchmark(logger: Any) -> bool:
# On ROCm this is MIOpen's exhaustive search: a first VAE decode tuned for 10 to 23 minutes and crashed a gfx1030.
if _module_is_rocm(torch):
return False
- torch.backends.cudnn.benchmark = True
+ _write_cudnn_benchmark(torch.backends.cudnn, True)
return True
except Exception as exc: # noqa: BLE001 - optimisation only
_warn(logger, "cudnn_benchmark", exc)
diff --git a/studio/backend/core/inference/video.py b/studio/backend/core/inference/video.py
index 78565c610f2..2fe21c5b1ff 100644
--- a/studio/backend/core/inference/video.py
+++ b/studio/backend/core/inference/video.py
@@ -6005,6 +6005,13 @@ class VideoBackend:
speed_optims = speed_optims + tuple(f"h3_vae_{name}" for name in vae_levers)
except Exception as exc: # noqa: BLE001 -- optimisation only, never fail a load
logger.warning("video.h3_vae_fast failed, keeping the stock VAE: %s", exc)
+ if "cudnn_benchmark" in speed_optims:
+ try:
+ from .video_minimax_h3_vae import install_audio_vae_without_cudnn_benchmark
+ if install_audio_vae_without_cudnn_benchmark(getattr(pipe, "audio_vae", None)):
+ logger.info("video.h3_audio_vae: cudnn.benchmark held off for the audio VAE")
+ except Exception as exc: # noqa: BLE001 -- optimisation only, never fail a load
+ logger.warning("video.h3_audio_vae: keeping the stock audio VAE: %s", exc)
resolved = build_resolved_record(
{
diff --git a/studio/backend/core/inference/video_minimax_h3_vae.py b/studio/backend/core/inference/video_minimax_h3_vae.py
index 826c1571340..6ca74dfd5b8 100644
--- a/studio/backend/core/inference/video_minimax_h3_vae.py
+++ b/studio/backend/core/inference/video_minimax_h3_vae.py
@@ -1178,6 +1178,45 @@ def _install_decode_scope(vae: Any, *, fp16_accum: bool) -> bool:
return True
+# Skipping the search measured <= 1.4% slower here; a T4 / L4 still gain 17-19% / 2-8% from it, so they keep it.
+_AUDIO_VAE_NO_SEARCH_CAPABILITIES = frozenset({(8, 0), (10, 0), (12, 0)})
+
+
+def _audio_vae_search_gains_nothing() -> bool:
+ try:
+ import torch
+ return tuple(torch.cuda.get_device_capability()) in _AUDIO_VAE_NO_SEARCH_CAPABILITIES
+ except Exception: # noqa: BLE001
+ return False
+
+
+def install_audio_vae_without_cudnn_benchmark(audio_vae: Any) -> bool:
+ """Hold ``cudnn.benchmark`` off for the audio VAE (host seconds + huge workspaces per new shape). Idempotent."""
+ if audio_vae is None or getattr(audio_vae, "_unsloth_no_cudnn_benchmark", False):
+ return False
+ if not _audio_vae_search_gains_nothing():
+ return False
+
+ from .diffusion_speed import cudnn_benchmark_scope
+
+ def _held_off(stock: Any) -> Any:
+ def call(self, *args, **kwargs):
+ with cudnn_benchmark_scope(False):
+ return stock(*args, **kwargs)
+
+ return call
+
+ wrapped = False
+ for name in ("decode", "encode"):
+ stock = getattr(audio_vae, name, None)
+ if callable(stock):
+ setattr(audio_vae, name, types.MethodType(_held_off(stock), audio_vae))
+ wrapped = True
+ if wrapped:
+ audio_vae._unsloth_no_cudnn_benchmark = True
+ return wrapped
+
+
@lru_cache(maxsize = 4)
def _triton_version_ok(version: Optional[str] = None) -> bool:
if version is None:
diff --git a/studio/backend/tests/test_video_minimax_h3_vae.py b/studio/backend/tests/test_video_minimax_h3_vae.py
index d3648f1b9c2..5e4fb344e8e 100644
--- a/studio/backend/tests/test_video_minimax_h3_vae.py
+++ b/studio/backend/tests/test_video_minimax_h3_vae.py
@@ -811,6 +811,252 @@ def test_the_video_backend_wires_the_layer_into_the_h3_load_only():
assert compile_settle.lineno < settle.lineno
+def test_the_h3_load_holds_cudnn_benchmark_off_for_the_audio_decode_only_when_it_engaged():
+ import ast
+ import pathlib
+
+ source = (pathlib.Path(H.__file__).parent / "video.py").read_text(encoding = "utf-8")
+ tree = ast.parse(source)
+ installs = [
+ c
+ for c in ast.walk(tree)
+ if isinstance(c, ast.Call)
+ and getattr(c.func, "id", None) == "install_audio_vae_without_cudnn_benchmark"
+ ]
+ (install,) = installs
+ load = next(
+ n
+ for n in ast.walk(tree)
+ if isinstance(n, ast.FunctionDef) and n.name == "_load_h3_modular_pipeline"
+ )
+ assert any(c is install for c in ast.walk(load))
+ guard = next(
+ n
+ for n in ast.walk(load)
+ if isinstance(n, ast.If) and any(c is install for c in ast.walk(n))
+ )
+ assert "cudnn_benchmark" in ast.unparse(guard.test) and "speed_optims" in ast.unparse(
+ guard.test
+ )
+
+
+def _ampere(monkeypatch):
+ monkeypatch.setattr(H, "_audio_vae_search_gains_nothing", lambda: True)
+
+
+class _AudioVAE:
+ def __init__(self):
+ self.seen = []
+
+ def decode(self, z, **kwargs):
+ self.seen.append(torch.backends.cudnn.benchmark)
+ return (z,)
+
+ def encode(self, x, **kwargs):
+ self.seen.append(("encode", torch.backends.cudnn.benchmark))
+ return (x,)
+
+
[email protected]("before", [True, False])
+def test_audio_decode_runs_without_cudnn_benchmark_and_restores_it(before, _ampere):
+ from core.inference import diffusion_speed as S
+ prev = torch.backends.cudnn.benchmark
+ try:
+ torch.backends.cudnn.benchmark = before
+ vae = _AudioVAE()
+ assert H.install_audio_vae_without_cudnn_benchmark(vae)
+ assert not H.install_audio_vae_without_cudnn_benchmark(vae), "installs once"
+ z = torch.zeros(1)
+ assert vae.decode(z, return_dict = False)[0] is z
+ vae.decode(z)
+ assert vae.encode(z, return_dict = False)[0] is z
+ assert vae.seen == [False, False, ("encode", False)]
+ assert torch.backends.cudnn.benchmark is before
+ assert not S._cudnn_bench_scopes
+ finally:
+ torch.backends.cudnn.benchmark = prev
+
+
+def test_audio_decode_scope_restores_after_a_raising_decode(_ampere):
+ prev = torch.backends.cudnn.benchmark
+
+ class _Raises:
+ def decode(self, z):
+ raise RuntimeError("boom")
+
+ try:
+ torch.backends.cudnn.benchmark = True
+ vae = _Raises()
+ assert H.install_audio_vae_without_cudnn_benchmark(vae)
+ with pytest.raises(RuntimeError, match = "boom"):
+ vae.decode(0)
+ assert torch.backends.cudnn.benchmark is True
+ finally:
+ torch.backends.cudnn.benchmark = prev
+
+
+def test_audio_decode_scope_ignores_missing_decoders(_ampere):
+ assert not H.install_audio_vae_without_cudnn_benchmark(None)
+ assert not H.install_audio_vae_without_cudnn_benchmark(types.SimpleNamespace(decode = None))
+
+
+def test_audio_decode_scope_wraps_a_decode_only_vae(_ampere):
+ prev = torch.backends.cudnn.benchmark
+ seen = []
+
+ class _DecodeOnly:
+ def decode(self, z):
+ seen.append(torch.backends.cudnn.benchmark)
+ return z
+
+ try:
+ torch.backends.cudnn.benchmark = True
+ vae = _DecodeOnly()
+ assert H.install_audio_vae_without_cudnn_benchmark(vae)
+ assert vae.decode(1) == 1 and seen == [False] and not hasattr(vae, "encode")
+ assert torch.backends.cudnn.benchmark is True
+ finally:
+ torch.backends.cudnn.benchmark = prev
+
+
[email protected]("mid", [True, False])
+def test_cudnn_benchmark_written_mid_decode_survives_it(mid, _ampere):
+ from core.inference import diffusion_speed as S
+
+ seen = {}
+
+ class _VAE:
+ def decode(self, z):
+ seen["snapshot"] = S.snapshot_backend_flags()["cudnn_benchmark"]
+ S.restore_backend_flags({"cudnn_benchmark": mid})
+ seen["after_write"] = torch.backends.cudnn.benchmark
+ return z
+
+ prev = torch.backends.cudnn.benchmark
+ try:
+ torch.backends.cudnn.benchmark = True
+ vae = _VAE()
+ assert H.install_audio_vae_without_cudnn_benchmark(vae)
+ vae.decode(0)
+ assert seen["snapshot"] is True, "a snapshot taken mid-decode must see the process value"
+ assert seen["after_write"] is False, "the decode keeps its own value until it ends"
+ assert (
+ torch.backends.cudnn.benchmark is mid
+ ), "the write made during the decode must survive it"
+ assert not S._cudnn_bench_scopes
+ finally:
+ torch.backends.cudnn.benchmark = prev
+
+
+def test_enabling_cudnn_benchmark_mid_decode_lands_after_it(monkeypatch, _ampere):
+ from core.inference import diffusion_speed as S
+
+ monkeypatch.setattr("core._torchao_stub._module_is_rocm", lambda torch: False)
+ seen = {}
+
+ class _VAE:
+ def decode(self, z):
+ seen["enabled"] = S._enable_cudnn_benchmark(None)
+ seen["inside"] = torch.backends.cudnn.benchmark
+ return z
+
+ prev = torch.backends.cudnn.benchmark
+ try:
+ torch.backends.cudnn.benchmark = False
+ vae = _VAE()
+ assert H.install_audio_vae_without_cudnn_benchmark(vae)
+ vae.decode(0)
+ assert seen == {"enabled": True, "inside": False}
+ assert torch.backends.cudnn.benchmark is True
+ finally:
+ torch.backends.cudnn.benchmark = prev
+
+
+ "capability, installs",
+ [
+ ((7, 5), False),
+ ((8, 0), True),
+ ((8, 6), False),
+ ((8, 9), False),
+ ((9, 0), False),
+ ((10, 0), True),
+ ((12, 0), True),
+ (RuntimeError("no GPU"), False),
+ ],
+)
+def test_the_audio_vae_keeps_the_search_where_it_was_not_measured_to_gain_nothing(
+ monkeypatch, capability, installs
+):
+ def probe(device = None):
+ if isinstance(capability, Exception):
+ raise capability
+ return capability
+
+ monkeypatch.setattr(torch.cuda, "get_device_capability", probe)
+ vae = _AudioVAE()
+ stock = vae.decode
+ assert H.install_audio_vae_without_cudnn_benchmark(vae) is installs
+ assert (vae.decode == stock) is not installs
+
+
+def test_cudnn_benchmark_scopes_that_close_out_of_order():
+ from core.inference import diffusion_speed as S
+
+ cudnn = torch.backends.cudnn
+ prev = cudnn.benchmark
+ try:
+ cudnn.benchmark = True
+ a, b = S.cudnn_benchmark_scope(False), S.cudnn_benchmark_scope(True)
+ a.__enter__()
+ assert cudnn.benchmark is False
+ b.__enter__()
+ assert cudnn.benchmark is True
+ a.__exit__(None, None, None)
+ assert cudnn.benchmark is True, "the scope still open keeps its value"
+ b.__exit__(None, None, None)
+ assert cudnn.benchmark is True and not S._cudnn_bench_scopes
+ cudnn.benchmark = False
+ a, b = S.cudnn_benchmark_scope(False), S.cudnn_benchmark_scope(False)
+ a.__enter__()
+ b.__enter__()
+ b.__exit__(None, None, None)
+ a.__exit__(None, None, None)
+ assert cudnn.benchmark is False and not S._cudnn_bench_scopes
+ finally:
+ cudnn.benchmark = prev
+
+
+def test_cudnn_benchmark_scopes_on_two_threads_restore_the_process_value():
+ import threading
+
+ from core.inference import diffusion_speed as S
+
+ cudnn = torch.backends.cudnn
+ prev = cudnn.benchmark
+ inside, release = threading.Event(), threading.Event()
+
+ def other():
+ with S.cudnn_benchmark_scope(False):
+ inside.set()
+ release.wait(5)
+
+ try:
+ cudnn.benchmark = True
+ t = threading.Thread(target = other)
+ t.start()
+ assert inside.wait(5)
+ with S.cudnn_benchmark_scope(False):
+ release.set()
+ t.join(5)
+ assert not t.is_alive()
+ assert cudnn.benchmark is True and not S._cudnn_bench_scopes
+ finally:
+ release.set()
+ cudnn.benchmark = prev
+
+
@pytest.mark.skipif(H._kernels() is None, reason = "needs Triton")
def test_kernel_annotations_resolve_against_the_module_globals():
# Triton <= 3.2 resolves kernel annotations in module globals; a closure-local ``tl`` NameErrors there