Repository navigation
Docker Studio: stop disabling Unsloth's TRL patches on GPU hosts - #10825
Conversation
|
Confirmed this hits docker/Dockerfile.studio, where the image-level UNSLOTH_ALLOW_CPU=1 reaches every process and makes unsloth/models/rl.py skip the TRL trainer patches even on a GPU host. Will get this reviewed. |
…a GPU
Four things the per-container rule missed, each reproduced against the published
image on an NVIDIA host before and after.
Dockerfile.studio bakes UNSLOTH_IMAGE_ALLOW_CPU=1 but BASE_IMAGE defaults to the
PUBLISHED unsloth/unsloth:core, whose entrypoint predates the name. A standalone
`docker build -f docker/Dockerfile.studio` therefore opted in and still exited 1 on
a CPU-only host. Confirmed by running :core with the new variable: exit 1, where
UNSLOTH_ALLOW_CPU=1 starts. The publish workflow pins the core digest from the same
run, so CI could not see it. Studio now copies the entrypoint it needs.
gpu_visible() shells out to nvidia-smi -L, which lists the hardware and ignores
CUDA_VISIBLE_DEVICES; torch honours it, so an empty value or -1 leaves
device_count() == 0. The GPU path was therefore taken for processes with no GPU:
with --gpus and -e CUDA_VISIBLE_DEVICES= the opt-in was stripped and `import
unsloth` raised NotImplementedError, where main imported fine. Both masks now count
as no GPU, which also replaces a misleading driver-too-old exit with the CPU
fallback the user asked for.
allow_cpu used ${VAR:-...}, so `-e UNSLOTH_ALLOW_CPU=` fell through to the image
opt-in and started a GPU-less container that main refused. `-` keeps an explicit
empty value meaning off, as the comment beside it already claimed.
host_has_nvidia() in run.sh still piped nvidia-smi into grep -q under pipefail, the
exact shape fixed in entrypoint.sh; there a SIGPIPE reads as no GPU and silently
drops --gpus.
Tests: the GPU-host case now builds its environment from the Dockerfile ENV instead
of spelling the new name, so it fails on main rather than passing vacuously against
the ENV that caused the bug; plus the two masks, the empty value, the bundled
entrypoint, and the one CPU path that reaches exec with no opt-in, where an
unconditional export would have hidden.
|
@codex security review |
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
I pushed cac276c to this branch with four fixes, each reproduced against the published image on an NVIDIA host before and after. The change this PR makes is right, and I confirmed the bug it fixes is real: What the per-container rule missed:
Verification, on top of the suites already listed: 1664 simulated startup cells covering Linux/WSL2/Docker Desktop on macOS and Windows, NVIDIA and AMD and CPU-only, multi-GPU, MIG, arm64, a broken NVML, an empty The GPU-host test now builds its environment from the Dockerfile ENV rather than spelling the new variable, because as written it also passed on main, against the very ENV that caused the bug. Nine of the file's tests now fail on main, up from five. One behaviour worth stating plainly in the description rather than leaving to the entrypoint comment: on a host with no GPU, a non-login Also worth a separate look: the |
|
Codex Review: Didn't find any major issues. Breezy! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
🛡️ Codex Security ReviewSecurity review completed. No security issues were found in this pull request. Reviewed commit: Only the user who started this review can view the report in Codex. ℹ️ About Codex security reviews in GitHubThis is an experimental Codex feature. Security reviews are triggered when:
Once complete, Codex will leave suggestions, or a comment if no findings are found. |
Both classes stub /usr/bin-style tools, stage a /dev tree and read the environment a POSIX exec hands on. The guard only asked for bash on PATH, and Git Bash satisfies that on a Windows runner, so the whole file ran there and 10 of 23 failed on path translation and the exec bit: five FileNotFoundError on the recorded argv and five on the exec'd child's environment. Four of those predate the entrypoint cases added here, in TestRunShDegradesWithoutNvidia, which this branch does not touch, so the gap is not new. No workflow ran into it because the Windows matrix in cross-platform-parity-ci.yml names five files and this is not one of them; it runs on ubuntu in Repo tests (CPU). Verified on a staging run of this branch: ubuntu and macos-14 both 23 passed, windows-latest 10 failed. Nothing upstream CI exercises is lost, and a developer running the suite on Windows stops seeing ten failures for a file that cannot apply there.
|
Codex Review: Didn't find any major issues. Swish! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
* Unbreak main: read the sidebar hold-out contract as a condition, not as source text #10706 hoisted `hasPinMode && !pinned && collapseToZero` into a named const and gave it a peek exception. That changed nothing the contract protects, but the test pinned the inlined spelling, so Backend CI has failed on every main commit since 22bbff6 and on roughly 25 open PRs that touch none of this. Read the condition instead, with the helpers that already exist for exactly this in tests/studio/_js_source.py, and assert the thing the literal form never did: that aria-hidden and inert stay the same expression, since hidden-but-focusable is the bug. _js_source gains two pieces: - attribute_expressions(), to read what a JSX attribute is wired to. - an ASI-aware declaration scan. binding_joining() only looked for `const NAME = ...;` and sidebar.tsx has one semicolon in 500 lines, so it found no declarations there at all and answered None for a binding plainly present. * Restore linear DeepSeek R1 tool-call parsing, and measure linearity rather than speed #10507 added a wrapper sweep that seeks the next `{` once per opener. A DeepSeek R1 body is repeated `<|tool_sep|>` markers, so that is once per marker, each scanning the rest of the buffer: quadratic. Measured over doubling input, the R1 path went 2.00x per doubling before #10507 and 2.21x, 2.40x, 2.66x, 4.82x after, reaching 2.9s on 80k markers. The sweep now carries the next `{` forward instead of re-seeking it, since both indices only move forward, and stops when there is none left. It also no longer copies the gap between a marker and a far-away object: a fence or blank space is short, so a long gap is not a body. Rejecting it is the conservative direction, because an untrusted span is masked rather than exempted. All five adversarial shapes are back to 2.00x per doubling. test_pr5624_regressions caught this and was reported as a flake, because an absolute `elapsed < 1.0` at one size cannot tell a slow runner from a slow parser: it read 0.20s on a quiet runner and 1.41s on a busy one, and the real regression only tipped it over sometimes. The three tests now compare the cost of 4x the input against the cost of 1x. Linear is ~4x, quadratic is ~16x. Healthy measures 3.94-4.09 across all four shapes; with #10507's sweep restored it measures 6.7x and 12.2x, so the bar at 6.0 has margin on both sides. Adds the distant-object shape as a fourth case. It is the one that stayed quadratic after the obvious fix, because a `{` anywhere in the buffer means the per-marker seek always finds one. * Do not score a PowerShell host crash as an installer-watcher failure #10825 went red on test_the_watcher_scores_the_image_that_ran_not_the_words_in_the_message with pwsh aborting on SIGABRT out of AssemblyName.ParseAsAssemblySpec: the .NET host tearing itself down, on a probe that loads no assembly of its own and passes everywhere else. Both pwsh probes now go through one runner that retries once and then skips, and only for an abnormal termination carrying a host fault banner. A clean non-zero exit, or the wrong HITS count, is the watcher being wrong and still fails: verified by breaking Watch-ForCompiler.ps1 and confirming the test goes red, and by driving all four shapes (crash-then-ok, crash-twice, clean non-zero, abnormal without a banner) through the runner directly. * Re-triage the 7 dependency-scan findings an upstream release reopened pip scan-packages fails on every PR that touches deps (#10819 is the current one) with 5 CRITICAL and 2 HIGH that no PR introduced. The baseline binds each entry to a hash of the flagged code, so an upstream release that edits those lines reopens the entry by design. scikit-learn 1.9.1 did exactly that; unsloth-zoo reopens on its own PyPI releases. Reviewed all 7 against the source, not the check name: - sklearn/datasets/_openml.py, 'C2 polling/beaconing loop': the `while True` inside _retry_on_network_error. It decrements retry_counter, re-raises at zero and re-raises 412 immediately. A bounded retry, not a beacon. - sklearn/externals/array_api_compat/{cupy,dask,numpy,torch}/__init__.py, 'Downloads and executes remote code': `__import__(__spec__.parent + '.linalg')`, four copies of a vendored shim importing its OWN submodule, with the upstream comment explaining that the name is built dynamically so the library can be vendored. No network, no remote code. - unsloth_zoo/compiler.py, 'obfuscation + exec/eval': our own compiler exec'ing the patched forward methods it generates. That is the module's entire purpose. - unsloth_zoo/mlx/loader.py, same check: the Exec evidence is almost all `mx.eval(...)`, MLX's lazy-array evaluation, which is not Python eval at all. Entries are appended, not regenerated, so the other 228 keep their existing review. Known follow-up: unsloth-zoo is first-party and releases often, so these two entries will reopen again. Worth deciding separately whether a package we publish belongs in a third-party supply-chain scan at all; not changing the gate's design here. * Read the media status guard as a guard, not as one exact line #10788 rewrote setStatusIfNewest's ticket check from if (ticket === statusTicket.current) setStatus(next); to if (ticket !== statusTicket.current) return; setStatus(next); which admits exactly the same reads, and Frontend build + bundle sanity went red on the substring. Same failure class as the sidebar contract in the previous commit. Both spellings now count, checked against setStatusIfNewest's own callback body so a guard elsewhere in the file cannot stand in for it. Verified against #10788's source (passes) and against three mutations (guard deleted, guard inverted, guard moved out of the callback), each of which fails. * Bound the fence, not the gap, when trusting a wrapper body The previous commit refused any gap over 4096 chars between a wrapper marker and its object, to avoid copying it once per marker. Differential testing against the old sweep over long gaps showed that is too blunt in the one direction that matters: _only_a_code_fence strips before it matches, so a genuine fence trailed by blank space, or an object preceded by a long blank run, was accepted before and refused after. Refusing wrongly is not free. An untrusted wrapper body gets masked, and end to end that turns a tool argument of {"q": "<think>rehearsed</think>"} into a run of U+E000, which is the defect #10507 added _inference_wrapper_spans to avoid. The gap's blank ends are now found as indices and never copied, and the cap applies to what is left, which is the only part the fence test decides on. Blank is unbounded again, as it is in real output. Differential against main's sweep: 60000 random short inputs, 0 mismatches. 2520 long-gap inputs across blank, fence, text and brace fillers at 1 to 20000 chars: the only remaining divergence is a fence whose stripped form exceeds 4096 characters, that is a 4000-plus backtick run or language tag, which is what the cap is for and is documented as such. Still 2.00x per doubling on all six adversarial shapes, including the two the cap exists for (one distant object, and a long blank run before it). * Record the new tool_call_parser constant in the refactor guard inventories The guard pins the parsing stack's module surface, so the added _MAX_FENCE_CHARS reads as an unrecorded top-level name and fails test_ast_inventory_matches_the_baseline and test_runtime_surface_matches_the_baseline. Added by hand rather than with 'refactor_guard.py snapshot'. A full snapshot on this tree also rewrites 111 unrelated ast entries, 63 patch targets and two idempotence inputs, none of which this branch touches, and folding someone else's unrecorded drift into a CI fix would hide it. test_guarded_functions_produce_the_same_bytes, the digest over the 1833-input corpus, passes unchanged, which is the check that would have caught a behaviour change in the sweep. * Attribute a temporary DLL to a compiler, so Windows No Compiler CI can pass This job has never once been green: 0 successes against 70 failures and 28 cancelled runs in its last 100, red on main continuously. It fails on its own artefact detector, which scored every *.dll created anywhere under TEMP while the installer ran. The installer unpacks llama.cpp's checksum-verified prebuilt release into a staging directory there, so ~25 DLLs land under TEMP with no compiler within reach, and the job reported them as 'the artefact half of the same shape'. They are not that shape. What was blocked in the field, and what this job's own prose says it measures, is powershell.exe -> csc.exe -> %TEMP%\<random>.dll An extracted archive is a different thing, so the gate was wrong and the installer was right. A DLL now counts only when a compile is evidenced in ITS OWN directory. CodeDom, which is what Add-Type uses and what was flagged, writes the response file, the generated source and the captured streams into the per-invocation directory it puts the assembly in, so the pairing holds for the shape this exists to catch. A .cmdline or .rsp still counts on its own, wherever it lands. The narrowing is self-checking: the positive control compiles a real type with Add-Type and REQUIRES both detectors to fire before any measurement is believed, so cutting too far fails there rather than passing quietly. Also fixes the message that reported this. Both throws read '{0}' literally on every firing, because -f binds tighter than the string concatenation it was applied to and formatted only the last fragment. Tests: test_the_watcher_still_reports_intermediates_that_were_left_behind asserted a bare leftover.dll, which is the over-broad rule itself; it now leaves a response file beside the assembly, which is what a compile that was not cleaned up looks like. Two new cases pin the change: an unpacked release archive is not a compile, and a real compile in a sibling directory is still caught while the archive beside it is not. 49 passed. * Require the media status guard to precede the write, not merely exist The early-return spelling this test started accepting is only equivalent when the guard runs FIRST. Checking presence alone let setStatus(next); if (ticket !== statusTicket.current) return; pass, which publishes the superseded status before returning and is the exact bug the test exists to catch. Confirmed by building that page and watching all four tests pass. The guard's match index must now come before the first setStatus(. The inline 'if (a === b) setStatus(next);' form satisfies it by construction. Verified against main, against #10788's early-return form, and against both regressions (write-then-guard, and the guard deleted outright), which now fail. * Unblock the desktop leg, require a bare stale return, pin the MLX loader entry Windows No Compiler CI: with the artefact detector fixed, the positive control and the shell leg both pass for the first time, and the desktop leg then failed on something that had been hidden behind them. Under $ErrorActionPreference = 'Stop', a native command writing ANY line to stderr raises NativeCommandError, and install.ps1 --tauri reported [TAURI:ERROR_CLEAR] create virtual environment recovered which is the installer saying it recovered. That killed the step before either detector was read. Both legs now drop to 'Continue' around the child only; the exit code stays the gate, which for the desktop leg is deliberately not checked at all, so a stderr line failing it was never the intent. media-status-sequencing: requiring the guard to precede the write still accepted 'if (ticket !== statusTicket.current) return setStatus(next);' ahead of the normal write, which publishes the superseded status out of the return expression. Confirmed by building that page and watching all four tests pass. The stale branch's return must now be bare. Verified against main, against #10788's form, against a braced early return, and against three regressions (return-with-write, write-then-guard, guard deleted), which all fail. scan_packages baseline: the appended unsloth_zoo/mlx/loader.py entry is pinned to its reviewed file, matching the compiler.py entry beside it. The obfuscation check's evidence is the __import__/eval lines and the import TARGET is a variable, so it sits outside the evidence: a changed target would leave evidence_hash intact and keep the finding suppressed. Scan still exits 0 with 17 suppressed and no active CRITICAL or HIGH. * Do not score the positive control's own compile against the installer With the desktop leg unblocked, the shell leg failed reporting the installer spawned 1 compiler process(es) on a cvtres.exe created by csc.exe at 12:49:23, about a second before the step began. That is the positive control from the step above: it compiles a type on purpose, and the 4688 window starts a second early, so its compile fell inside the installer's lookback. The hits already present when the action has not yet started are recorded and subtracted by identity. Moving the floor to 'now' instead would have given up what that second is for, which is keeping a process created in the same tick as the floor from being dropped. Also closes the last hole in the media sequencing guard: guarding the first setStatus while a second sits unguarded after it leaves every stale response overwriting the status. The callback must now write exactly once. All three pages have exactly one write today, #10788 included, and an added second one fails. * State WHEN the collapsed sidebar leaves the accessibility tree, not that it does Asking only that the held-out condition still appears in the expression accepts dropping the peek exception along with it, and a peeked sidebar is on screen: aria-hidden and inert on a visible, focusable panel is the same defect the assertion guards, pointing the other way. So expand the attribute expression down to its four inputs and compare the whole truth table against the one this contract wants: removed exactly when pin mode is on, the sidebar is unpinned, it collapses to zero, and it is not being peeked at. Any spelling admitting exactly those states passes, so the rename, the rewrap and the hoisted const that broke the old exact-string form are all invisible; dropping the peek exception, dropping inert, dropping collapseToZero and inverting the exception all fail. expand_bindings stops at the four inputs rather than walking to the bottom. hasPinMode is itself a const further up, and expanding it too drags in the prop plumbing that decides whether pin mode exists at all, which belongs to a different component. boolean_table refuses anything that is not names, && || ! and parentheses, so a comparison cannot be quietly mistranslated on the way to Python. Also pins the OpenML suppression to the file it was reviewed against. The hashed evidence is the bare 'while True:'; what makes the loop benign is the retry counter, the decrement and the two re-raises around it, all outside that line. Removing the bound would have left the entry suppressing. Verified against scikit-learn 1.9.1: it still suppresses, and one flipped digit reopens the CRITICAL. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Wait for the find bar to settle instead of sleeping 200ms at it Frontend build + bundle sanity went red on a commit that touched a PowerShell script and a node test, on 'chromium/Linux: the chord re-focuses the field instead of closing', 177/178. The check presses the chord, sleeps a flat 200ms and reads the state; open_bar right above it already waits on a condition, with a comment about the first open crossing a lazy boundary. The same boundary is in front of this press, so on a loaded runner the sleep expires first and the check reports a defect that is not there. It now waits for open && focused, and Escape waits for the bar to be gone rather than sleeping 250ms. Neither wait asserts anything: a bar that never settles spends the timeout and then fails on the same check with the same message, so a real break is still reported and only the speed of the machine stops being part of the contract. Verified both directions: 178/178 unchanged, and with requestFocus mutated into a toggle (setOpen(was => !was), which is literally 'closes instead of re-focusing') the check fails in all four engine modes. * Require the status write to survive the stale branch, not just follow it Ordering says the write comes after the early return. It does not say the write is still reached: `if (ticket !== statusTicket.current) { return; setStatus(next); }` returns first and satisfies the guard regex, the ordering rule and the exactly-one-write rule while publishing nothing at all. When the stale branch carries a block, the write now has to live past the end of it. The `ticket === current` spelling needs no such rule, since its pattern already ties the write to the guard. Mutations: the stranded write fails, a braced early return with the write after the block passes, the braceless #10788 form passes, and dropping the guard outright still fails. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Score a compile once, at its root, not at every process in the chain The timestamp baseline did not hold. The shell leg failed again on the same cvtres.exe, and the reason it survived the subtraction is that the Security log is written with latency: the positive control's csc.exe started before the installer's window opened, its cvtres.exe child landed just inside, and NEITHER was in the log yet when the baseline was read. There was nothing to subtract. No arrangement of timestamps wins that race. So attribute by the chain instead. A compiler started by a compiler is a step of a compile that is already being scored, not a new one: csc.exe shells out to cvtres.exe to build its resource blob, and counting that as a second hit says the action compiled twice. Reading ParentProcessName off the record settles the cross-step bleed for good, because the child is the only part of the control's chain that was ever in range. Detection is unchanged for a compile the action really starts. Its root compiler is spawned by the installer's shell, not by another compiler, and the window opens before the action does, so the root is in range and is reported. What this drops is only ever the second process of a chain whose first was already seen or was never in range at all. An orphaned cvtres.exe with a non-compiler parent still counts, and a record from a schema with no ParentProcessName at all still counts, so an empty field is not read as a compiler parent. Four tests, covering each of those: the shell's compile, the orphaned resource step, the compiler's own resource step, and the pre-ParentProcessName schema. 53 pass. --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
…adratic (#10868) test_deepseek_r1_huge_fenceless_body_is_linear failed on #10864 at 6.56 against a bar of 6.0, on a branch that touches no parser code. It failed the same way on #10825. The parser is fine: measured locally across all four shapes the median 4x ratio is ~4.0, which is what linear looks like. The measurement is what is wrong. _growth computed min(big over repeats) / min(small over repeats) and its comment claimed that dividing one minimum by the other cancels the machine out. It does not. The two minima come from two batches run at different times, so a quiet window during the small batch and a busy window during the big batch multiply rather than cancel, and the quotient of two separately-taken minima is not a minimum of anything. Measured on 2 pinned CPUs under load, 15 trials per shape: strategy R1 R1-distant GLM V3 >= 6.0 min/min max 8.69 max 8.23 max 8.27 max 8.59 7 of 60 paired median max 4.26 max 4.83 max 4.83 max 5.42 0 of 60 End to end, 10 contended runs of the four linearity tests: the old form fails 3 of 10 runs, the new form 0 of 10. Each pair now times the small input and then the big one back to back and forms the ratio inside the pair, so contention hits both halves and divides out, which is what the old comment claimed for the unpaired form. The median across pairs then discards one that got unlucky in either direction. Detection is kept, which is the half worth checking before loosening a bar. Sabotaging the R1 sweep back to quadratic (re-adding a per-marker tail rescan) still fails, at 14.2x and 15.3x. On a synthetic 16x path the new form reports 8 of 8 over the bar, the same as the old one. On the marginal 6.7x shape (#10832's partially fixed sweep) it reports 9 of 12 against the old 10 of 12, a difference well inside the noise at that sample size, and that shape's sibling test measures 12.2x when broken, so the suite still catches it. The bar stays at 6.0. Nothing here loosens the threshold; it only stops the measurement fed to it from being dominated by whoever else is on the runner. The 60 second backstop still reads the BEST big time rather than the worst, so it fires on a path that is genuinely too slow and not on a runner that stalled once.
unslothai#10868 replaced the linearity check in test_pr5624_regressions.py after it failed on unslothai#10825 and again on unslothai#10864 at 6.56 against a 6.0 bound, both times on branches that touch none of that code. The same shape is elsewhere in the suite: sub-100ms budgets, two separately-taken durations compared against each other, and concurrency proved by how long four threads took. All of them run under pytest -n 4 on a shared runner, where descheduling is indistinguishable from the regression they guard. Each one is rewritten to assert the thing it is named for. test_llama_cpp_wait_for_vram_settle.py has five, all of them claims about the helper's sleeping: did it skip the wait, nap once per poll, clip the last nap to the deadline. Record the durations it asks for and assert on those. The tightest was elapsed < 0.05 around a short-circuit, which one GC pause exceeds. test_account_model_access.py proved eight probes ran together by taking under 0.4s. Its own sibling two functions up already uses a threading.Barrier for the same claim, so use one here too, sized off _PROBE_FANOUT so lowering the fan-out fails this rather than satisfying a Barrier(1). test_mcp_http_sessions.py had three. Two chats running concurrently needed a counter that spans clients, since no single client's max_live can see an overlap between two of them; six parallel closes get a Barrier(6), so a serial close deadlocks and says so instead of merely running slowly; and the eviction test asserts the caller returned while the victim's teardown was still running, which is the property the 0.5s bound was standing in for. test_stream_cancel_registration_timing.py compared two separately-taken durations, exactly what unslothai#10868 had to remove from _growth. The two patterns differ in chunks seen, deterministically: the blocking loop never lets the cancel through and drains all eight, the awaiting loop stops at the first. Four guards against a quadratic blow-up carried absolute budgets (test_tool_xml_strip.py, test_update_release_notes.py, test_rag_store.py). Backtracking is superlinear by definition, so growth is the property, and unslothai#10868's paired-ratio statistics already exist for it. Lift _growth and _assert_linear out of test_pr5624_regressions.py into tests/_shared/growth.py, generalised over the function under measurement, next to real_accelerator.py and for the same reason. test_profile_stats.py and the two liveness files keep a wall-clock bound, because "it did not block" is what they mean, but a generous one: the sharp claim in each is already asserted next to it (the row count is zero, stop() returned False, the stub raises if detection starts). test_backend_ci_parallel_isolation.py scans for this shape and required three named files to keep exhibiting it, which made it a second, invisible reason those files could not be fixed: rewriting the vram-settle bounds failed there, in a file about CI topology, with a message about a sample. It builds all three shapes itself now. Not touched: test_health_answers_within_probe_budget.py. Its bounds are the subject, derived from the real desktop probe timeout rather than from a guess, and it already asserts on state where state was the honest answer. Each rewritten assertion was checked against a deliberately broken implementation: no cold-start short-circuit, an unclipped sleep, a one-shot wait loop, _PROBE_FANOUT of 1, _MAX_CLOSE_THREADS of 1, and two synthetic quadratic sweeps. Full backend suite run the way CI runs it, three times: identical failure set to main.
#10897) * Stop ten test assertions from measuring the runner instead of the code #10868 replaced the linearity check in test_pr5624_regressions.py after it failed on #10825 and again on #10864 at 6.56 against a 6.0 bound, both times on branches that touch none of that code. The same shape is elsewhere in the suite: sub-100ms budgets, two separately-taken durations compared against each other, and concurrency proved by how long four threads took. All of them run under pytest -n 4 on a shared runner, where descheduling is indistinguishable from the regression they guard. Each one is rewritten to assert the thing it is named for. test_llama_cpp_wait_for_vram_settle.py has five, all of them claims about the helper's sleeping: did it skip the wait, nap once per poll, clip the last nap to the deadline. Record the durations it asks for and assert on those. The tightest was elapsed < 0.05 around a short-circuit, which one GC pause exceeds. test_account_model_access.py proved eight probes ran together by taking under 0.4s. Its own sibling two functions up already uses a threading.Barrier for the same claim, so use one here too, sized off _PROBE_FANOUT so lowering the fan-out fails this rather than satisfying a Barrier(1). test_mcp_http_sessions.py had three. Two chats running concurrently needed a counter that spans clients, since no single client's max_live can see an overlap between two of them; six parallel closes get a Barrier(6), so a serial close deadlocks and says so instead of merely running slowly; and the eviction test asserts the caller returned while the victim's teardown was still running, which is the property the 0.5s bound was standing in for. test_stream_cancel_registration_timing.py compared two separately-taken durations, exactly what #10868 had to remove from _growth. The two patterns differ in chunks seen, deterministically: the blocking loop never lets the cancel through and drains all eight, the awaiting loop stops at the first. Four guards against a quadratic blow-up carried absolute budgets (test_tool_xml_strip.py, test_update_release_notes.py, test_rag_store.py). Backtracking is superlinear by definition, so growth is the property, and #10868's paired-ratio statistics already exist for it. Lift _growth and _assert_linear out of test_pr5624_regressions.py into tests/_shared/growth.py, generalised over the function under measurement, next to real_accelerator.py and for the same reason. test_profile_stats.py and the two liveness files keep a wall-clock bound, because "it did not block" is what they mean, but a generous one: the sharp claim in each is already asserted next to it (the row count is zero, stop() returned False, the stub raises if detection starts). test_backend_ci_parallel_isolation.py scans for this shape and required three named files to keep exhibiting it, which made it a second, invisible reason those files could not be fixed: rewriting the vram-settle bounds failed there, in a file about CI topology, with a message about a sample. It builds all three shapes itself now. Not touched: test_health_answers_within_probe_budget.py. Its bounds are the subject, derived from the real desktop probe timeout rather than from a guess, and it already asserts on state where state was the honest answer. Each rewritten assertion was checked against a deliberately broken implementation: no cold-start short-circuit, an unclipped sleep, a one-shot wait loop, _PROBE_FANOUT of 1, _MAX_CLOSE_THREADS of 1, and two synthetic quadratic sweeps. Full backend suite run the way CI runs it, three times: identical failure set to main. * Size the growth fixtures off the old bound, and derive the liveness ceilings Two review findings, both right. assert_linear measures units AND units * factor, so replacing an absolute budget means passing the old size divided by factor. Three of the five conversions did that; the backtick-run and orphan-opens ones did not, and their big leg ran at 4x anything previously measured. That matters only on the regression each guards: the backtick parser took over a minute at 20k when broken, so at 80k it would take about sixteen, and the job timeout would kill the run before the ratio could say why. The big < 60.0 backstop cannot help, because it is checked after the measurement rather than during it. Both call sites now put the previously measured size on the big leg, and assert_linear says so where a caller reads it. The liveness ceilings were widened to a number with no relation to the product. commands.rs gives each watchdog probe HEALTH_PROBE_TIMEOUT, ten seconds, so a route that blocked for 10 to 29 seconds passed the test while timing out every real probe. Read that constant, as test_health_answers_within_probe_budget.py already does for its own budget, and use half of it: ten times the headroom of the 0.5s it replaces, and provably inside what the launcher allows. * Tighten the comments this branch added * Pin two timing assertions to what they are about, not to slack The eviction test's victim slept 1.5s, which a caller only had to outwait part of to read as prompt; it now holds its teardown on an event the test releases, so a caller that waits on it at all cannot return, and the remaining ceiling comes from _SESSION_CLOSE_TIMEOUT rather than being picked. The writer shutdown test now records the timeout stop() hands its join instead of allowing 5s of wall clock, so a stop() that waits whole seconds fails even though the elapsed budget would have passed it. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Assert both ends of the settle window, and stop buying slack this leg does not need The never-settles case only checked that the helper napped more than once, so a loop capped at two iterations recorded [0.1, 0.1] and passed while the VRAM was still moving. Both ends are now read off the recorded naps. The terminal-callback bound goes back to 1.0s: studio-backend-ci.yml ignores test_profile_stats.py in the -n 4 leg and reruns it serially, so a looser bound only lets a stalling callback through. * Bound liveness against a route that does nothing, not against the watchdog Half the watchdog's probe budget is 5s, which passes a route that grew seconds of synchronous work on the event loop. The probe snippets now serve a route that only returns a dict through the same app and client, so both pay the same interpreter and scheduler and what is left is the route's own cost. The watchdog bound stays as the second half of the pair: a relative bound cannot see an absolute timeout, since a control that took seconds would scale with it. * Bound the eviction call against the same call with nothing to evict Half of _SESSION_CLOSE_TIMEOUT is five seconds, which passes a caller that blocks for a second before handing the victim to the cleanup worker. The cap is now applied after a control call on a second URL, so the two differ only in whether an eviction happens and the claim is measured rather than budgeted. * Take the runner out of the clipping test, abort a known-slow growth run, drop a live dependency The slow-probe test asked for a nap that a correct helper need not make: if the scheduler ate the 0.1s left of the budget it returned at the deadline check instead, and the assertion failed on a good run. It now runs on a clock the test moves, so the probe charges its cost instead of sleeping and every sample is exact. growth() takes abort_over_s, so a big leg already over the backstop stops the repeats instead of measuring the same known-bad path three times. The parallel-isolation meta-test no longer requires the live backend suite to still contain a fragile assertion; the synthetic files cover every shape, and that requirement would have turned cleaning the last one into a failure. * Pair the liveness controls, clock the drift test, ask the eviction by thread A control taken in its own batch shares no scheduler delay with the request it is compared against, so a pause landing on the measurement alone was not divided out and the 50ms floor made that stricter than the bound it replaced. Both liveness snippets now alternate control and measurement and take the best of three on each side. The never-settles test moves to the same fake clock as the slow-probe one: its lower bound says the helper did not stop early, and real time spent outside sleep() retires the deadline without appearing in the naps. The eviction test asks which thread calls close() instead of how long the caller took. __aexit__ cannot answer it, since that always runs on the session's own loop thread, but the caller of close() is exactly the claim in the test's name. * Size the close barrier off the fan-out, and watch the join as well as the close A fixed Barrier(6) deadlocks a correctly batched close configured any narrower than six and then reports it as serial. It now waits for one batch and opens exactly that many sessions, so a partial last batch cannot leave stragglers waiting for a party that never arrives. The eviction test also records joins on the cleanup worker. Handing the teardown off and then waiting on the worker anyway spends the same deadline, and nothing else here can see it: a bounded join leaves the close off the calling thread and the session still open. --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Training does not work in
unsloth/unsloth:lateston a machine with a GPU. Studio's Train page, the bundled notebooks,unsloth trainand GRPO all stop with aTypeErrorthe moment they build a trainer. This makes them work.Why it breaks
The Studio image sets
ENV UNSLOTH_ALLOW_CPU=1so the image can also start on a machine without a GPU. Inside the Unsloth library that same variable means something different: "CPU-only CI, skip the TRL patches" (since #5429). An imageENVreaches every process in the container, so on a GPU host everything in the image trains with stock TRL instead of Unsloth's trainers.Measured on the published image (RTX 6000 Ada and RTX 3090, driver 610.43):
SFTConfig.__init__() got an unexpected keyword argument 'max_seq_length'Gemma3_(270M).ipynbin JupyterLab, orunsloth-runSFTTrainer.__init__() got an unexpected keyword argument 'tokenizer'unsloth trainSFTConfigerrorfast_inference=True'Qwen3ForCausalLM' object has no attribute 'warnings_issued'243 of the 445 notebooks baked into the image pass
tokenizer=to a TRL trainer, so the notebook failure is not one notebook.The two images differ, which is the clearest symptom:
from trl import SFTTrainer, GRPOTrainergivestrl.trainer...SFTTrainer/GRPOTrainerinsidelatest, andUnslothSFTTrainer/UnslothGRPOTrainerinsidecore, which never sets the variable.The fix
The image keeps its own opt-in and stops handing the library a variable that means something else:
Dockerfile.studiosetsUNSLOTH_IMAGE_ALLOW_CPU=1instead ofUNSLOTH_ALLOW_CPU=1. The build itself still passesUNSLOTH_ALLOW_CPU=1toinstall.shinline, because the build host has no GPU.entrypoint.shnow decides per container. GPU visible: it unsetsUNSLOTH_ALLOW_CPUfor everything it starts, and warns if the user passed it. No GPU: it exportsUNSLOTH_ALLOW_CPU=1when the opt-in is on, so Studio, JupyterLab and the notebooks still work on CPU.-e UNSLOTH_ALLOW_CPU=0still gives the strict refusal on a GPU-less host, and:corestill refuses without an opt-in.UNSLOTH_SKIP_GPU_CHECK, which skips the torch checks and not the variable's meaning.gpu_visible()readsnvidia-smi -Linto a variable beforegrep -q: underset -o pipefail, agrep -qthat exits on the first line can turn the producer's SIGPIPE into the pipeline's status, which would read as "no GPU".Before and after
A is the published
unsloth/unsloth:latest/:core. B is both images built from this branch with the same pinned refs.docker exectrainer classes, GPU hostSFTTrainer/GRPOTrainerUnslothSFTTrainer/UnslothGRPOTrainerGemma3_(270M).ipynbthroughunsloth-runTypeErrorunsloth train --max-steps 5SFTConfigfast_inference=Truewarnings_issuedGRPO_OK,UnslothGRPOTrainerUNSLOTH_ALLOW_CPUin the Studio process / adocker execshell:corewith-e UNSLOTH_ALLOW_CPU=1on a GPU hostThe rest is unchanged on both sides. A CPU-only host still starts with its warning, still has the variable in the Studio process, and reached the same 9 UI checks;
-e UNSLOTH_ALLOW_CPU=0with no GPU still exits 1;:corestill refuses without an opt-in and starts on CPU with one. Studio chat, JupyterLab, GGUF export andllama.cppbehave the same.Verification
tests/python/test_docker_cpu_fallback.py: 17 passed. Five of them fail onmain: the image opt-in, the absentENV, the CPU export, the dropped explicit value on a GPU host, and theSKIP_GPU_CHECKpath. The entrypoint cases run the real script against stubbednvidia-smiandpython, and read the environment the exec'd command receives.tests/python/test_docker_*.pyplustests/studio/install/test_docker_studio_keep_cuda_prebuilt.py: 521 passed, 5 skipped, 1 failed. The failure,test_docker_nb_refresh_state_durability.py::test_an_abandoned_restore_puts_the_tree_back, fails identically onmain.Not in this PR
The variable still means two things inside Unsloth: "allow CPU" and "skip the TRL patches" are the same switch. Keying the skip on an actually absent accelerator is a library change, separate from this.
On a CPU-only host, a
docker execshell no longer inheritsUNSLOTH_ALLOW_CPU, sopython -c "import unsloth"there reports that it needs a GPU. Studio, JupyterLab, their kernels and SSH logins all still get it, andunsloth studio reset-password,unsloth-llama-updateand Studio chat were checked in that state.Passing
-e UNSLOTH_ALLOW_CPU=1on a GPU host now gets a warning and patched trainers. Shells opened withdocker execstill see the value passed todocker run, which the warning says.