Skip to content

Studio: a CPU torch handover must not disarm the flavor invariant - #10906

Merged
danielhanchen merged 11 commits into
mainfrom
fix-cpu-handover-disarms-torch-flavor-invariant
Sep 14, 2026
Merged

danielhanchen merged 11 commits into
mainfrom
fix-cpu-handover-disarms-torch-flavor-invariant

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Sep 14, 2026 •

Copy link
Copy Markdown
Member

Problem

Several Windows users have reported that an in-app update takes their GPU away. The shape is always the same: inference was using the GPU, they update, and afterwards everything runs on CPU. Re-running install.ps1 fixes it, and the next update breaks it again.

llama.cpp is not the thing that gets downgraded. On an affected machine UNSLOTH_PREBUILT_INFO.json still reads the correct CUDA bundle throughout:

release_tag     : b10472-mix-4b653db
asset           : app-b10472-mix-4b653db-windows-x64-cuda12-older.zip
backend         : cuda
backend_request : auto
runtime_line    : cuda12

What actually changed is the managed venv:

torch.__version__ torch.version.cuda torch.cuda.is_available() torch.cuda.device_count()
2.11.0+cpu        None               False                     0

llama-server --list-devices then reports Available devices: (none). The Windows CUDA bundle does not ship cudart64_*.dll / cublas64_*.dll and the release carries no cudart-* asset, so _windows_pip_nvidia_dll_dirs sources them from the venv's torch/lib and nvidia/* wheels. A +cpu venv has neither, the CUDA ggml backend cannot load, and it enumerates nothing.

Why the existing invariant did not catch it

_ensure_expected_torch_flavor (step 13w) exists precisely for this. It was not reverted and it is still wired into the Windows branch. It just never gets as far as reading the wheel:

  1. setup.ps1:5297 picks the wheel index from $CuTag, which is cpu whenever the nvidia probe returns nothing. setup.ps1:5561-5571 then publishes UNSLOTH_EXPECTED_TORCH_TAG = "cpu".
  2. _expected_torch_flavor_tag() takes the handover first, ahead of the manifest, so a venv recorded as cu128 resolves to cpu.
  3. The guard below then returns pass, because _explicit_cpu_torch_index_pin() only looks at the user's UNSLOTH_TORCH_INDEX_URL and knows nothing about where the tag came from:
_cpu_pinned = expected == "cpu" and _explicit_cpu_torch_index_pin()
if not (_is_cuda_family_leaf(expected) or expected in ("xpu", "rocm") or _cpu_pinned):
    return True

So the install reports success and nothing warns. The guard cannot tell "the user asked for CPU" from "the GPU probe failed", because both produce expected == "cpu".

Fix

Treat a cpu handover as the probe's answer rather than a stated choice. When the handover says cpu, there is no explicit pin, the manifest records a CUDA family, and an NVIDIA GPU is still present, the invariant runs instead of skipping.

Both facts have to hold. Requiring only the manifest would reinstall a CUDA wheel onto a machine whose GPU has genuinely been removed, which is worse than leaving it on CPU.

Which CUDA family gets installed comes from the driver, not from the manifest. Get-PytorchCudaTag returns cpu for two different reasons: an empty nvidia-smi probe, and a driver that genuinely tops out below CUDA 11 or gets lowered by Get-CudaFamilyCappedForPreTuring. Reinstating the recorded cu128 in the second case would install a wheel the driver cannot load. _driver_cuda_torch_flavor_tag() reads the leaf of _detect_cuda_torch_index_url(), which mirrors Get-PytorchCudaTag (ancient-driver cpu and pre-Turing cap included), and that family is what gets enforced. No usable family means the CPU handover stands untouched. The manifest keeps the job it is good for, establishing that this venv is meant to be CUDA; it does not get to pick which CUDA.

Both probes look for nvidia-smi in the same places. _has_usable_nvidia_gpu already walked the ProgramFiles\NVIDIA Corporation\NVSMI and System32 candidates, because nvidia-smi.exe is routinely off PATH on Windows, while _nvidia_smi_path was shutil.which plus /usr/bin. A host in that state answered "GPU present" and then fell through to the cu126 default when asked which family, which on Blackwell is a wheel with no supported kernels. One _nvidia_smi_candidates() helper now backs both, which also fixes the pre-Turing SM-coverage check that reads the same path.

Looking in the same places is not enough on its own: the two also have to CHOOSE the same way. _has_usable_nvidia_gpu walks candidates until one answers, so a stale nvidia-smi on PATH does not stop it, while the family probe stopped at the first candidate that merely existed and read no version from it. _detect_cuda_torch_index_url now walks the candidates itself and returns on the first that exits 0 with a parseable CUDA Version:, applying the pre-Turing cap against the one that actually answered. A shutil.which result is kept without an os.path.isfile check, since which has already proved it runnable and gating it rejects a bare nvidia-smi on any host without /usr/bin/nvidia-smi.

An explicit index pin still outranks everything. A CPU pin means a deliberate CPU install is untouched, and a CUDA pin outranks the driver probe too, since the repair helpers install from the pinned URL and expecting anything else would flag a venv they had just built correctly.

This is resolved inside _expected_torch_flavor_tag() rather than inside the invariant, so the caller records the enforced tag as well. Overriding only the invariant's local copy repaired the venv and then wrote cpu to the manifest, leaving the next update with no CUDA record to fire on: a one-shot fix.

The handover is read in three places, so it now goes through one _handover_torch_flavor_tag() helper. An inline read drifting out of step with the others is how this class of bug returns.

Before and after

Same mocked venv throughout: installed wheel 2.11.0+cpu, manifest records cu128.

scenario before after
update, empty nvidia-smi probe pass, wheel never read, silent repair runs
repair could not fix the wheel pass install fails
handover cu128, probe found the GPU repair runs unchanged
user pinned the CPU index pass unchanged
cpu handover, nothing recorded pass unchanged
cpu handover, cu128 recorded, GPU really gone pass unchanged
cu128 recorded, driver too old for any CUDA wheel pass unchanged, handover stands
cu128 recorded, driver reports CUDA 12.4 pass repairs to cu124, not cu128
cu128 index pinned, driver reports 12.6 pass enforces cu128, the pin

Only the first two and the second-to-last rows move; the rest are the ones that make this safe to ship.

A 6302-case matrix over OS x installed wheel x handover x manifest record x index pin x UNSLOTH_TORCH_BACKEND x NVIDIA-present moves exactly 48 cases, every one of them a cpu handover with a CUDA record on a host that still has its GPU. No CPU-pinned case, no nvidia=False case and no NO_TORCH case moves, and no moved case leaves a +cpu wheel on an NVIDIA host.

The first row is the reported bug, and before this change it printed nothing at all. After it, the existing guidance fires:

[WARN] the installer handed over a CPU torch expectation, but this venv was recorded as
       cu128 and an NVIDIA GPU is still present; enforcing cu128.
PyTorch flavor mismatch (installed cpu, need cu128) -- reinstalling correct build...

Tests

TestACpuHandoverDoesNotDisarmTheInvariant in tests/studio/install/test_cuda_repair.py covers every row above through the existing _run_flavor_invariant harness, plus a structural check that the three handover reads stay behind the one helper, a check that the enforced tag reaches _recordable_torch_flavor_tag and not just the invariant, and a check that the driver-family helper maps an ancient-driver .../cpu URL to "" rather than to a family named cpu.

One existing case had to stop pairing a 12.4 driver with a cu128 record, which was only self-consistent while the record picked the family.

One existing assertion in TestTheWindowsXpuTritonSwapReachesADirectRun pinned the literal inline read in _ensure_xpu_triton; it now asserts the helper call. Its intent, that the swap stays setup.ps1's job under setup.ps1, is unchanged.

tests/studio/install/ plus studio/backend/tests/test_install_resolve_prebuilt.py: 4704 passed, 19 skipped, after merging main. tests/sh/test_setup_staged_root.sh: 36 passed.

Scope

Windows update path only. No GPU and no Windows machine is needed to run the tests; everything is mocked.

setup.ps1 publishes UNSLOTH_EXPECTED_TORCH_TAG=cpu whenever its nvidia-smi probe
comes back empty. _ensure_expected_torch_flavor returned pass on that tag without
ever reading the installed wheel, so 'unsloth studio update' reported a venv
rebuilt as 2.11.0+cpu as a successful install.

The handover is the probe's answer, not a stated choice, so it no longer outranks
the flavor the last completed install recorded. When the manifest names a CUDA
family and an NVIDIA GPU is still present, that wins and the repair runs. An
explicit index pin still wins over both, and a host whose GPU has genuinely gone
is still left alone.

Reads of the handover now go through _handover_torch_flavor_tag().
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 14, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-09-14T13:05:44.562391Z 3f6bd5e Manual request
🔒 Security Review ✅ Completed 2026-09-14T05:21:56.321895Z 2baec73 PR opened
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 2baec73ce9

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

Comment thread studio/install_python_stack.py Outdated
f"was recorded as {_recorded} and an NVIDIA GPU is still present; "
f"enforcing {_recorded}."
)
expected = _recorded

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Carry the enforced CUDA tag into the manifest

When this override fires, it changes only the function-local expected; the caller's torch_flavor_tag remains "cpu" (lines 8055-8056) and is later passed to write_manifest (line 8236). Thus the repaired CUDA venv is immediately recorded as CPU. On the next update where setup again hands over CPU, _RECORDED_TORCH_TAG is no longer CUDA, this branch does not run, and the dependency pass can leave the venv on CPU again. Return or otherwise propagate the effective _recorded tag so the completion manifest preserves the invariant across updates.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Correct, and this made the fix a one-shot. The override only replaced the invariant's local copy of expected, so the caller still held torch_flavor_tag = "cpu" and _recordable_torch_flavor_tag(torch_flavor_tag) wrote cpu into the manifest. The venv got repaired, the record did not, and the next update had no CUDA tag left to defend.

Moved the resolution up into _expected_torch_flavor_tag() so the enforced tag is what both the invariant and the manifest writer see. Added two tests: test_the_enforced_tag_reaches_the_manifest asserts _expected_torch_flavor_tag() == "cu128" and _recordable_torch_flavor_tag(resolved) == "cu128" in the bug case, and test_a_host_that_lost_its_gpu_records_cpu pins that a host which genuinely has no NVIDIA GPU still records cpu.

@danielhanchen

Copy link
Copy Markdown
Member Author

For context, this is one of three separate paths that can leave a GPU machine running on CPU. They are independent and can land in any order:

Two things I checked and ruled out while tracing this, recorded here so nobody re-treads them:

The jump in CPU asset downloads on the llama.cpp fork around 2026-07-08 (CPU share 13.3% to 45.0% between b9899-mix-5dd3721 and b9909-mix-53618c5, published the same day) is a measurement artifact, not a regression. #6311 merged 8 minutes after b9909 went live and re-routed CPU-only hosts from ggml-org/llama.cpp to the fork, so CPU traffic moved into the repo being measured. CUDA counts rose across that boundary rather than falling.

The stricter Windows runtime-payload gate from #10404 does not fire. I listed both b10909 Windows CUDA bundles against runtime_payload_health_groups("windows-cuda") and every required group is present; the cudart trio is only required when a paired runtime archive exists, and that release publishes none.

Verified selection is correct at v0.1.804-beta, v0.1.808-beta and main on Colab T4, L4, A100 and G4 (RTX PRO 6000 Blackwell), Kaggle 2x T4, and gfx1151 Linux, so none of this affects Linux NVIDIA asset selection.

@danielhanchen

Copy link
Copy Markdown
Member Author

Simulation results

I ran the full cartesian product of every input that decides whether this invariant runs, base against head: installed wheel x setup-script handover x manifest record x explicit index pin x UNSLOTH_TORCH_BACKEND x NVIDIA present x OS. 6302 cases, fully mocked, no GPU and no Windows machine involved.

48 of 6302 cases change, and every one of them has the same signature:

field value in every changed case
handover exactly cpu
manifest record cu124 or cu128
NVIDIA present always True
UNSLOTH_TORCH_BACKEND only "" or cuda
explicit index pin never the CPU index

Asserted over the diff, all passing:

  • no change when the manifest recorded nothing, cpu, or rocm
  • no change without an NVIDIA GPU
  • no change unless the handover is exactly cpu
  • no change when the user pinned the CPU index
  • no change for a rocm / xpu / cpu UNSLOTH_TORCH_BACKEND, because the existing _TORCH_BACKEND != expected guard below still catches those
  • NO_TORCH stays inert
  • nothing raises on either side
  • no case goes fail to pass, so this can only turn a silent pass into a loud repair or failure, never mask a real breakage

Transitions: 32 pass to fail (the repair now runs and the unrepairable case now fails the install), 16 pass to pass (the wheel was already correct; the only difference is that it got probed).

Reachability

The handover is published by setup.ps1 only. Neither setup.sh nor install.sh sets UNSLOTH_EXPECTED_TORCH_TAG, and the call site is:

# 13w. Windows torch flavor invariant
if IS_WINDOWS and not NO_TORCH:

So the Linux and macOS rows in the grid above are unreachable in production and are there only to prove the change is inert on them. Nothing outside the Windows update path can reach the new branch.

There is also a second, independent brake I had not relied on: _has_usable_nvidia_gpu() itself returns False when CUDA_VISIBLE_DEVICES is "" or -1, so a masked Windows host is not force-repaired onto CUDA either.

Existing installs

A venv installed before the flavor was recorded has an empty _RECORDED_TORCH_TAG, so it is untouched. That is in the assertions above ("no change when the manifest recorded nothing"). It is also the one limitation worth stating plainly: this repairs hosts whose manifest names a CUDA family, and a pre-recording install will still need one install.ps1 run to get a record before the invariant can defend it.

Premise check

The root cause depends on PyPI's Windows torch being CPU-only, which is by design rather than an accident: PyTorch publishes CPU-only wheels to PyPI for Windows and macOS and GPU wheels only for Linux, because PEP 440 has no way to express a compute backend, so +cu128 builds live on the separate download.pytorch.org/whl/cu128 index and need --index-url. The dependency steps on the update path install with no --index-url, so they resolve 2.11.0+cpu.

Sources: torch on PyPI, PyTorch previous versions and index URLs, uv's PyTorch integration guide on the local-specifier scheme

Scope

No frontend, TypeScript, Rust, src-tauri or Playwright file is touched by this PR, so there is no browser surface to test. tests/studio/install/: 4037 passed, 6 skipped.

danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 14, 2026
…nvariant

The CPU-handover override only replaced `_ensure_expected_torch_flavor`'s local
copy of `expected`, so the caller still held `torch_flavor_tag = "cpu"` and
`_recordable_torch_flavor_tag(torch_flavor_tag)` wrote "cpu" into the manifest.
The venv got repaired and the record did not, which left the next update with no
CUDA tag to defend and made the whole fix a one-shot.

Resolve it inside `_expected_torch_flavor_tag()` instead, so the enforced tag is
what both the invariant and the manifest writer see. Two tests:
`test_the_enforced_tag_reaches_the_manifest` pins cu128 through
`_recordable_torch_flavor_tag` in the bug case, and
`test_a_host_that_lost_its_gpu_records_cpu` pins that a host which genuinely has
no NVIDIA GPU still records cpu.
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 14, 2026
Comment-only pass over what this branch adds. Measured numbers and the mechanism
write-ups move to the PR description, where they belong; what stays is the
invariants the code does not state on its own.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex security review

danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 14, 2026

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 4de47c523c

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

# tag too, instead of repairing the venv and then writing "cpu" to the manifest.
if env == "cpu" and not _explicit_cpu_torch_index_pin():
recorded = (_RECORDED_TORCH_TAG or "").strip().lower()
if _is_cuda_family_leaf(recorded) and _has_usable_nvidia_gpu():

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve CPU selection for unsupported NVIDIA drivers

When an NVIDIA GPU is still listed but its driver reports a maximum CUDA version below 11—for example after a driver downgrade—setup.ps1::Get-PytorchCudaTag deliberately selects cpu, while _has_usable_nvidia_gpu() only verifies that nvidia-smi -L lists a GPU. With a prior cu* manifest, this condition therefore replaces the fresh CPU handover with the old CUDA tag and reinstalls a wheel that the current driver cannot use. Require the current CUDA-family detection to yield a supported cu* family, rather than relying only on GPU presence, before overriding the CPU handover.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Correct. Get-PytorchCudaTag has an explicit else { return "cpu" } below CUDA 11, and Get-CudaFamilyCappedForPreTuring can lower the family on top of that, so a CPU handover is sometimes a statement rather than an empty probe. _has_usable_nvidia_gpu() cannot tell the two apart, and reinstating the recorded cu128 there installs a wheel the driver cannot load.

Rather than only gating the override, the enforced tag now comes from the driver instead of from the record. _driver_cuda_torch_flavor_tag() reads the leaf of _detect_cuda_torch_index_url(), which is the Python mirror of Get-PytorchCudaTag, ancient-driver cpu and pre-Turing cap included, so it answers the same question the handover did. No usable family means the CPU handover stands untouched. The record keeps the job it is good for, which is establishing that this venv is meant to be CUDA; it no longer gets to pick which CUDA.

One extra case fell out of this: an explicit CUDA index pin has to outrank the probe, because the repair helpers install from the pinned URL and expecting the driver family instead would flag a venv they had just built correctly.

Four tests: an ancient driver keeps the handover, a downgraded driver gets its own family (unit and end to end), a cu128 pin beats a cu126 driver, and the helper maps an ancient-driver .../cpu URL to "" rather than to a family named cpu. One existing test also had to stop pairing a 12.4 driver with a cu128 record, which was only self-consistent while the record picked the family.

The 6302-case flavor matrix still moves exactly 48 cases, all of them a CPU handover with a CUDA record on a host that still has its GPU. No CPU-pinned case, no nvidia=False case and no NO_TORCH case moves.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 14, 2026
setup.ps1::Get-PytorchCudaTag returns "cpu" for two different reasons: an empty
nvidia-smi probe, and a driver that genuinely tops out below CUDA 11 or gets
lowered by Get-CudaFamilyCappedForPreTuring. The override treated both as the
first, so a driver downgrade would see the manifest's cu128 reinstated and a
wheel installed that the driver cannot load.

Read the family the driver can actually run, via _detect_cuda_torch_index_url,
which mirrors Get-PytorchCudaTag ancient-driver "cpu" and pre-Turing cap
included, and enforce THAT. No usable family means the CPU handover stands. An
explicit CUDA index pin outranks the probe, since the repair helpers install
from the pinned URL and expecting anything else would flag a venv they had just
built correctly.

Four tests: an ancient driver keeps the handover, a downgraded driver gets its
own family rather than the record (unit and end to end), an explicit cu128 pin
wins over a cu126 driver, and the helper maps an ancient-driver cpu URL to ""
rather than to a family called cpu.

tests/studio/install/: 4045 passed, 6 skipped.
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 14, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 976ffb4c48

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

_detect_cuda_torch_index_url mirrors setup.ps1::Get-PytorchCudaTag, ancient-driver "cpu"
and pre-Turing cap included, so reading its leaf asks the same question the handover did.
"""
leaf = _detect_cuda_torch_index_url().rstrip("/").rsplit("/", 1)[-1].strip().lower()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Probe the same Windows nvidia-smi paths before choosing CUDA

When setup hands over cpu after a transiently empty GPU probe and the later presence check rediscovers an NVIDIA GPU via the fixed ProgramFiles\NVIDIA Corporation\NVSMI or System32 paths, this helper derives the family through _detect_cuda_torch_index_url(), whose _nvidia_smi_path() checks only PATH and /usr/bin. On Windows systems where nvidia-smi.exe is off PATH (a case already handled by both setup.ps1 and _has_usable_nvidia_gpu()), it therefore defaults to cu126 instead of reading the driver. This can overwrite a cu128/cu130 environment and record cu126; on a Blackwell GPU that wheel has no supported kernels, yet the flavor verification accepts the matching tag. Reuse the fixed-location candidate probing when deriving the driver family.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Correct. _has_usable_nvidia_gpu already walks the ProgramFiles\NVIDIA Corporation\NVSMI and System32 candidates, with a comment saying why, while _nvidia_smi_path was shutil.which plus /usr/bin. So the presence check and the family probe were asking two different questions about the same host, and the second one fell through to its cu126 default.

Fixed by making them share one _nvidia_smi_candidates() helper, PATH first, then the Windows fixed locations or the Linux /usr/bin path. _nvidia_smi_path returns the first that exists. That also fixes the other caller, the pre-Turing SM-coverage check at _nvidia_compute_sms, which had the same blind spot.

Two tests: a Windows host whose only nvidia-smi.exe is under ProgramFiles now resolves through _nvidia_smi_path, and both probes are pinned to the shared helper by source inspection so they cannot drift apart again. Both fail on the previous commit.

On a non-Windows host the candidate list is unchanged, so nothing moves there.

_has_usable_nvidia_gpu already probed the Windows fixed locations that
install.ps1 and setup.ps1 use, because nvidia-smi.exe is routinely off PATH
there. _nvidia_smi_path, which _detect_cuda_torch_index_url reads, checked PATH
and /usr/bin only. So on such a host the presence check said "GPU present" while
the family probe fell back to its cu126 default, and the enforced tag recorded a
family the driver never reported. On Blackwell that wheel has no supported
kernels, and the flavor verification accepts the matching tag either way.

One _nvidia_smi_candidates() helper now backs both. Two callers that disagree
about where nvidia-smi lives disagree about the host.

Two tests: a Windows host with nvidia-smi.exe only under ProgramFiles resolves
through _nvidia_smi_path, and both probes are pinned to the shared helper. Both
fail on the previous commit.

tests/studio/install/ + test_install_resolve_prebuilt.py: 4351 passed, 7 skipped.
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 14, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 831da39d82

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

Comment thread studio/install_python_stack.py Outdated
Comment on lines +3119 to +3120
if os.path.isfile(candidate):
return candidate

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Continue past an unusable nvidia-smi candidate

When a stale nvidia-smi remains on PATH while the fixed Program Files/System32 copy works, _has_usable_nvidia_gpu() continues through the candidate list and confirms the GPU, but this helper returns the stale executable merely because the file exists. _detect_cuda_torch_index_url() then receives no driver version and defaults to cu126, so a direct run or recovered CPU handover can replace a cu128/cu130 environment with a wheel that has no kernels for a Blackwell GPU. Fresh evidence after the earlier path-probing comment is that the new shared helper unifies candidate enumeration but still does not select the candidate that successfully answers; continue until a candidate yields a usable driver response.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Correct, and it is the same bug one level down from the previous round: I unified where the two probes LOOK without unifying how they CHOOSE. _has_usable_nvidia_gpu walks candidates until one answers; _nvidia_smi_path stopped at the first that existed, so a stale nvidia-smi on PATH won and the family probe read no version.

_detect_cuda_torch_index_url now walks the candidates itself and returns on the first one that exits 0 and yields a parseable CUDA Version:, falling back to cu126 only when none do. The pre-Turing cap is applied against the candidate that actually answered, which it has to be.

test_the_family_probe_walks_past_a_stale_candidate stubs a PATH entry that exits 9 and a second candidate reporting CUDA 12.8, and asserts cu128.

Comment thread studio/install_python_stack.py Outdated
def _nvidia_smi_path() -> "str | None":
"""The first nvidia-smi that exists, or None."""
for candidate in _nvidia_smi_candidates():
if os.path.isfile(candidate):

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Preserve the executable supplied by shutil.which

This new isfile gate breaks the existing localized-banner regression test, which intentionally stubs shutil.which("nvidia-smi") to return the intercepted command name rather than creating that file in the working directory. Running python -m pytest -q tests/studio/install/test_cuda_repair.py -x now yields 235 passes followed by test_detect_index_url_reads_a_localized_nvidia_smi_banner failing because the helper skips the command and returns the cu126 fallback instead of cu130; either retain the previously trusted shutil.which result or update the test double as part of this change.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Correct, and my local run gave me a false pass: this box has a real /usr/bin/nvidia-smi reporting CUDA 13.1, so the isfile gate rejected the stubbed "nvidia-smi", fell through to the real binary, and the test got its cu130 from the host rather than from its own double. On a GPU-free runner there is nothing at /usr/bin/nvidia-smi, so the helper returns None and the family defaults to cu126.

Reproduced by hiding that path:

candidates: ["nvidia-smi", "/usr/bin/nvidia-smi"]
_nvidia_smi_path() -> None

shutil.which has already proved its result runnable, so it is now kept without an isfile check; only the fixed-location candidates are gated on existence. test_a_which_result_is_trusted_without_an_isfile_check pins that directly.

I also added a throwaway conftest that stubs os.path.isfile to hide /usr/bin/nvidia-smi, and re-ran the suite under it: 238 pass with the fix, and 2 fail without it. That is the environment difference that hid this from me the first time.

Two follow-ups to the shared candidate list, both the same mistake one level
down: I unified where the two probes LOOK without unifying how they CHOOSE.

_has_usable_nvidia_gpu walks candidates until one answers. _nvidia_smi_path
stopped at the first that merely existed, so a stale nvidia-smi on PATH won and
_detect_cuda_torch_index_url read no version and defaulted to cu126. On Blackwell
that wheel has no kernels. The family probe now walks the candidates itself and
returns on the first that exits 0 with a parseable CUDA Version, applying the
pre-Turing cap against the candidate that actually answered.

The isfile gate also rejected a bare "nvidia-smi" from shutil.which, which had
already proved it runnable. That broke the localized-banner test on any host
without /usr/bin/nvidia-smi. It passed for me only because this box has a real
one reporting CUDA 13.1, so the test read its cu130 off the host rather than off
its own double. Only the fixed-location candidates are gated on existence now.

Three tests: a which result is trusted without an isfile check, the family probe
walks past a candidate that exits non-zero, and the shared-helper chain is pinned
by source inspection. Verified under a conftest that hides /usr/bin/nvidia-smi,
the way a GPU-free runner sees it: 238 pass with the fix, 2 fail without it.

Merged origin/main: the branch was ~40 commits behind and CI was failing four
staged-root shell checks that pass on main and on the merge.

tests/studio/install/ + test_install_resolve_prebuilt.py: 4702 passed, 19
skipped. tests/sh/test_setup_staged_root.sh: 36 passed.
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 14, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 3f6bd5eb17

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

Comment on lines +3517 to +3519
m = re.search(r"CUDA(?: UMD)? Version:\s*(\d+)\.(\d+)", result.stdout)
if m is None:
continue

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Require the family candidate to list the GPU

When a stale nvidia-smi on PATH exits successfully and prints a parseable CUDA banner but its -L output contains no GPU, _has_usable_nvidia_gpu() rejects it and can confirm the GPU through the fixed Windows copy, while this loop accepts the stale candidate before reaching that copy. I checked setup.ps1's detection at lines 2347-2369, which retains the executable that actually passes Test-NvidiaSmiHasGpu; using a different candidate here can therefore select (for example) cu126 instead of the working copy's cu128/cu130, leaving Blackwell without supported kernels. Fresh evidence beyond the earlier stale-candidate report is that the new loop advances only on command/parse failure, not when the candidate failed the GPU-presence predicate; derive the family from the candidate that also lists a usable GPU.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Correct, and it is the third form of the same bug: round two fixed where the two probes LOOK, round three fixed which candidate they RUN, and this is what they ACCEPT. The loop advanced only on a command or parse failure, so a stale copy that exits 0 with a parseable banner and an empty -L still decided the family.

_lists_a_gpu is lifted out of _has_usable_nvidia_gpu to module scope as _nvidia_smi_lists_a_gpu and applied in both places, so the two cannot disagree about what counts as a working nvidia-smi. That matches setup.ps1 keeping whichever executable passes Test-NvidiaSmiHasGpu.

test_a_banner_without_a_gpu_does_not_decide_the_family builds your case exactly: a PATH candidate that exits 0 reporting CUDA Version: 12.6 with an empty -L, and a second candidate reporting 13.1 with a GPU listed. It asserts cu130, and fails on the previous commit. test_both_probes_share_the_gpu_presence_predicate pins the shared predicate by source inspection.

The two subprocess doubles in the suite had to learn to answer -L, which they now do off cuda_version: a driver that reports a CUDA version has a GPU to report it for.

The candidate loop advanced only on a command or parse failure, not on the
GPU-presence predicate. A stale nvidia-smi that exits 0 and prints a perfectly
parseable CUDA banner while -L enumerates nothing therefore decided the family,
even though _has_usable_nvidia_gpu rejects exactly that copy and walks on to the
working one, and setup.ps1 keeps whichever executable passes
Test-NvidiaSmiHasGpu. The family then came off the wrong driver.

_lists_a_gpu is lifted out of _has_usable_nvidia_gpu as _nvidia_smi_lists_a_gpu
and applied in both places, so the two cannot disagree about what counts as a
working nvidia-smi. That is the third form of this same bug: first where they
look, then which one they run, now what they accept.

Two tests: a stale copy reporting CUDA 12.6 with an empty -L does not win over a
working copy reporting 13.1, and both probes are pinned to the shared predicate.
Both fail on the previous commit. The two subprocess doubles in the suite now
answer -L, which they have to for any test that reaches the family probe.

tests/studio/install/ + test_install_resolve_prebuilt.py: 4704 passed, 19
skipped. tests/sh/test_setup_staged_root.sh: 36 passed.
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 14, 2026
Both caught by CI, not by me, because I had been running tests/studio/install/
rather than tests/studio/, and because this box has a real nvidia-smi.

test_xpu_triton_swap execs a SLICE of install_python_stack into a hand-built
namespace. _ensure_xpu_triton now reads the handover through
_handover_torch_flavor_tag instead of inline, which is not in that namespace, so
both platform-guard tests died with NameError at call time. The helper is
provided with the same semantics as the real one.

The localized-banner double answers --query-gpu=compute_cap and otherwise prints
the banner. The family probe now also runs -L, which that fallback answers with
a banner listing no GPU, so the candidate was skipped. It passed here only
because this host has a real /usr/bin/nvidia-smi to fall through to, reporting
CUDA 13.1: the test was reading its cu130 off the host rather than off its own
double, which is the exact trap that hid the earlier regression. It now has a -L
arm.

Re-ran the whole of tests/studio/ under a conftest that hides
/usr/bin/nvidia-smi, the way a GPU-free runner sees it: 11154 passed, 77
skipped. The one remaining failure,
test_pr10648_offline_and_status::test_the_pr_only_added_new_arms_to_the_setup_status_blocks,
reproduces on a clean checkout of main with no PR applied: its guard asserts
"step " is absent from removed diff lines, and a substep line added elsewhere
contains that substring.
@danielhanchen
danielhanchen merged commit 24f0627 into main Sep 14, 2026
59 checks passed
@danielhanchen
danielhanchen deleted the fix-cpu-handover-disarms-torch-flavor-invariant branch September 14, 2026 16:37
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants