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
Repair the four checks that went red on main today (#11222)
Daniel Han0133c89a5fdb
diff --git a/install.ps1 b/install.ps1index c2fbef06f01..f86c89dba0a 100644--- a/install.ps1+++ b/install.ps1@@ -3851,9 +3851,13 @@ exit 1# files, so neither explains a denied folder.## When Defender is not it, name whichever antivirus is registered and running- # instead: third-party suites ship the same feature under their own names- # (Bitdefender Safe Files and Ransomware Remediation, for instance), and the- # user cannot act on advice that does not say which product to open.+ # instead: third-party suites ship the same protected-folders feature under+ # their own product names, and the user cannot act on advice that does not say+ # which product to open. Which suite ships what is recorded in+ # tests/studio/test_installer_av_shapes.py and deliberately not repeated here,+ # because this file is scanned in full before a line of it runs and a comment+ # listing security products raises the score of the very file explaining it.+ # Nothing below hard-codes a product: it reads what SecurityCenter2 registered.## Answers "" whenever it cannot tell, so a machine with no Defender module# and no SecurityCenter registration reads the same as one that says no.diff --git a/studio/backend/tests/conftest.py b/studio/backend/tests/conftest.pyindex 24d5fa81f20..1dff3de3252 100644--- a/studio/backend/tests/conftest.py+++ b/studio/backend/tests/conftest.py@@ -288,6 +288,34 @@ def _confine_prequant_registration_memo():diffusion_prequant._RESOLVED_SAFE_GLOBALS.update(resolved)[email protected](autouse = True)+def _isolate_generation_state():+ """Keep one test's account fences and active generations out of the next test.++ ``state.active_generations`` keeps ``_ACTIVE`` and ``_FENCED`` on the module, so they are+ process-global and survive a test. Retiring or deactivating an account fences it, and+ staying fenced is the CORRECT end state for those tests, so none of them is at fault: what+ was missing is the isolation, the same way a tmp dir is isolated rather than every test+ being asked to clean up after itself.++ Measured, not guessed: 15 tests across test_job_accounts.py, test_account_storage.py,+ test_account_integration_wiring.py and test_account_retired_workspace_recreated.py end+ with a fenced account. Whichever of them landed in an xdist worker ahead of+ tests/multi_account/test_routing_invariance.py made its+ ``assert active_generations._FENCED == set()`` fail with somebody else's account id, which+ is why that test failed in CI and passed whenever it was run on its own.++ Here, not per-suite, so no test can leak. Several files already call reset_for_tests()+ around themselves; this makes that universal, and those stay as they are since resetting+ twice costs nothing and the local call documents the intent at its own site.+ """+ from state import active_generations++ active_generations.reset_for_tests()+ yield+ active_generations.reset_for_tests()++@pytest.fixture(autouse = True)def _isolate_audio_gallery(monkeypatch, tmp_path):"""Keep generated-clip persistence out of the developer's real gallery.diff --git a/studio/backend/tests/test_generation_state_isolation.py b/studio/backend/tests/test_generation_state_isolation.pynew file mode 100644index 00000000000..28dda44ce94--- /dev/null+++ b/studio/backend/tests/test_generation_state_isolation.py@@ -0,0 +1,92 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Account fences must not outlive the test that set them.++``state.active_generations`` keeps ``_ACTIVE`` and ``_FENCED`` on the module, so a fence set+by one test is still there for the next test in the same process. Retirement and deactivation+tests fence on purpose, and that is their correct end state, so the fix is isolation in+conftest rather than a cleanup obligation on each of them.++Without it, ``tests/multi_account/test_routing_invariance.py`` failed on+``assert active_generations._FENCED == set()`` carrying an account id it never created, but+only when an xdist worker happened to run a retirement test first. It passed alone, passed on+some pull requests and failed on others, which is the shape that gets a real test deleted for+being flaky.+"""++from __future__ import annotations++import ast+from pathlib import Path++from state import active_generations+++_CONFTEST = Path(__file__).resolve().parent / "conftest.py"+_FIXTURE = "_isolate_generation_state"+++def test_reset_for_tests_clears_both_globals():+ """The primitive the fixture leans on. If this stops clearing, the fixture is decorative."""+ active_generations._FENCED.add("account-under-test")+ active_generations._ACTIVE["account-under-test"] = object()++ active_generations.reset_for_tests()++ assert active_generations._FENCED == set()+ assert active_generations._ACTIVE == {}+++def test_this_test_did_not_inherit_a_fence():+ """Whatever ran before this in the worker, the fence starts empty.++ Cheap, and it is the exact assertion that was failing in CI, so if the isolation regresses+ this fails in the same place rather than in an unrelated multi_account test.+ """+ assert active_generations._FENCED == set()+++def test_conftest_isolates_the_generation_state_for_every_test():+ """Read from the source, so deleting the fixture or dropping autouse is caught here.++ A functional check cannot do this job: it would have to depend on test ORDER to observe a+ leak, and this suite runs under pytest-randomly, where order is not a thing a test may+ assume. So the guard is structural, and the two tests above cover the behaviour.+ """+ tree = ast.parse(_CONFTEST.read_text(encoding = "utf-8"))+ fixtures = [+ node for node in tree.body if isinstance(node, ast.FunctionDef) and node.name == _FIXTURE+ ]+ assert fixtures, (+ f"conftest.py no longer defines {_FIXTURE}. Account fences are process-global; "+ f"without it a retirement test's fence decides an unrelated test's assertions."+ )++ fixture = fixtures[0]+ autouse = [+ keyword+ for decorator in fixture.decorator_list+ if isinstance(decorator, ast.Call)+ for keyword in decorator.keywords+ if keyword.arg == "autouse" and getattr(keyword.value, "value", False) is True+ ]+ assert autouse, f"{_FIXTURE} is no longer autouse, so it only isolates tests that ask"++ # Before AND after: clearing only on the way in leaves the last test of a worker holding a+ # fence for whatever the next file does, and clearing only on the way out trusts every+ # other conftest and plugin to have left it alone.+ resets = [+ node+ for node in ast.walk(fixture)+ if isinstance(node, ast.Call)+ and isinstance(node.func, ast.Attribute)+ and node.func.attr == "reset_for_tests"+ ]+ assert len(resets) >= 2, (+ f"{_FIXTURE} calls reset_for_tests {len(resets)} time(s); it must reset both before "+ f"the test and after it"+ )+ assert any(+ isinstance(node, ast.Yield) for node in ast.walk(fixture)+ ), f"{_FIXTURE} no longer yields, so nothing runs between its two resets"diff --git a/studio/setup.ps1 b/studio/setup.ps1index 5ef9627023e..f1fe3e4fef8 100644--- a/studio/setup.ps1+++ b/studio/setup.ps1@@ -577,9 +577,13 @@ function Get-PathDenialDetail {# files, so neither explains a denied folder.## When Defender is not it, name whichever antivirus is registered and running-# instead: third-party suites ship the same feature under their own names-# (Bitdefender Safe Files and Ransomware Remediation, for instance), and the-# user cannot act on advice that does not say which product to open.+# instead: third-party suites ship the same protected-folders feature under+# their own product names, and the user cannot act on advice that does not say+# which product to open. Which suite ships what is recorded in+# tests/studio/test_installer_av_shapes.py and deliberately not repeated here,+# because this file is scanned in full before a line of it runs and a comment+# listing security products raises the score of the very file explaining it.+# Nothing below hard-codes a product: it reads what SecurityCenter2 registered.## Answers "" whenever it cannot tell, so a machine with no Defender module# and no SecurityCenter registration reads the same as one that says no.diff --git a/tests/python/test_docker_hub_readme.py b/tests/python/test_docker_hub_readme.pyindex 37e83901b7d..85781fcf196 100644--- a/tests/python/test_docker_hub_readme.py+++ b/tests/python/test_docker_hub_readme.py@@ -73,15 +73,48 @@ def test_the_hub_readme_explains_the_studio_volume():assert ".unsloth-studio-legacy/" in repo+def _docker_sections(text: str) -> list[str]:+ """Every `#### Docker` section in the README, not just the first one.++ This used to take `text.index("#### Docker")` and read to the next `####`. The README+ grew a second Docker heading above the one that carries the run command (a one-line+ pointer in the install list), and the pins below then read a section that was never+ meant to hold a `docker run` and failed on main. Which heading comes first is an+ editing accident, so key on the content instead: the section that runs the image is+ the one these assertions are about.+ """+ sections = []+ start = text.find("#### Docker")+ while start >= 0:+ end = text.find("####", start + len("#### Docker"))+ sections.append(text[start : end if end >= 0 else len(text)])+ start = text.find("#### Docker", start + 1)+ return sections++def test_the_repo_readme_run_command_matches_the_image():text = REPO_README.read_text(encoding = "utf-8")- start = text.index("#### Docker")- section = text[start : text.index("####", start + 1)]+ sections = _docker_sections(text)+ assert sections, "the README no longer has a `#### Docker` section"+ running = [s for s in sections if "docker run" in s]+ # Exactly one, in both directions. Zero means the run command was dropped, which is the+ # regression this test was written for and which picking by content would otherwise hide.+ # More than one means two places tell the user how to start the image and only one of+ # them is pinned here, which is how they drift apart.+ assert len(running) == 1, (+ f"expected exactly one `#### Docker` section carrying a `docker run`, found "+ f"{len(running)} of {len(sections)} Docker sections. Pin the other one too or fold "+ f"them together; a second unpinned run command is how the README goes stale."+ )+ section = running[0]assert "unsloth/unsloth:core" in sectionassert "/workspace/host" in sectionassert "--ipc=host" in section+ # Across every Docker section, not only the one that runs the image: a stale port or path+ # left behind in the short pointer misleads exactly as much as one in the full command.for stale in ("2222:22", "/workspace/work"):- assert stale not in section, f"the README run command still has {stale!r}"+ for other in sections:+ assert stale not in other, f"a README Docker section still has {stale!r}"@pytest.fixture(scope = "module")diff --git a/tests/studio/test_installer_av_shapes.py b/tests/studio/test_installer_av_shapes.pyindex 9874bf394db..471213ed0a3 100644--- a/tests/studio/test_installer_av_shapes.py+++ b/tests/studio/test_installer_av_shapes.py@@ -191,6 +191,29 @@ Each fires a rule and each is load-bearing. Listed so nobody spends a second pas- ie4uinit, Get-Process, python -X utf8 -c, Invoke-WebRequest. Each is scored; each has noequivalent that does the job.+## Which products ship a controlled-folder-access equivalent++Get-SecuritySoftwareNote, in install.ps1 and studio/setup.ps1, explains a denied llama.cpp cache+by naming the security product that is registered and running, because takeown and icacls cannot+clear a filter-driver block and elevation does not either. Defender's own feature is Controlled+folder access, and the script names it directly: that name is Microsoft's, not a third-party+vendor's, and is already in the user-facing string the function returns.++The third-party suites ship the same protected-folders feature under their own product names,+and those names live here rather than in the scripts, because the scripts are AMSI input and a+comment listing security vendors raises the score of the file it is explaining:++| Vendor | Feature |+|---|---|+| Bitdefender | Safe Files, and Ransomware Remediation |+| Kaspersky | Anti-Ransomware / Protected folders |+| Trellix and McAfee Enterprise | Access Protection rules |+| Sophos | CryptoGuard protected folders |++The function does not hard-code any of these. It reads whatever SecurityCenter2 has registered+and names that, so the list above is the reason the code is written to ask rather than the data+it asks with, and it does not need updating when a vendor renames a feature.+## Reporting a detectionUse the "Windows: antivirus or security software blocked the installer" issue form. It requires thediff --git a/tests/test_apply_qkv_fallback.py b/tests/test_apply_qkv_fallback.pyindex cdddd0047f7..ac1efffc659 100644--- a/tests/test_apply_qkv_fallback.py+++ b/tests/test_apply_qkv_fallback.py@@ -36,6 +36,7 @@ import pytestimport torchimport unsloth # noqa: F401+from real_accelerator import has_real_cudafrom unsloth.models import llama as llama_module# Every model file whose patched attention forward calls apply_qkv / apply_o. gemma.py,@@ -230,9 +231,16 @@ def _plain_model_dtype() -> "torch.dtype":return torch.float16+# has_real_cuda(), not torch.cuda.is_available(): tests/_zoo_aggressive_cuda_spoof.py patches+# the latter True process-wide and never puts it back, and a skipif is evaluated at import, so+# sharing a session with tests/version_compat or tests/vllm_compat would un-skip this on a+# CPU-only box. tests/_shared/real_accelerator.py records the answer before any spoof can run.+# The narrow probe rather than has_real_accelerator() because the body allocates on "cuda"+# by name, and the broad one is also true on an XPU-only or Ascend NPU-only host.+# Both halves are enforced by tests/python/test_accelerator_skip_guards.py.@pytest.mark.gpu@pytest.mark.skipif(- not torch.cuda.is_available(),+ not has_real_cuda(),reason = "loads a real checkpoint through FastLanguageModel; needs an accelerator",)def test_apply_qkv_fallback_end_to_end():diff --git a/tests/test_import_fixes_drift.py b/tests/test_import_fixes_drift.pyindex c175130b402..41cf41a98c8 100644--- a/tests/test_import_fixes_drift.py+++ b/tests/test_import_fixes_drift.py@@ -1444,14 +1444,26 @@ def test_rope_carry_keeps_every_nested_base_on_every_real_config():from transformers.models.auto.configuration_auto import CONFIG_MAPPINGchecked, damaged = [], {}- for name, config_class in sorted(CONFIG_MAPPING.items()):+ # Told apart on purpose from `checked` below. A build with no `rope_parameters` at all is+ # transformers 4.x, where this whole carry does not exist and there is nothing to sweep; a+ # build that HAS the attribute but exposes no nested config is drift worth failing on.+ # Collapsing the two would either red the 4.x job forever or silently stop testing 5.x.+ saw_rope_parameters = False+ # keys(), then resolve inside the try. CONFIG_MAPPING is lazy: .items() imports every+ # config module to hand back the classes, so ONE model whose module needs an optional+ # dependency takes the whole sweep down before the loop body runs. Seen with+ # transformers.models.gemma3n, which imports timm.data.ImageNetInfo and raises ImportError+ # on a timm that does not export it. A config that cannot be built on this machine cannot+ # be the one that regressed, so it is skipped rather than allowed to end the sweep.+ for name in sorted(CONFIG_MAPPING.keys()):try:- config = config_class()+ config = CONFIG_MAPPING[name]()except Exception:continueparameters = getattr(config, "rope_parameters", None)if not isinstance(parameters, dict):continue+ saw_rope_parameters = Truelabels = [k for k, v in parameters.items() if isinstance(v, dict)]if len(labels) < 2:continue@@ -1472,6 +1484,13 @@ def test_rope_carry_keeps_every_nested_base_on_every_real_config():"stray_top_level_rope_theta": "rope_theta" in restored,}+ if not saw_rope_parameters:+ pytest.skip(+ "this transformers has no config.rope_parameters, so there is no per-label rope "+ "dict for a scaling replacement to damage (4.x keeps rope_scaling as a plain "+ "attribute; test_rope_scaling_replacement_keeps_the_base_frequency covers it)"+ )+assert checked, "no config with a nested rope dict was found to check"assert not damaged, (f"a per-label scaling replacement lost bases on {sorted(damaged)} "@@ -1499,7 +1518,10 @@ def test_rope_carry_leaves_the_zoo_gemma_local_base_alone_on_a_real_config():assert (config.rope_theta == 10000.0), f"the carry overwrote the local rotary base with {config.rope_theta!r}"- parameters = config.rope_parameters+ # getattr, not attribute access: the isinstance check below already says this is optional,+ # but transformers 4.x RAISES rather than returning None here, so reading it directly made+ # the tolerance unreachable and failed the test on the 4.x job.+ parameters = getattr(config, "rope_parameters", None)if isinstance(parameters, dict):assert (parameters.get("rope_theta") == 10000.0diff --git a/tests/test_lora_dropout_patch_summary.py b/tests/test_lora_dropout_patch_summary.pyindex 7e8eec738b4..b6943816a41 100644--- a/tests/test_lora_dropout_patch_summary.py+++ b/tests/test_lora_dropout_patch_summary.py@@ -22,9 +22,9 @@ import itertoolsimport textwrapimport pytest-import torchimport unsloth # noqa: F401+from real_accelerator import has_real_acceleratorfrom unsloth.models import llama as llama_modulefrom unsloth.models.llama import _fused_lora_skip_reason@@ -99,9 +99,14 @@ def test_the_summary_call_carries_the_reason():assert "MLP layers.{unfused_reason}" in source+# has_real_accelerator(), not torch.cuda.is_available(): tests/_zoo_aggressive_cuda_spoof.py+# patches the latter True process-wide and never puts it back, and a skipif is evaluated at+# import, so sharing a session with tests/version_compat or tests/vllm_compat would un-skip+# this on a CPU-only box. tests/_shared/real_accelerator.py records the answer before any+# spoof can run. Enforced by tests/python/test_accelerator_skip_guards.py.@pytest.mark.gpu@pytest.mark.skipif(- not torch.cuda.is_available(),+ not has_real_accelerator(),reason = "loads a real checkpoint through FastLanguageModel; needs an accelerator",)def test_summary_reason_is_logged_for_a_real_model():diff --git a/tests/test_st_save_merged_signature.py b/tests/test_st_save_merged_signature.pyindex 258134b0d39..dca389afc0f 100644--- a/tests/test_st_save_merged_signature.py+++ b/tests/test_st_save_merged_signature.py@@ -130,14 +130,68 @@ def _extract_helper(name):_normalize_save_method = _extract_helper("_normalize_save_method")+_PROBE_PACKAGE = "_unsloth_st_source_probe"+++def _probe_package():+ """A package for the exec'd body to resolve its deferred relative imports against.++ #11067 put `from ..save import _is_adapter_save_method` inside `_save_pretrained_merged`,+ deferred on purpose: a module-scope bind out of `unsloth.save` closes an import cycle.+ `exec` with a bare globals dict has no `__name__` and no `__package__`, so a relative+ import there raises `KeyError: "'__name__' not in globals"`, and every test that calls the+ body died on it rather than on anything it was checking.++ Satisfying it by importing unsloth would give up what this file is for: it reads the two+ closures out of the source precisely so the assertions run without an unsloth import. So+ stand up a package that owns the same relative path and put the REAL helper in it, pulled+ from unsloth/save.py by source the way `_normalize_save_method` already is. The import+ statement then executes for real and binds the shipped function, so a change to that+ function's behaviour still reaches these tests.++ Registered under a name of our own rather than "unsloth", so this cannot shadow the real+ package for anything else in the session.+ """+ import sys+ import types++ if _PROBE_PACKAGE in sys.modules:+ return++ root = types.ModuleType(_PROBE_PACKAGE)+ root.__path__ = []+ models = types.ModuleType(f"{_PROBE_PACKAGE}.models")+ models.__path__ = []+ save = types.ModuleType(f"{_PROBE_PACKAGE}.save")+ # By source, not by import, for the same reason as everything else in this file.+ save_src = SAVE_PY.read_text(encoding = "utf-8")+ helper = [+ n+ for n in ast.parse(save_src).body+ if isinstance(n, ast.FunctionDef) and n.name == "_is_adapter_save_method"+ ]+ assert helper, "_is_adapter_save_method is gone from save.py; the deferred import cannot bind"+ exec(ast.get_source_segment(save_src, helper[0]), save.__dict__)++ sys.modules[_PROBE_PACKAGE] = root+ sys.modules[f"{_PROBE_PACKAGE}.models"] = models+ sys.modules[f"{_PROBE_PACKAGE}.save"] = save++def _extract(i):"""Exec one closure body standalone so it can actually be called."""src = ST_PY.read_text(encoding = "utf-8")node = _defs("_save_pretrained_merged", ST_PY)[i]import textwrap+ _probe_package()branding = []ns = {+ # The package coordinates of unsloth/models/sentence_transformer.py, mirrored onto the+ # probe package: `from ..save import ...` in the body resolves one level up from+ # `<probe>.models`, which is where the extracted helper was just installed.+ "__name__": f"{_PROBE_PACKAGE}.models.sentence_transformer",+ "__package__": f"{_PROBE_PACKAGE}.models","os": __import__("os"),"print": lambda *a, **k: None,"_normalize_save_method": _normalize_save_method,@@ -149,6 +203,27 @@ def _extract(i):return ns["_save_pretrained_merged"], branding+def test_the_deferred_import_binds_the_shipped_helper():+ """The harness above must resolve that import for real, not paper over it.++ A stub returning a constant would make the "lora" tests pass while testing nothing, which+ is the failure mode worth guarding: the point of routing through the real+ `_is_adapter_save_method` is that its spelling rules ("LoRA", "lora ") are the ones the+ shipped code applies.+ """+ _probe_package()+ import sys++ helper = sys.modules[f"{_PROBE_PACKAGE}.save"]._is_adapter_save_method+ for accepted in ("lora", "LoRA", "lora ", " LORA"):+ assert helper(accepted), f"the shipped helper no longer accepts {accepted!r}"+ for refused in ("merged_16bit", "lora_adapter", None, 1):+ assert not helper(refused), f"the shipped helper now accepts {refused!r}"+ # And it is the shipped source, not a copy that can drift from it.+ save_src = SAVE_PY.read_text(encoding = "utf-8")+ assert "def _is_adapter_save_method(save_method):" in save_src++class _Tok:def __init__(self):self.saved = []@@ -268,14 +343,57 @@ def test_no_modules_fallback_still_does_a_16bit_merge(tmp_path):assert st.inner.merged-def test_the_forwarding_path_still_accepts_lora(tmp_path):- """With modules.json present the merge understands every method, so the- refusal above must not leak into this branch."""+def test_the_forwarding_path_refuses_lora_for_its_own_reason(tmp_path):+ """Both branches refuse "lora", and the two refusals must stay distinct.++ This test used to assert that the forwarding path ACCEPTED "lora", on the premise that+ with modules.json present the merge understands every method. unsloth#11067 retired that+ premise: `save_pretrained_merged` writes a loadable SentenceTransformer, and an+ adapter-only save has no base weights for one, so it now refuses here too. Before that,+ "lora" matched no branch in merge_and_overwrite_lora and fell through to a 16bit merge,+ which happened to write something loadable for a request that asked for adapters.++ The invariant the old test was really protecting survives the change and is what is+ checked now: the no_modules refusal must not leak into this branch. Both raise, so a+ bare `pytest.raises` would no longer notice if one wrongly borrowed the other's reason,+ which is why the two messages are pinned apart rather than merely asserted non-empty.+ """fn, _ = _extract(1)st = _FakeST(no_modules = False)- fn(st, str(tmp_path), None, "lora")- assert st.inner.forwarded["save_method"] == "lora"- assert not st.inner.merged+ with pytest.raises(NotImplementedError) as raised:+ fn(st, str(tmp_path), None, "lora")++ message = str(raised.value)+ # Its own reason: no base weights for a loadable SentenceTransformer, plus the two ways+ # out. Not the no_modules reason, which is about falling back to merge_and_unload.+ assert "adapter" in message+ assert "merged_16bit" in message+ assert "no modules.json was found" not in message, (+ "the no_modules refusal leaked into the branch that HAS modules.json; the two "+ "conditions are different and a user told the wrong one looks for the wrong file"+ )+ # Refused before anything is touched, exactly as the no_modules branch is.+ assert not st.inner.merged, "must refuse BEFORE merging the adapters away"+ assert st.saved == [], "and before writing a half-finished directory"+ assert st.inner.forwarded is None, "and without forwarding the unsupported method on"+++def test_the_two_lora_refusals_do_not_share_a_message(tmp_path):+ """Written because the check above can only see one of the pair at a time.++ If both branches were ever collapsed onto one message, each test would still pass on its+ own substring while the distinction that makes the advice actionable was gone.+ """+ fn, _ = _extract(1)+ messages = []+ for no_modules in (True, False):+ with pytest.raises(NotImplementedError) as raised:+ fn(_FakeST(no_modules = no_modules), str(tmp_path), None, "lora")+ messages.append(str(raised.value))+ assert messages[0] != messages[1], (+ "both 'lora' refusals now say the same thing, so the message no longer tells the "+ "user whether modules.json was the problem"+ )# ---- spellings mean the same thing as in unsloth_save_model ----------------