Skip to content

Studio: keep a Windows update from leaving a CPU-only PyTorch - #9857

Merged
danielhanchen merged 23 commits into
mainfrom
studio-windows-torch-flavor-invariant
Aug 31, 2026
Merged

danielhanchen merged 23 commits into
mainfrom
studio-windows-torch-flavor-invariant

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Aug 27, 2026 •

Copy link
Copy Markdown
Member

What happens

Two Windows users hit this independently after the in-app update to desktop 0.1.803-beta (package 2026.8.21).

A machine with 2x RTX A4000 (driver 553.09, CUDA 12.4) had been training and holding models in VRAM the day before. After the update, Settings > System showed VRAM --, "No visible GPU", "GPU devices: No visible GPU detected", and everything ran on CPU. nvidia-smi listed both cards, Device Manager was clean, and UNSLOTH_PREBUILT_INFO.json still said backend cuda / runtime_line cuda12. The managed venv reported:

2.11.0+cpu None False 0

and the bundled llama-server reported:

> & "$env:USERPROFILE\.unsloth\llama.cpp\build\bin\Release\llama-server.exe" --list-devices
Available devices:
  (none)

A second user reported the same shape on a different machine, RTX recognised via Vulkan but not CUDA, with the video and training sections refusing to load. Their downgrade was affected too, which is expected: upgrade and downgrade take the same environment-mutating path.

Both were fixed by rerunning the installer, which printed exactly the line that names the problem:

PyTorch flavor mismatch (installed cpu, need cu124) -- reinstalling correct build...

Why

The in-app updater runs unsloth studio update, which runs studio/setup.ps1, which runs studio/install_python_stack.py. install.ps1 is never on that path, and install.ps1:5925-5985 holds the only PyTorch flavor repair there has ever been. Its helpers Get-ExpectedTorchFlavorTag and Get-InstalledTorchTag live inside the script-level try and are not dot-sourceable, so setup.ps1 cannot borrow them.

Meanwhile the dependency steps in install_python_stack.py install with deps and without an --index-url, so the resolver's default source is PyPI, and studio/backend/requirements/single-env/constraints.txt names no torch to cap it. On Windows PyPI's torch is CPU-only.

Both Windows repair passes are disabled in that file:

  • install_python_stack.py:2350 returns early on Windows, commented "Windows torch is owned by install.ps1"
  • install_python_stack.py:5613 gates all of step 13 on not IS_WINDOWS, immediately under a comment reading "Steps above can pull CUDA torch from PyPI, so repair last"

That assumption holds for a fresh install. It does not hold for an in-app update, which bypasses install.ps1 entirely. So a cu124 venv can come out of an update as 2.11.0+cpu with the update reporting success.

The (none) device list is downstream of the same wheel. llama_cpp.py:9824 _windows_pip_nvidia_dll_dirs supplies cudart64_*.dll and cublas64_*.dll to the CUDA-built llama-server from the venv's torch/lib and nvidia/* wheels. A +cpu venv ships neither, so the CUDA ggml backend cannot load and enumerates nothing, while the prebuilt marker still correctly says cuda.

What this PR does

A Windows torch flavor invariant, as step 13w in install_python_stack.py.

_ensure_expected_torch_flavor() resolves the flavor this venv is supposed to hold, most authoritative first:

  1. UNSLOTH_EXPECTED_TORCH_TAG, exported by setup.ps1 right before the handoff, so it describes the index the torch install arm actually used
  2. the flavor the last completed install recorded in the manifest, read at import because install_python_stack() drops the manifest before the dependency pass
  3. a live probe, for a run nothing set up

On a mismatch it prints install.ps1's line verbatim and reinstalls the bounded trio (torch>=2.4,<2.11.0, torchvision>=0.19,<0.26.0, torchaudio>=2.4,<2.11.0) from the correct index. That trio is deliberately byte-identical to install.ps1's $_fixSpecs rather than to _CUDA_TORCH_PKG_SPEC: a venv repaired by studio update should land on the same wheels as one repaired by the installer, or a support log stops describing one install.

If torch is still CPU-only afterwards on a host that expected a GPU build, the install now fails. install.ps1 warns and exits 0 there; failing is the point of this function, because that exact state is what was being reported as "dependencies up to date" while the app ran on CPU.

