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: finish the backend CI cleanup #8506 started (#8554)
Daniel Hanb01c8b9cd94b
diff --git a/studio/backend/core/inference/stt_sidecar.py b/studio/backend/core/inference/stt_sidecar.pyindex 3f379c94047..878f527c7d4 100644--- a/studio/backend/core/inference/stt_sidecar.py+++ b/studio/backend/core/inference/stt_sidecar.py@@ -928,8 +928,15 @@ def _training_active() -> bool:return False-def _clear_device_cache(device: Optional[str]) -> None:- gc.collect()+def _clear_device_cache(device: Optional[str], collect: bool = True) -> None:+ """Drop the unreferenced model, then hand its blocks back to the allocator.++ ``collect = False`` for a caller that has just collected and dropped nothing since: a full+ collection is not free (a long-lived backend reaches millions of tracked objects, where one+ pass costs about a second), and the cancel path below runs this twice in a row while it+ holds the model lock that ``wait_for_load_to_settle`` waits on."""+ if collect:+ gc.collect()try:import torchif device == "cuda":@@ -1347,8 +1354,14 @@ class WhisperSttSidecar:except SttLoadCancelledError:candidate = Noneif resident_released:+ # _release_engine_locked already collected, and the candidate was dropped+ # before it ran, so nothing has become garbage since. This second call is+ # only here to empty the cache of the device this LOAD picked, which need+ # not be the resident's, so it keeps the sweep and skips the collection.self._release_engine_locked()- _clear_device_cache(device)+ _clear_device_cache(device, collect = False)+ else:+ _clear_device_cache(device)raisefinally:self._end_load(cancel_event)diff --git a/studio/backend/tests/conftest.py b/studio/backend/tests/conftest.pyindex 2d466acf62e..621702dcfc0 100644--- a/studio/backend/tests/conftest.py+++ b/studio/backend/tests/conftest.py@@ -860,3 +860,38 @@ def healthy_diffusers(monkeypatch):if _real is not None and hasattr(_real, attr):setattr(proxy, attr, getattr(_real, attr))monkeypatch.setitem(sys.modules, "diffusers", proxy)+++def real_prequant_safe_globals(monkeypatch):+ """Stand in for the allowlist entries this host cannot import, and hand back the real resolver.++ The file header promises these tests run without torchao, and the Backend CI image keeps that+ promise literally: it installs torch and transformers and no torchao at all. Production then+ resolves not one entry of ``_PREQUANT_SAFE_GLOBALS``, the registration floor ("TorchVersion+ plus at least one real torchao class") is not met, every load refuses, and 19 tests in here+ fail on ``assert None is not None`` -- saying nothing whatever about the loader they are+ about. ``test_diffusion_convrot.py`` loads through the same registration and needs it too,+ which is why this lives here rather than in one of the two files. The tests also swap ``sys.modules["torch"]`` for a bare module while a load runs, so+ even ``torch.torch_version`` is unimportable at that moment, torchao or no torchao.++ Standing in only for the names that did NOT resolve keeps a host that has torchao testing the+ real classes. Which names a given release actually ships is asked separately, by+ ``test_the_registration_floor_needs_a_real_torchao``, which skips rather than pretends -- and+ ``test_the_registration_refuses_when_nothing_resolves`` pins the refusal itself, so the gate+ that the CI image trips is still under test rather than merely worked around.+ """+ import core.inference.diffusion_prequant as pq++ resolver = pq._prequant_safe_globals+ resolved = {name: obj for obj, name in resolver()}+ pairs = [+ (resolved.get(f"{module}.{name}") or type(name, (), {}), f"{module}.{name}")+ for module, name in pq._PREQUANT_SAFE_GLOBALS+ ]+ monkeypatch.setattr(pq, "_prequant_safe_globals", lambda: pairs)+ # Per test rather than per process: the memo is a module global, so one test's registration+ # would otherwise decide the answer for every test that ran after it.+ monkeypatch.setattr(pq, "_SAFE_GLOBALS_REGISTERED", None)+ monkeypatch.setattr(pq, "_RESOLVED_SAFE_GLOBALS", set())+ return resolverdiff --git a/studio/backend/tests/test_diffusion_convrot.py b/studio/backend/tests/test_diffusion_convrot.pyindex a8a3b1b7cae..6fe28162c4d 100644--- a/studio/backend/tests/test_diffusion_convrot.py+++ b/studio/backend/tests/test_diffusion_convrot.py@@ -44,6 +44,13 @@ from core.inference.diffusion_convrot import ( # noqa: E402rotation_metadata_error,)+[email protected](autouse = True)+def _pin_prequant_safe_globals(real_prequant_safe_globals):+ """Apply the shared stand-in allowlist (see conftest) to every test in this module."""+ return real_prequant_safe_globals++GROUP = 16 # a power of 4, small enough to keep the test model tinydiff --git a/studio/backend/tests/test_diffusion_prequant.py b/studio/backend/tests/test_diffusion_prequant.pyindex 331160e9c80..224ed17f590 100644--- a/studio/backend/tests/test_diffusion_prequant.py+++ b/studio/backend/tests/test_diffusion_prequant.py@@ -29,35 +29,9 @@ from core.inference.diffusion_prequant import (@pytest.fixture(autouse = True)-def real_prequant_safe_globals(monkeypatch):- """Stand in for the allowlist entries this host cannot import, and hand back the real resolver.-- The file header promises these tests run without torchao, and the Backend CI image keeps that- promise literally: it installs torch and transformers and no torchao at all. Production then- resolves not one entry of ``_PREQUANT_SAFE_GLOBALS``, the registration floor ("TorchVersion- plus at least one real torchao class") is not met, every load refuses, and 19 tests in here- fail on ``assert None is not None`` -- saying nothing whatever about the loader they are- about. The tests also swap ``sys.modules["torch"]`` for a bare module while a load runs, so- even ``torch.torch_version`` is unimportable at that moment, torchao or no torchao.-- Standing in only for the names that did NOT resolve keeps a host that has torchao testing the- real classes. Which names a given release actually ships is asked separately, by- ``test_the_registration_floor_needs_a_real_torchao``, which skips rather than pretends -- and- ``test_the_registration_refuses_when_nothing_resolves`` pins the refusal itself, so the gate- that the CI image trips is still under test rather than merely worked around.- """- resolver = pq._prequant_safe_globals- resolved = {name: obj for obj, name in resolver()}- pairs = [- (resolved.get(f"{module}.{name}") or type(name, (), {}), f"{module}.{name}")- for module, name in pq._PREQUANT_SAFE_GLOBALS- ]- monkeypatch.setattr(pq, "_prequant_safe_globals", lambda: pairs)- # Per test rather than per process: the memo is a module global, so one test's registration- # would otherwise decide the answer for every test that ran after it.- monkeypatch.setattr(pq, "_SAFE_GLOBALS_REGISTERED", None)- monkeypatch.setattr(pq, "_RESOLVED_SAFE_GLOBALS", set())- return resolver+def _pin_prequant_safe_globals(real_prequant_safe_globals):+ """Apply the shared stand-in allowlist (see conftest) to every test in this module."""+ return real_prequant_safe_globals# ── resolve_prequant_source ──────────────────────────────────────────────────────diff --git a/studio/backend/tests/test_research_runs_hardening.py b/studio/backend/tests/test_research_runs_hardening.pyindex b81342d54fd..9f5e90cb545 100644--- a/studio/backend/tests/test_research_runs_hardening.py+++ b/studio/backend/tests/test_research_runs_hardening.py@@ -1332,8 +1332,11 @@ def test_a_cancelled_send_is_only_discarded_once(monkeypatch):real_discard = research_runs.ResearchSupervisor._discard_taskasync def _counting_discard(self, run_id, task, what):- discards.append(what)- return await real_discard(self, run_id, task, what)+ started = time.monotonic()+ try:+ return await real_discard(self, run_id, task, what)+ finally:+ discards.append((what, time.monotonic() - started))monkeypatch.setattr(research_runs.ResearchSupervisor, "_discard_task", _counting_discard)@@ -1369,12 +1372,15 @@ def test_a_cancelled_send_is_only_discarded_once(monkeypatch):supervisor._check_active = _cancelled- started = time.monotonic()with pytest.raises(research_runs.RunCancelled):asyncio.run(supervisor._stream_completion(run, [{"role": "user"}], report_progress = False))- elapsed = time.monotonic() - started- assert [w for w in discards if w == "send"] == ["send"], f"discards: {discards}"- assert elapsed < 1.0, f"cancellation took {elapsed:.2f}s, more than one cleanup bound"+ assert [w for w, _ in discards if w == "send"] == ["send"], f"discards: {discards}"+ # Measured over the cleanup itself rather than over the test's wall clock. The bound is a+ # TIMER, so a second one shows up as time spent waiting; everything before the cancellation+ # is fixed setup that has nothing to do with this guarantee, and on a shared two-core runner+ # that setup alone reached 0.9s and failed the old whole-test budget on machine speed.+ waited = sum(seconds for _w, seconds in discards)+ assert waited < 2 * research_runs._STREAM_CLEANUP_TIMEOUT_SECONDS, f"discards: {discards}"def test_a_cancelled_stream_iterator_is_only_discarded_once(monkeypatch):@@ -1388,8 +1394,11 @@ def test_a_cancelled_stream_iterator_is_only_discarded_once(monkeypatch):real_discard = research_runs.ResearchSupervisor._discard_taskasync def _counting_discard(self, run_id, task, what):- discards.append(what)- return await real_discard(self, run_id, task, what)+ started = time.monotonic()+ try:+ return await real_discard(self, run_id, task, what)+ finally:+ discards.append((what, time.monotonic() - started))monkeypatch.setattr(research_runs.ResearchSupervisor, "_discard_task", _counting_discard)@@ -1424,13 +1433,13 @@ def test_a_cancelled_stream_iterator_is_only_discarded_once(monkeypatch):supervisor._check_active = _cancelled- started = time.monotonic()with pytest.raises(research_runs.RunCancelled):asyncio.run(supervisor._stream_completion(run, [{"role": "user"}], report_progress = False))- elapsed = time.monotonic() - started- iterator_discards = [w for w in discards if w == "stream_iterator"]+ iterator_discards = [w for w, _ in discards if w == "stream_iterator"]assert len(iterator_discards) == 1, f"discarded {len(iterator_discards)} times: {discards}"- assert elapsed < 1.0, f"cancellation took {elapsed:.2f}s, more than one cleanup bound"+ # The time spent WAITING on cleanup, not the test's wall clock: see the send-side test above.+ waited = sum(seconds for _w, seconds in discards)+ assert waited < 2 * research_runs._STREAM_CLEANUP_TIMEOUT_SECONDS, f"discards: {discards}"def test_stream_completion_first_output_timeout_survives_iterator_cleanup(monkeypatch):diff --git a/studio/backend/tests/test_stt_sidecar.py b/studio/backend/tests/test_stt_sidecar.pyindex 36094d536e1..cb07246d528 100644--- a/studio/backend/tests/test_stt_sidecar.py+++ b/studio/backend/tests/test_stt_sidecar.py@@ -775,6 +775,14 @@ def test_accelerator_load_failure_retries_on_cpu(monkeypatch):def test_pending_load_can_be_cancelled_without_waiting_for_model_lock(monkeypatch):+ # The bound that carries the contract is the CANCEL thread's: it must come back while the+ # build still holds the model lock, so two seconds against an indefinite wait is the whole+ # question. The other waits below are liveness only -- they say "this must happen", and the+ # assertion after each is what fails if it does not. Two seconds there was a budget on+ # runner speed instead: after the build is released the load thread still has to be+ # scheduled and run the cancel path's two full gc.collect()s, which a loaded two-core CI+ # runner did not finish inside it.+ settle = 30.0_install_fake_torch(monkeypatch)sidecar = WhisperSttSidecar(keep_alive_seconds = 0)build_started = threading.Event()@@ -783,7 +791,7 @@ def test_pending_load_can_be_cancelled_without_waiting_for_model_lock(monkeypatcdef build(_repo, _device, _dtype, _cancel_event):build_started.set()- assert release_build.wait(timeout = 2)+ assert release_build.wait(timeout = settle)return object(), object()def run_load():@@ -798,19 +806,19 @@ def test_pending_load_can_be_cancelled_without_waiting_for_model_lock(monkeypatcload_thread = threading.Thread(target = run_load)load_thread.start()- assert build_started.wait(timeout = 2)+ assert build_started.wait(timeout = settle)result = []cancel_thread = threading.Thread(target = lambda: result.append(sidecar.cancel_pending_load()))cancel_thread.start()- cancel_thread.join(timeout = 2)+ cancel_thread.join(timeout = 2) # the contract: back while the build still holds the lockassert not cancel_thread.is_alive()assert result == [True]assert load_thread.is_alive()release_build.set()- load_thread.join(timeout = 2)+ load_thread.join(timeout = settle)assert not load_thread.is_alive()assert len(errors) == 1