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
Run the repo CPU test suite on all four runner cores (#9019)
Daniel Han6c124b6dd830
diff --git a/.github/workflows/studio-backend-ci.yml b/.github/workflows/studio-backend-ci.ymlindex 24a842e8544..d638b944af8 100644--- a/.github/workflows/studio-backend-ci.yml+++ b/.github/workflows/studio-backend-ci.yml@@ -57,11 +57,20 @@ jobs:pytest:name: (Python ${{ matrix.python }})runs-on: ubuntu-latest- # 30, not 15: the suite now runs 14.1 to 15.0 minutes on every interpreter in the matrix, so a- # 15 minute budget cancels whichever jobs happen to land on the slow side of the median and the- # result is a coin flip rather than a verdict. This guards against a hang, which 30 still does;- # it was never meant to be a performance budget. The suite's own runtime is the real problem.- timeout-minutes: 30+ # 45 guards against a hang; it is not a performance budget. The comment this replaces+ # claimed 14.1 to 15.0 minutes against a limit of 30, but this step now measures 22.5 to+ # 29.2 minutes across the matrix, and it has been cancelling at the limit: across the six+ # open PRs on this branch's stack, five had one leg cancelled at 30m9s while its siblings+ # passed at 25 to 29 minutes. Which leg loses is luck, so every PR carries a red check+ # that says nothing about the PR.+ # Running it on all four cores would fix the duration properly and is worth ~79+ # runner-minutes a push, but this suite is not order-independent enough yet. Measured+ # under `-n 4` on a 4-vCPU runner it fails tests serial does not, in more than one way and+ # not the same way twice. The repo job below IS order-independent and does run parallel;+ # this one waits until those dependencies are found and fixed individually. Raising the+ # limit costs nothing until a job actually needs it, and a cancelled leg costs the whole+ # 30 minutes anyway.+ timeout-minutes: 45strategy:fail-fast: falsematrix:@@ -168,7 +177,7 @@ jobs:pip install \python-multipart aiofiles sqlalchemy cryptography psutil \pyyaml jinja2 mammoth unpdf requests typer \- 'numpy<3' pytest pytest-asyncio httpx+ 'numpy<3' pytest pytest-asyncio pytest-xdist httpx# torchvision: unsloth_zoo.vision_utils imports it at module scope.pip install --index-url https://download.pytorch.org/whl/cpu --extra-index-url https://pypi.org/simple \'torch>=2.4,<2.11' 'torchvision<0.26'@@ -206,7 +215,9 @@ jobs:# in version-compat-ci.yml that installs the heavier dep set# (torchcodec, full transformers/peft/bnb pins) those tests need.# State-sensitive hardware-spoofing files run in isolation in the- # next step because they mutate hardware.py module globals.+ # next step because they mutate hardware.py module globals, and+ # tests/studio/load_freeze in the step after that because its+ # assertions are wall-clock latency bounds.# -m: honour markers from tests/python/conftest.py (`server` =# needs studio venv, `e2e` = needs network).# --deselect:@@ -217,12 +228,19 @@ jobs:# and the latest tokenizers (0.23.1) is incompatible with the# transformers it resolves to. Tracked separately; this is a# real bug in the no-torch install path, not a CI issue.+ #+ # -n 4: 806.1s -> 219.7s locally on the same 4-worker shape as the runner, with an+ # identical 2-failed / 8066-passed / 178-skipped / 40-subtest result. The three pytest+ # steps below stay serial deliberately: the hardware-spoof step exists precisely+ # because those files mutate hardware.py module globals, and all three already measure+ # under 0.1 minutes on the runner, so there is nothing to win and isolation to lose.run: |- python -m pytest tests/ -q --tb=short \+ python -m pytest tests/ -q --tb=short -n 4 \--ignore=tests/qlora \--ignore=tests/saving \--ignore=tests/utils \--ignore=tests/sh \+ --ignore=tests/studio/load_freeze \--ignore=tests/studio/test_hardware_dispatch_matrix.py \--ignore=tests/studio/test_is_mlx_dispatch_gate.py \--ignore=tests/studio/test_xpu_spoof_pipeline.py \@@ -248,6 +266,22 @@ jobs:tests/studio/test_is_mlx_dispatch_gate.py \tests/studio/test_xpu_spoof_pipeline.py+ - name: Event-loop latency tests (wall clock, run without CPU contention)+ env:+ PYTHONPATH: ${{ github.workspace }}/studio+ UNSLOTH_COMPILE_DISABLE: '1'+ # These drive a live uvicorn server and assert upper bounds on real+ # elapsed time: a /health burst must stay under 250 ms while a 600 ms+ # blocking probe runs, and a 100-request burst under 350 ms. That is the+ # actual contract (the route hands the blocking call to a thread), so the+ # bounds cannot be relaxed without the test ceasing to test anything.+ # A descheduled worker inflates them, so they run alone. Measured under+ # 3x CPU oversubscription the margin is wide (8 ms against 250, 38 ms+ # against 350), but a runner core is several times slower than the box+ # that measured it, which puts the 350 ms one within reach.+ # 20s serially, against the ~10 minutes -n 4 saves on this job.+ run: python -m pytest tests/studio/load_freeze -q --tb=short+- name: CLI tests (unsloth_cli)# unsloth_cli/tests had no CI at all: `unsloth_cli/**` was only a paths# trigger and a ruff target, so 673 tests covering the studio launcher,diff --git a/tests/python/test_no_torch_filtering.py b/tests/python/test_no_torch_filtering.pyindex fa977c67e5d..e645eb2956b 100644--- a/tests/python/test_no_torch_filtering.py+++ b/tests/python/test_no_torch_filtering.py@@ -224,10 +224,20 @@ class TestRealRequirementsFiltering:pytest.skip("extras.txt not found in repo")if not EXTRAS_NO_DEPS_TXT.is_file():pytest.skip("extras-no-deps.txt not found in repo")- existing_filtered = set(REQ_ROOT.glob(".*-filtered-*.txt"))+ self._created = []yield- for path in set(REQ_ROOT.glob(".*-filtered-*.txt")) - existing_filtered:- path.unlink(missing_ok = True)+ # Only what this test made. These land in the REAL requirements directory, and+ # the previous version deleted everything that appeared since its own snapshot,+ # so under pytest-xdist one test's teardown removed a file another worker was+ # still reading and that test failed with FileNotFoundError.+ for path in self._created:+ Path(path).unlink(missing_ok = True)++ def _filter(self, source, packages):+ """ips._filter_requirements, remembering the file so teardown can remove it."""+ result = ips._filter_requirements(source, packages)+ self._created.append(result)+ return resultdef _non_blank_non_comment(self, path: Path) -> list[str]:"""Return non-blank, non-comment lines from a requirements file."""@@ -236,7 +246,7 @@ class TestRealRequirementsFiltering:def test_extras_txt_torch_packages_removed(self):"""extras.txt: all NO_TORCH_SKIP_PACKAGES must be removed, everything else preserved."""- result = ips._filter_requirements(EXTRAS_TXT, ips.NO_TORCH_SKIP_PACKAGES)+ result = self._filter(EXTRAS_TXT, ips.NO_TORCH_SKIP_PACKAGES)filtered = self._non_blank_non_comment(Path(result))original = self._non_blank_non_comment(EXTRAS_TXT)@@ -260,7 +270,7 @@ class TestRealRequirementsFiltering:def test_extras_no_deps_txt_torchcodec_and_dlpack_removed(self):"""extras-no-deps.txt: torchcodec and torch-c-dlpack-ext must be removed."""- result = ips._filter_requirements(EXTRAS_NO_DEPS_TXT, ips.NO_TORCH_SKIP_PACKAGES)+ result = self._filter(EXTRAS_NO_DEPS_TXT, ips.NO_TORCH_SKIP_PACKAGES)filtered = self._non_blank_non_comment(Path(result))original = self._non_blank_non_comment(EXTRAS_NO_DEPS_TXT)@@ -278,7 +288,7 @@ class TestRealRequirementsFiltering:def test_extras_txt_most_packages_preserved(self):"""Ensure a representative set of non-torch packages survive filtering."""- result = ips._filter_requirements(EXTRAS_TXT, ips.NO_TORCH_SKIP_PACKAGES)+ result = self._filter(EXTRAS_TXT, ips.NO_TORCH_SKIP_PACKAGES)filtered_text = Path(result).read_text(encoding = "utf-8").lower()must_survive = ["scikit-learn", "loguru", "tiktoken", "einops", "tabulate"]@@ -288,7 +298,7 @@ class TestRealRequirementsFiltering:def test_extras_no_deps_txt_trl_preserved(self):"""trl should survive NO_TORCH filtering in extras-no-deps.txt."""- result = ips._filter_requirements(EXTRAS_NO_DEPS_TXT, ips.NO_TORCH_SKIP_PACKAGES)+ result = self._filter(EXTRAS_NO_DEPS_TXT, ips.NO_TORCH_SKIP_PACKAGES)filtered_text = Path(result).read_text(encoding = "utf-8").lower()assert "trl" in filtered_text, "trl should survive NO_TORCH filtering"diff --git a/tests/python/test_windows_setup_output_encoding.py b/tests/python/test_windows_setup_output_encoding.pyindex a96aeea4c08..4d8a91b681f 100644--- a/tests/python/test_windows_setup_output_encoding.py+++ b/tests/python/test_windows_setup_output_encoding.py@@ -50,6 +50,7 @@ import shutilimport subprocessimport sysimport tempfile+import uuidfrom functools import lru_cachefrom pathlib import Path@@ -161,7 +162,16 @@ def _run_capturing_bytes(is how the CLI spawns setup for ``unsloth studio update``. Piped stdout isrequired to reproduce, and is captured as bytes, never decoded here."""- tmp = REPO_ROOT / "tests" / "python" / f"_{stem}_probe_{int(use_command_shape)}.ps1"+ # Unique per call. The name used to be (stem, shape), which several tests+ # share, so under pytest-xdist one case could unlink the script after another+ # had written it and before its pwsh child opened it. pwsh is installed on+ # ubuntu-latest, so these do not skip there and would race for real.+ tmp = (+ REPO_ROOT+ / "tests"+ / "python"+ / f"_{stem}_probe_{int(use_command_shape)}_{uuid.uuid4().hex}.ps1"+ )tmp.write_text(script, encoding = "utf-8")try:base = [_PWSH, "-NoLogo", "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass"]diff --git a/tests/studio/install/test_diffusers_pin.py b/tests/studio/install/test_diffusers_pin.pyindex ed54bfce209..2fecfdf98b3 100644--- a/tests/studio/install/test_diffusers_pin.py+++ b/tests/studio/install/test_diffusers_pin.py@@ -22,6 +22,11 @@ import reREPO_ROOT = pathlib.Path(__file__).resolve().parents[3]REQ_ROOT = REPO_ROOT / "studio" / "backend" / "requirements"PIN_FILE = REQ_ROOT / "diffusers-pin.txt"++# The shape install_python_stack._filter_requirements writes: a dot, the source stem,+# "-filtered-", then tempfile's random suffix. NamedTemporaryFile's suffixes are+# [A-Za-z0-9_]{8}, so this cannot swallow a checked-in file that merely starts with a dot.+_GENERATED_FILTER = re.compile(r"\.[\w.-]+-filtered-\w{8}\.txt")STACK = REPO_ROOT / "studio" / "install_python_stack.py"INSTALL_SH = REPO_ROOT / "install.sh"@@ -58,6 +63,17 @@ def test_only_the_pin_file_names_diffusers():for path in sorted(REQ_ROOT.rglob("*.txt")):if path == PIN_FILE:continue+ # install_python_stack._filter_requirements writes `.{stem}-filtered-XXXX.txt`+ # BESIDE the source on purpose, so relative -r/-c includes still resolve, and it+ # does not delete it. So a copy of the pin file can be sitting here while this+ # runs -- transiently under pytest-xdist, where another worker is exercising that+ # function, and durably on any machine that has run a real install. It is a+ # generated temp, not a second source of the pin.+ # Matched by that exact shape rather than by "starts with a dot": a checked-in+ # hidden file such as .constraints.txt is a real requirements file and a real+ # place the pin could be overridden from, so it stays in the scan.+ if _GENERATED_FILTER.fullmatch(path.name):+ continuenamed = [line for line in _requirements(path) if line.lower().startswith("diffusers")]if named:offenders[str(path.relative_to(REPO_ROOT))] = nameddiff --git a/tests/studio/test_backend_ci_parallel_isolation.py b/tests/studio/test_backend_ci_parallel_isolation.pynew file mode 100644index 00000000000..c4b7fd3733c--- /dev/null+++ b/tests/studio/test_backend_ci_parallel_isolation.py@@ -0,0 +1,87 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Guards the files Backend CI deliberately keeps out of the parallel pytest run.++The repo-cpu-tests job runs tests/ under `-n 4`. Two groups cannot go through it:++- tests/studio/load_freeze asserts UPPER bounds on real elapsed time (a /health+ burst under 250 ms while a 600 ms blocking probe runs, a 100-request burst+ under 350 ms). Those bounds are the contract, so they cannot be loosened, and a+ pytest worker descheduled by the other three inflates them.+- the hardware-spoof files mutate hardware.py module globals, so they leak into+ whatever shares their worker.++Both are ignored from the parallel invocation and run again in their own serial+step. That is two edits held together by nothing, and dropping the second one is+silent: the job stays green while the tests stop running. These tests fail if the+ignore appears without a step that runs the same path, or the other way round.+"""++import re+from pathlib import Path++import pytest++WORKFLOW = Path(__file__).resolve().parents[2] / ".github" / "workflows" / "studio-backend-ci.yml"++# (ignored path, why it cannot share a worker)+ISOLATED = [+ ("tests/studio/load_freeze", "wall-clock latency bounds"),+ ("tests/studio/test_hardware_dispatch_matrix.py", "mutates hardware.py globals"),+ ("tests/studio/test_is_mlx_dispatch_gate.py", "mutates hardware.py globals"),+ ("tests/studio/test_xpu_spoof_pipeline.py", "mutates hardware.py globals"),+]+++def _pytest_commands(text: str) -> list[str]:+ """Every `python -m pytest ...` invocation in the workflow, line joins resolved.++ Read off the raw text rather than the parsed YAML: a `run:` block is one+ scalar and the interesting structure is inside it, so parsing buys nothing and+ would make this depend on the job/step layout instead of the commands.+ """+ joined = re.sub(r"\\\s*\n\s*", " ", text)+ return [+ line.strip()+ for line in joined.splitlines()+ if "python -m pytest" in line and not line.lstrip().startswith("#")+ ]++[email protected]("path, reason", ISOLATED, ids = [p for p, _ in ISOLATED])+def test_an_isolated_path_is_ignored_by_every_parallel_pytest_run(path, reason):+ for command in _pytest_commands(WORKFLOW.read_text(encoding = "utf-8")):+ if " -n " not in f" {command} ":+ continue+ assert f"--ignore={path}" in command, (+ f"{path} ({reason}) is not ignored by a parallel pytest run in "+ f"{WORKFLOW.name}, so it shares four workers on the runner's four vCPUs: {command}"+ )++[email protected]("path, reason", ISOLATED, ids = [p for p, _ in ISOLATED])+def test_an_isolated_path_still_runs_in_a_serial_step(path, reason):+ """Ignoring it is half the change. Without this, the tests silently stop running."""+ serial = [+ command+ for command in _pytest_commands(WORKFLOW.read_text(encoding = "utf-8"))+ if " -n " not in f" {command} "+ and re.search(rf"(?<![\w/]){re.escape(path)}(?![\w/])", command)+ ]+ assert serial, (+ f"{path} is ignored from the parallel run ({reason}) and no serial pytest step runs "+ f"it, so it runs nowhere in {WORKFLOW.name} while the job stays green."+ )+++def test_the_command_scan_sees_the_parallel_run_and_the_serial_steps():+ """Pin the parser: a scan that matched nothing would pass both tests above."""+ commands = _pytest_commands(WORKFLOW.read_text(encoding = "utf-8"))+ parallel = [command for command in commands if " -n " in f" {command} "]+ assert len(parallel) == 1, f"expected exactly one parallel pytest run, got {parallel}"+ assert "tests/" in parallel[0]+ # The line joins have to be resolved, or the parallel command reads as `pytest tests/ -q`+ # with none of its --ignore flags and the first test above passes on nothing.+ assert "--ignore=" in parallel[0]+ assert len(commands) > 1, "no serial pytest steps found; the ignore checks cannot fail"diff --git a/tests/studio/test_chat_preset_builtin_invariants.py b/tests/studio/test_chat_preset_builtin_invariants.pyindex 31b2a2b733f..b02a5ee9eb9 100644--- a/tests/studio/test_chat_preset_builtin_invariants.py+++ b/tests/studio/test_chat_preset_builtin_invariants.py@@ -2,6 +2,8 @@ import jsonimport osimport shutilimport subprocess+import tempfile+import uuidimport textwrapfrom pathlib import Path@@ -37,25 +39,43 @@ def _require_node():pytest.skip("node --experimental-strip-types not available")+def _write_atomic(path: Path, text: str):+ """Write through a unique temp file and os.replace.++ register.mjs and loader.mjs are shared by every _run, and write_text truncates+ before it writes, so rewriting one while another worker's node process is+ importing it can hand that process an empty or partial module. Contents are+ constant, so the rename leaves every reader a whole file.+ """+ fd, tmp = tempfile.mkstemp(dir = str(path.parent), prefix = path.name, suffix = ".tmp")+ with os.fdopen(fd, "w", encoding = "utf-8") as handle:+ handle.write(text)+ os.replace(tmp, path)++def _ensure_harness():TEMP.mkdir(parents = True, exist_ok = True)- (TEMP / "register.mjs").write_text(+ _write_atomic(+ TEMP / "register.mjs","import { register } from 'node:module';\nregister('./loader.mjs', import.meta.url);\n",- encoding = "utf-8",)- (TEMP / "loader.mjs").write_text(+ _write_atomic(+ TEMP / "loader.mjs","export function resolve(specifier, context, next) {\n"" if (specifier.endsWith('/types/runtime')) return next(specifier + '.ts', context);\n"" return next(specifier, context);\n""}\n",- encoding = "utf-8",)def _run(script: str):_require_node()_ensure_harness()- script_path = TEMP / "run.mts"+ # Unique per call: a shared run.mts let two xdist workers interleave write and exec,+ # so one ran the other's script (5-6 of these 9 failed on every -n 4 run).+ # A unique name, not a per-call dir like _node_harness.py uses: these scripts reach+ # the sources by a path relative to TEMP, so an extra level breaks every import.+ script_path = TEMP / f"run_{uuid.uuid4().hex}.mts"script_path.write_text(script, encoding = "utf-8")env = dict(os.environ, NODE_NO_WARNINGS = "1")result = subprocess.run(@@ -64,7 +84,7 @@ def _run(script: str):"--experimental-strip-types","--import=./register.mjs","--no-warnings",- "run.mts",+ script_path.name,],cwd = str(TEMP),capture_output = True,@@ -72,6 +92,7 @@ def _run(script: str):timeout = 30,env = env,)+ script_path.unlink(missing_ok = True)assert result.returncode == 0, f"stderr: {result.stderr}\nstdout: {result.stdout}"last = [line for line in result.stdout.strip().splitlines() if line.strip()][-1]return json.loads(last)