It is conservative by construction. These no-op:

  • no-torch mode
  • a stated UNSLOTH_TORCH_BACKEND that disagrees with the handover, so a user who asked for cpu / rocm / xpu keeps it
  • an expected tag that is absent, cpu, or unreadable
  • a rocm expectation, which delegates to the ROCm path that owns the per-architecture repo.amd.com index no generic tag can name
  • torch missing or present-but-unimportable, which is the base install's problem and a louder failure than a wrong flavor
  • installed flavor already equal to the expected one
  • CUDA_VISIBLE_DEVICES emptied or -1, but only for an expectation this run inferred from the hardware. An emptied mask is a reason not to conclude cu124 from a probe; it is not a reason to ignore a cu124 somebody stated. Vetoing a stated expectation on a mask reproduced the whole defect, so it is pinned by tests both ways

An xpu expectation IS enforced, and was in an earlier revision of this PR excluded. setup.ps1 publishes "xpu", so ignoring it left the invariant incoherent: step 13's repair set is gated off Windows entirely, and nothing else looks at that venv after the dependency steps have re-resolved torch from PyPI. It repairs against the XPU floor (torch>=2.6, which unsloth/models/_utils.py raises below) rather than the CUDA one.

A no-wipe escape in setup.ps1. Separate bug on the same path, worth fixing here because it bites the same users. setup.ps1:4152 collapses the expected tag to "cpu" whenever its bounded nvidia-smi probe comes back empty. On a direct update none of the existing escapes apply (the pin escape needs a pin, the in-place escape needs cu* to cu*, the preserve guards need $InstallerManagedSetup, which is only true under install.ps1), so a healthy cu124 venv was deleted and setup then aborted telling the user to run install.ps1. There is no rollback copy on that path, because only install.ps1 keeps one. Now it keeps the venv and warns.

Manifest support. write_manifest(..., expected_torch_tag=...) and recorded_torch_flavor(), additive, schema unchanged. Only the flavor tag is recorded, never the index URL: a pinned index can carry a token in userinfo, query or fragment, and this file sits in the venv and is read back by verify-install. There is a test asserting no http ever reaches the manifest.

Not changed, deliberately

  • studio/setup.sh. The invariant is Windows-gated, setup.sh selects no torch index (install.sh does), and install_python_stack already reads the pin env vars directly. An export there would have no reader.
  • studio/src-tauri/src/update.rs. Forwarding UNSLOTH_INSTALLER_TORCH_TAG from the desktop looks like the natural fix but is a no-op: the child already inherits the environment, and the desktop process never holds that variable (install.ps1 sets it in its own process). Its only consumer also requires UNSLOTH_INSTALL_ROLLBACK_MANAGED, and setting that on the desktop path would tell setup.ps1 a rollback copy exists when none does. The manifest fallback covers the desktop update instead.

Testing

Suite Result
tests/studio/install/ (full) 2894 passed, 3 skipped
tests/studio/install/test_cuda_repair.py 192 passed
tests/studio/install/test_windows_torch_flavor_invariant.py 31 passed (new file)
tests/python/test_install_python_stack.py 169 passed
tests/studio/test_xpu_triton_swap.py 60 passed
the same set on Python 3.10 and 3.12 3100 passed, 4 skipped each
studio/setup.ps1 under real PowerShell 7.6 34 checks, 0 failures
ruff (pinned 0.6.9) on all changed Python clean

The new tests cover the escape's ordering and narrowness, StrictMode-safe condition ordering, the handover export ordering, install.ps1 to Python parity for the spec trio and both message texts, AST wiring of step 13w, the step-total arithmetic re-executed from source, and the manifest round-trip. The repair harness makes a repair that works and one that does not genuinely different runs, rather than asserting on a mock call list.

Windows and macOS did run. Rather than leave this as source-parity only, the branch was replicated onto a staging repo and its full CI executed there: all 21 workflows green, including Windows Unsloth UI / API / Update / GGUF / Application Control, Mac Unsloth Install Matrix, Mac UI + API + Update + Inference, Clean machine install, Interrupted install recovery and Kaggle T4 GPU CI.

Behaviour, before and after. The repair step was run from this branch and from the merge base against a throwaway venv holding a real torch on disk:

venv before after
CPU wheel on an NVIDIA host stays 2.11.0+cpu, update reports success repaired to 2.6.0+cu124
the genuine PyPI win_amd64 wheel, unpacked stays CPU-only, success repaired
a repair that does not take silently succeeds update fails
healthy cu124 / rocm6.4 / xpu untouched untouched
deliberate CPU install untouched untouched
cu124 under a cu128 expectation untouched repaired

The exact argv the repair builds also resolves against the live PyTorch indexes, checked with uv pip install --dry-run: cu124, cu128, xpu and cpu each land a consistent trio with matching local tags.

Follow-up

The reporting half of this is a separate change: a +cpu torch currently makes the backend say "No visible GPU" rather than "PyTorch is CPU-only and cannot use the 2 NVIDIA GPUs on this host", because every GPU field is gated on torch.cuda.is_available() and nvidia-smi is never consulted once that returns False. Same shape as #8473. That fix, plus the repair action in Settings both users asked for, follows in a second PR.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 27, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 27, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 27, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 27, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 27, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 27, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 27, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 27, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 27, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 27, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 27, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 27, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 27, 2026
@oobabooga

Copy link
Copy Markdown
Member

Reviewed this and it looks right to me. The Windows update path previously skipped torch flavor repair, and the new final repair step re-probes after dependency installs while preserving the expected flavor through the setup handoff. With PowerShell 7.6.5 available, tests/studio/install passed with 2,818 passed and 12 skipped. Ruff also passed, and the broader tests/studio failure list matched the merge base exactly.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@danielhanchen

Copy link
Copy Markdown
Member Author

On the one red check here, Mac Unsloth UI + API + Update + Inference CI.

It is the Multi-turn determinism via OpenAI + Anthropic SDKs step in .github/scripts/studio_smoke/multi_turn_chat.py, which asserts that two identical requests at temperature 0 return byte-identical text, and it fails on main for the same reason. The three most recent runs of that workflow on main (33301417667 and the two before it) all fail on the same assertion at turn 2, with the same pair of near-miss completions from the 270M model. Nothing in this PR touches inference, sampling or the llama.cpp bindings.

I also hit the Linux instance of the same step earlier in this branch; it cleared on a rerun with no code change, which is what a nondeterministic assertion does.

The one real failure this branch did cause was Repo tests (CPU): tests/studio/test_xpu_triton_swap.py still asserted the old contract in which the Triton swap had exactly two repair points and Windows was skipped outright. Step 13w adds a third, and a direct python install_python_stack.py on Windows has no setup.ps1 postlude to swap Triton back afterwards, so the test was calling the fix a regression. Fixed in 747983f, with Windows now covered on both sides: it defers when setup.ps1 published the handover variable, and does the swap itself when nothing else will.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Can't wait for the next one!

Reviewed commit: 4b06de2e6b

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

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".

danielhanchen and others added 2 commits August 31, 2026 05:04
Comment-only pass over the eight files this branch touches: delete restatements
of the code, section banners and narration, and collapse multi-line blocks that
did not carry a distinct fact per line. Added comment lines 409 -> 140.

No code or behaviour change. Installer suites still pass (3123 passed).
chatgpt-codex-connector[bot]

This comment was marked as resolved.

danielhanchen and others added 2 commits August 31, 2026 08:49
Two problems on the verification that runs after the flavor repair.

_installed_flavor_tag_now fell back to reading torch/version.py whenever the
runtime probe did not answer cleanly, which lumps together two different facts.
A probe that could not RUN is the wedged-driver host the fallback exists for. A
probe that ran and reported that torch does not import is a definitive answer,
and version.py still names the requested +cu124 tag from a half-written or
DLL-less wheel, so the caller read tag == expected and wrote a completion
manifest over a torch nothing can import. That is the same "reported success
while unusable" state this whole change exists to remove, one layer later. The
probe now reports that case distinctly and the update fails with its own
message, which does not name the family: the wheel on disk may well be the right
one, and what is wrong is that it does not load. A torch that failed to import
BEFORE the repair cannot reach this, since the pre-repair chain returns early.

Second, when the CUDA major moved and the replacement torchao could not be
installed, the old one was left in place with a warning about the slow path.
Across a CUDA-major move it is not the slow path: _select_torchao_spec exists
because a torchao compiled for CUDA 12 cannot load its cpp under cu130, so the
update completed holding a package that may fail on import. Remove it, the way
the xFormers arm two lines down already removes a build made for a torch that is
gone. A release-only move keeps the old warning, because that one really is just
slower.

Fixing the second exposed a hole in the harness those tests share: its
pip_install_try stub only appended to a list, and list.append returns None, so
every test in that class had been exercising the could-not-install branch
without meaning to. The stub now returns a bool and takes a knob, so success and
failure are different runs.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

$script:TorchImportDefinitivelyFailed is raised when the probe reports an import
error rather than a timeout, so the wheel is the suspect and not the driver. Two
things then ignored it.

The flag never cleared $SkipPythonDeps, and every consumer of it lives inside
`if (-not $SkipPythonDeps)`. On a current core package with a valid manifest the
fast path announced a reinstall it then skipped, and setup exited successfully
over an unusable wheel.

The XPU and CPU arms never read it. Their force gates fire on a flavour change
or a pin change, and neither applies here: an unimportable +xpu wheel still
reports its on-disk tag as "xpu", so the bounded range is satisfied and the
resolver keeps it. The ROCm arm already forces every time.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 31, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 31, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 31, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 31, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Keep them coming!

Reviewed commit: d6c6ca2427

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

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".

danielhanchen added a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Aug 31, 2026
@danielhanchen
danielhanchen merged commit d5b153c into main Aug 31, 2026
58 of 74 checks passed
@danielhanchen
danielhanchen deleted the studio-windows-torch-flavor-invariant branch August 31, 2026 09:58
danielhanchen added a commit that referenced this pull request Aug 31, 2026
#9857 carried the same install_python_stack.py / setup.ps1 work, so its squash
merge conflicts with this branch's copy. Resolved by taking whichever side is
newer per hunk, and combining where both added something:

- _installed_flavor_tag_now keeps this branch's XPU-aware family reading AND
  main's _TORCH_TAG_UNIMPORTABLE answer for a probe that ran and did not import.
- _TORCH_TAG_UNIMPORTABLE, _warn_repair_left_torch_unimportable and the torchao
  removal across a CUDA-major move come from main; this branch never had them.
- _gpu_family_from_runtime_markers, _recordable_torch_flavor_tag, the flavor
  argument to _expected_torch_flavor_was_pinned and the manifest's
  expected_torch_tag_pinned key stay from this branch.
- setup.ps1 differed only in one comment; main's is the later wording.
danielhanchen added a commit that referenced this pull request Sep 1, 2026
* Stop the torchao ROCm test from depending on the host's GPU

test_skips_torchao_on_windows_rocm described a machine that cannot exist: a
Windows host with ROCm torch installed AND a usable NVIDIA GPU. The NVIDIA
claim is the input _expected_torch_flavor_tag uses to decide whether a CUDA
expectation exists at all, so the test asked for a cu* build on a box it had
just called ROCm.

That was inert until #9857 added the Windows torch flavor invariant, which is
the first step in install_python_stack to read the real installed torch. With
a CUDA expectation manufactured by the test and the CPU-only torch that
studio-backend-ci.yml installs, the invariant correctly refused the install
and returned 1, so a test about torchao selection failed on an assertion about
the whole installer. It passed on a CUDA workstation and failed on CI, on the
same code.

The invariant is right and stays as it is: on a real Windows ROCm host
_has_usable_nvidia_gpu is False, the expected tag is empty, and the step
returns early, so no ROCm user is affected. It is the fixture that was wrong.

The host is now coherent (no NVIDIA GPU), and the installed torch is pinned
through _probe_torch_runtime and _RECORDED_TORCH_TAG so the verdict no longer
depends on whatever torch the developer happens to have. #9857's invariant
keeps its own coverage in tests/studio/install/test_windows_torch_flavor_invariant.py.

Also adds the (True, True) case. Both signals agreeing is the ordinary Windows
ROCm state and the parametrization only covered the two mixed ones.

* Call the MCP start_training guard through the public fastmcp API

fastmcp 4.0.0 released today and dropped FastMCP._call_tool_mcp, so this
test started failing with AttributeError on every CI run that resolved
the dependency fresh. The pin is an open fastmcp>=3.0.2, so nothing held
CI on 3.x.

Nothing in the product is affected: every fastmcp import the backend
actually makes still resolves on 4.0.0, and the whole backend suite is
green there apart from this one test. So the pin is fine and only the
test needs to change.

Switch to get_tool/call_tool, which are public and carry the same
signatures on 3.0.2 (the floor) and on 4.0.0, and drop the
server._mask_error_details assertion. That flag was a stand-in for "the
409 detail reaches the caller", which the two message assertions below it
already prove directly, so the check cost a private attribute and bought
nothing. Verified against real installs of both 3.0.2 and 4.0.0.

---------

Co-authored-by: danielhanchen <[email protected]>
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 18, 2026
The sweep decided what to delete from a capture group it reached through $Matches after
a -notmatch. Which of -match and -notmatch populates $Matches, and on which result, is
version-sensitive in exactly the way unslothai#9857's empty-string-vs-null was, and a read that
comes back empty here feeds [int]::TryParse and skips the entry. Failing safe is the good
case; a wrong pid is not. Take the group off a [regex]::Match whose semantics do not
move between Windows PowerShell 5.1 and 7.x.
danielhanchen added a commit that referenced this pull request Sep 18, 2026
…11248)

* setup.ps1: stop a stale-venv rebuild deleting the venv it runs from

`unsloth studio update` runs setup.ps1 from the managed venv's own python.exe.
When the torch flavor no longer matches the host (here: cu130 installed, an
AMD GPU now in the machine, so rocm required), the direct-update branch did
Remove-Item -Recurse on that venv. Windows will not delete a running image, so
the delete emptied Lib\ and failed on Scripts\python.exe, leaving a venv with
no unsloth_cli and no rollback copy; the desktop's update and repair both start
from that interpreter, so neither could recover it.

setup.ps1 now knows when it runs from inside the venv (the CLI names its
interpreter as UNSLOTH_SETUP_HOST_PYTHON; a bounded Win32_Process walk covers
an older CLI) and takes the in-place PyTorch reinstall install.ps1 already uses
for the same situation. A rebuild that does run renames the venv aside first,
so a lock fails whole instead of after deleting most of the tree.

* setup.ps1: order the in-place route last, and make the venv probe separator-correct

The new direct-update escape sat ahead of the nvidia-smi cu* preservation guard. Its
condition is true for every stale direct update, because the desktop always runs setup
from the venv's own python.exe, so it consumed $shouldRebuild before the narrower guard
was tested and that guard could never fire.

That guard does two things: it keeps the venv, and it publishes
$script:PreservedInstallerTorchTag, which is what holds the index selection on the cu*
arm. Shadowed, the tag stayed null while the in-place route set
$script:PinChangedForceReinstall, and the pair reached the CPU arm. Replaying the
shipped ladder over 320 enumerated cells, base and head agree on 289; the one cell that
is neither an intended fix nor a match is an unpinned direct update with a cu128 venv
and a silent nvidia-smi:

  base: uv pip install torch torchvision torchaudio --index-url .../whl/cu128
  head: uv pip install torch torchvision torchaudio --force-reinstall --index-url .../whl/cpu

which is the CPU-only update #9857 added that guard to stop. Moving the block below the
guard leaves all 30 intended fixes and restores that cell; base and fixed now differ in
0 cells where the venv is kept on both sides.

Get-SetupHostInterpreterInVenv built its containment prefix with a literal backslash.
.NET returns '/'-separated paths from GetFullPath off Windows and treats '\' as an
ordinary filename character, so the prefix matched nothing and the helper answered null
for every input. Only Windows runs setup.ps1 for real, but the shipped pwsh tests run
everywhere, and test_the_cli_hint_names_the_venv_interpreter was red on every non-Windows
runner while its sibling passed vacuously. Build the prefix from
DirectorySeparatorChar instead.

Also move the stale-venv sweep out of the rebuild branch, so an install that renamed a
venv aside, failed to delete the copy under a lock, and thereafter only ever repairs in
place still collects it, and give the destination a pid suffix so two rebuilds inside
one second cannot collide on a name.

* setup.ps1: let the stale-venv sweep prove a directory is ours before deleting it

Moving the sweep out of the rebuild branch put it ahead of the custom-root ownership
guard, so that guard can no longer cover it, and "$_venvLeaf.stale-*" is a wildcard
rather than a proof of ownership: a user's own unsloth_studio.stale-backup matches it and
was deleted on an ordinary healthy update.

Validate the way install.ps1 already validates its own rollback sweep
(Test-StudioVenvRollbackMustBePreserved): refuse anything outside the generated
timestamp-PID shape, refuse reparse points, and spare a copy whose owning process is
still alive, which is a concurrent setup's rescue copy rather than our litter. Enumerate
with -Force too, so a leftover that picked up the hidden attribute is not skipped
forever by the sweep meant to collect it.

test_setup_ps1_stale_sweep_only_removes_its_own_litter runs the shipped sweep under pwsh
against real directories rather than reading it: an abandoned copy in the generated shape
goes, a stale-backup directory and a live owner's copy stay, and the live venv is never
touched. It fails on the unvalidated sweep with "a directory outside the generated name
shape must be left alone".

Routing is unchanged: replaying the ladder over the same 320 cells still gives 30 fixes,
0 violations and 0 newly wiped cells against base.

* studio.py: say that UNSLOTH_SETUP_HOST_PYTHON is a hint, not a promise

sys.executable is the managed venv's python.exe on the path that matters, where the
desktop spawns the managed CLI. It is not on the others: a pip-installed CLI, a repo
checkout and a staged run all put an interpreter here that lives nowhere near $VenvDir.

That is already safe, because setup.ps1 tests containment itself and a value outside the
venv reads as 'not inside', which keeps the pre-existing rebuild. The comment asserted
the guarantee as fact, which is the kind of thing that later justifies dropping the
containment test as redundant. Say which path it holds on and who checks.

* setup.ps1: read the stale-venv pid from an explicit Match, not $Matches

The sweep decided what to delete from a capture group it reached through $Matches after
a -notmatch. Which of -match and -notmatch populates $Matches, and on which result, is
version-sensitive in exactly the way #9857's empty-string-vs-null was, and a read that
comes back empty here feeds [int]::TryParse and skips the entry. Failing safe is the good
case; a wrong pid is not. Take the group off a [regex]::Match whose semantics do not
move between Windows PowerShell 5.1 and 7.x.

* Tighten the comments added by this change

Opening comment-reduction pass over this PR's own additions only, not the surrounding
file: 62 added comment lines to 43. Every surviving line names a mistake the next reader
would otherwise make, which is why the ordering rationale and the ownership rationale
keep a line each. AST-verified comment-only against b30af0c.

* Second comment sweep over this change's own additions

The in-place-route block restated the undeletable-running-image mechanism the function
header above it already gives, so it keeps only what is local to the decision: the issue
number, and that a hand-run checkout still rebuilds. setup.ps1 additions 32 comment lines
to 27. AST-verified comment-only against 7d0b1da.

* Make the stale-copy sweep prove ownership before it deletes

Three things found while simulating this PR, all in the new code rather than in what it replaced.

The sweep runs on every qualifying setup, including one that rebuilds nothing, and it runs ahead
of the custom-root guard. Its only authority for a recursive delete was a name, so a directory
named unsloth_studio.stale-<14 digits>-<pid> next to the venv was deleted on a run that otherwise
changed nothing, and also on a custom UNSLOTH_STUDIO_HOME whose venv the rebuild then refused to
touch for want of an Unsloth sentinel. Both are now refused: the guard predicate is hoisted so the
sweep asks the same ownership question the rebuild asks, and a candidate must carry pyvenv.cfg,
the studio-owned marker, or the new .unsloth-studio-stale marker that the rename drops into the
copy it moved. A copy too far gone to carry any of the three is named and left alone rather than
deleted blind. The marker is rewritten when the delete after the rename fails, so the litter that
branch announces is still litter the next run can identify.

Get-SetupHostInterpreterInVenv accepted a hint that named nothing. The hint is an inherited
environment variable and can outlive what it names, and a stale one pointing inside the venv would
route a venv that genuinely needs rebuilding into an in-place repair with no interpreter to
perform it. It must now name a file that is there. The parent walk also compares creation dates
before following ParentProcessId, which is what Microsoft's own Win32_Process guidance says to do
about reused process ids.

The rename destination took the timestamp and the pid but had no retry, while install.sh's
_start_studio_venv_replacement, which this mirrors, appends a numeric suffix until the name is
free. One process can reach this twice inside a second, and a copy it left earlier can still be on
disk because its delete failed. A taken name now takes a bounded suffix, and the sweep's shape
recognises it, or the copy it names could never be cleaned up.

Tests: the sweep test now drives the shipped sweep over six directories, including one that wears
the name and holds no environment and one whose name took a collision suffix; a new test refuses
an unclaimable custom root and then, as a negative control, sweeps the same tree once the owned
marker is present; the helper test adds a hint naming a deleted path, a directory, and Scripts
itself, with the real interpreter as its control.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

---------

Co-authored-by: Daniel Han <[email protected]>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
shaojun pushed a commit to shaojun/unsloth that referenced this pull request Sep 29, 2026
…nslothai#11248)

* setup.ps1: stop a stale-venv rebuild deleting the venv it runs from

`unsloth studio update` runs setup.ps1 from the managed venv's own python.exe.
When the torch flavor no longer matches the host (here: cu130 installed, an
AMD GPU now in the machine, so rocm required), the direct-update branch did
Remove-Item -Recurse on that venv. Windows will not delete a running image, so
the delete emptied Lib\ and failed on Scripts\python.exe, leaving a venv with
no unsloth_cli and no rollback copy; the desktop's update and repair both start
from that interpreter, so neither could recover it.

setup.ps1 now knows when it runs from inside the venv (the CLI names its
interpreter as UNSLOTH_SETUP_HOST_PYTHON; a bounded Win32_Process walk covers
an older CLI) and takes the in-place PyTorch reinstall install.ps1 already uses
for the same situation. A rebuild that does run renames the venv aside first,
so a lock fails whole instead of after deleting most of the tree.

* setup.ps1: order the in-place route last, and make the venv probe separator-correct

The new direct-update escape sat ahead of the nvidia-smi cu* preservation guard. Its
condition is true for every stale direct update, because the desktop always runs setup
from the venv's own python.exe, so it consumed $shouldRebuild before the narrower guard
was tested and that guard could never fire.

That guard does two things: it keeps the venv, and it publishes
$script:PreservedInstallerTorchTag, which is what holds the index selection on the cu*
arm. Shadowed, the tag stayed null while the in-place route set
$script:PinChangedForceReinstall, and the pair reached the CPU arm. Replaying the
shipped ladder over 320 enumerated cells, base and head agree on 289; the one cell that
is neither an intended fix nor a match is an unpinned direct update with a cu128 venv
and a silent nvidia-smi:

  base: uv pip install torch torchvision torchaudio --index-url .../whl/cu128
  head: uv pip install torch torchvision torchaudio --force-reinstall --index-url .../whl/cpu

which is the CPU-only update unslothai#9857 added that guard to stop. Moving the block below the
guard leaves all 30 intended fixes and restores that cell; base and fixed now differ in
0 cells where the venv is kept on both sides.

Get-SetupHostInterpreterInVenv built its containment prefix with a literal backslash.
.NET returns '/'-separated paths from GetFullPath off Windows and treats '\' as an
ordinary filename character, so the prefix matched nothing and the helper answered null
for every input. Only Windows runs setup.ps1 for real, but the shipped pwsh tests run
everywhere, and test_the_cli_hint_names_the_venv_interpreter was red on every non-Windows
runner while its sibling passed vacuously. Build the prefix from
DirectorySeparatorChar instead.

Also move the stale-venv sweep out of the rebuild branch, so an install that renamed a
venv aside, failed to delete the copy under a lock, and thereafter only ever repairs in
place still collects it, and give the destination a pid suffix so two rebuilds inside
one second cannot collide on a name.

* setup.ps1: let the stale-venv sweep prove a directory is ours before deleting it

Moving the sweep out of the rebuild branch put it ahead of the custom-root ownership
guard, so that guard can no longer cover it, and "$_venvLeaf.stale-*" is a wildcard
rather than a proof of ownership: a user's own unsloth_studio.stale-backup matches it and
was deleted on an ordinary healthy update.

Validate the way install.ps1 already validates its own rollback sweep
(Test-StudioVenvRollbackMustBePreserved): refuse anything outside the generated
timestamp-PID shape, refuse reparse points, and spare a copy whose owning process is
still alive, which is a concurrent setup's rescue copy rather than our litter. Enumerate
with -Force too, so a leftover that picked up the hidden attribute is not skipped
forever by the sweep meant to collect it.

test_setup_ps1_stale_sweep_only_removes_its_own_litter runs the shipped sweep under pwsh
against real directories rather than reading it: an abandoned copy in the generated shape
goes, a stale-backup directory and a live owner's copy stay, and the live venv is never
touched. It fails on the unvalidated sweep with "a directory outside the generated name
shape must be left alone".

Routing is unchanged: replaying the ladder over the same 320 cells still gives 30 fixes,
0 violations and 0 newly wiped cells against base.

* studio.py: say that UNSLOTH_SETUP_HOST_PYTHON is a hint, not a promise

sys.executable is the managed venv's python.exe on the path that matters, where the
desktop spawns the managed CLI. It is not on the others: a pip-installed CLI, a repo
checkout and a staged run all put an interpreter here that lives nowhere near $VenvDir.

That is already safe, because setup.ps1 tests containment itself and a value outside the
venv reads as 'not inside', which keeps the pre-existing rebuild. The comment asserted
the guarantee as fact, which is the kind of thing that later justifies dropping the
containment test as redundant. Say which path it holds on and who checks.

* setup.ps1: read the stale-venv pid from an explicit Match, not $Matches

The sweep decided what to delete from a capture group it reached through $Matches after
a -notmatch. Which of -match and -notmatch populates $Matches, and on which result, is
version-sensitive in exactly the way unslothai#9857's empty-string-vs-null was, and a read that
comes back empty here feeds [int]::TryParse and skips the entry. Failing safe is the good
case; a wrong pid is not. Take the group off a [regex]::Match whose semantics do not
move between Windows PowerShell 5.1 and 7.x.

* Tighten the comments added by this change

Opening comment-reduction pass over this PR's own additions only, not the surrounding
file: 62 added comment lines to 43. Every surviving line names a mistake the next reader
would otherwise make, which is why the ordering rationale and the ownership rationale
keep a line each. AST-verified comment-only against b30af0c.

* Second comment sweep over this change's own additions

The in-place-route block restated the undeletable-running-image mechanism the function
header above it already gives, so it keeps only what is local to the decision: the issue
number, and that a hand-run checkout still rebuilds. setup.ps1 additions 32 comment lines
to 27. AST-verified comment-only against 7d0b1da.

* Make the stale-copy sweep prove ownership before it deletes

Three things found while simulating this PR, all in the new code rather than in what it replaced.

The sweep runs on every qualifying setup, including one that rebuilds nothing, and it runs ahead
of the custom-root guard. Its only authority for a recursive delete was a name, so a directory
named unsloth_studio.stale-<14 digits>-<pid> next to the venv was deleted on a run that otherwise
changed nothing, and also on a custom UNSLOTH_STUDIO_HOME whose venv the rebuild then refused to
touch for want of an Unsloth sentinel. Both are now refused: the guard predicate is hoisted so the
sweep asks the same ownership question the rebuild asks, and a candidate must carry pyvenv.cfg,
the studio-owned marker, or the new .unsloth-studio-stale marker that the rename drops into the
copy it moved. A copy too far gone to carry any of the three is named and left alone rather than
deleted blind. The marker is rewritten when the delete after the rename fails, so the litter that
branch announces is still litter the next run can identify.

Get-SetupHostInterpreterInVenv accepted a hint that named nothing. The hint is an inherited
environment variable and can outlive what it names, and a stale one pointing inside the venv would
route a venv that genuinely needs rebuilding into an in-place repair with no interpreter to
perform it. It must now name a file that is there. The parent walk also compares creation dates
before following ParentProcessId, which is what Microsoft's own Win32_Process guidance says to do
about reused process ids.

The rename destination took the timestamp and the pid but had no retry, while install.sh's
_start_studio_venv_replacement, which this mirrors, appends a numeric suffix until the name is
free. One process can reach this twice inside a second, and a copy it left earlier can still be on
disk because its delete failed. A taken name now takes a bounded suffix, and the sweep's shape
recognises it, or the copy it names could never be cleaned up.

Tests: the sweep test now drives the shipped sweep over six directories, including one that wears
the name and holds no environment and one whose name took a collision suffix; a new test refuses
an unclaimable custom root and then, as a negative control, sweeps the same tree once the owned
marker is present; the helper test adds a hint naming a deleted path, a directory, and Scripts
itself, with the real interpreter as its control.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

---------

Co-authored-by: Daniel Han <[email protected]>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants