Repository navigation
Studio: share one torch classification probe across the repair paths - #8779
Conversation
_ensure_cuda_torch, _ensure_xpu_torch, _ensure_rocm_torch and _ensure_cpu_torch each spawned their own `import torch` subprocess to derive the same handful of facts about the installed wheel, and the installer runs all four at both the post-base-requirements repair point and the final one. A Linux update therefore started up to nine interpreters just to classify torch: four repair paths at each of the two points, plus the torchao version probe. Route them all through one memoized probe returning (ran, importable, version, hip, cuda). pip_install() invalidates it, since a pip operation is the only thing here that can change what is installed, so a repair that swaps torch is still followed by a fresh classification. The timeout is the part that actually bit: each probe was bounded at 90s independently, so a stalled GPU driver (exactly the host these repair paths exist to rescue) could hang an update for many minutes before the first on-disk fallback ran. It is now one 90s wait per repair point. `ran` and `importable` stay distinct so every caller keeps its existing behaviour: a probe that could not run falls back to the on-disk classifier, while torch that is present but un-importable still forces the reinstall.
|
@codex review |
|
Codex Review: Didn't find any major issues. Can't wait for the next one! 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 review |
Same explanations, fewer lines. The four repair paths each restated the same 'un-importable means missing or broken' point, and the probe docstring retold the nine-interpreter story at length; each now makes its point once. Comments and docstrings only, AST-verified per file (3/3 code unchanged). 702 tests pass, ruff clean.
Matches the SPDX two-line form the other new files in this tree use.
|
@codex review |
The five probes this consolidated each read their subprocess with errors="replace". The shared one kept text=True and lost that, which decodes strictly, and UnicodeDecodeError is a ValueError, so one undecodable byte in torch's import chatter escapes the except (OSError, TimeoutExpired) below and takes the installer down instead of falling back to the on-disk classifier. That fallback exists for exactly the hosts that reach this code. Reachable wherever the console code page and the child's output disagree, which is the Windows case this repo already carries an encoding suite for. The regression test runs a real subprocess rather than a mock, since which decoder was used is invisible to a mock. Reverting the one-line fix fails it with the UnicodeDecodeError.
|
Reviewed the parts flagged as unit-test-only and found one real regression, fixed in The shared probe lost the replacing decoderThe five probes this consolidated each read their subprocess with So one undecodable byte in torch import chatter takes the installer down rather than falling back to the on-disk classifier, and that fallback exists for exactly the hosts this code runs on. Reachable wherever the console code page and the child output disagree, which is the Windows case this repo already carries a whole encoding suite for. One line, plus a regression test that runs a real subprocess rather than a mock, since which decoder was used is invisible to a mock. Reverting the fix fails it with the Everything else in the refactor checks out
Test failures
|
|
Went back over this before merging and found two problems the tests do not cover. Both are introduced by this PR. 1. The shared probe can raise instead of falling backThe four per-site probes this replaces read bytes and decoded with The probe's own comment ("torch and its dependencies can chatter on import") names where the stray byte comes from: a driver banner, a Fix is 2.
|
| line | what runs |
|---|---|
| 4481-4484 | _ensure_cuda_torch / _ensure_rocm_torch / _ensure_xpu_torch / _ensure_cpu_torch |
| 4566-4567 | _probe_installed_torch_version() then _select_torchao_spec(...) |
| 4695-4698 | the four repair paths again |
On Windows ROCm the memo still holds the pre-install classification when torchao is pinned at 4566, so the spec is chosen for the torch that was just replaced. _ensure_cpu_torch at 4484 reads the same stale answer two lines after the install. Before this PR each of those was a fresh subprocess and saw the new torch.
The reasoning in the description is right, the coverage is not: there are two pip entry points and only one clears the memo. Simplest fix is to invalidate in pip_install_try as well.
The rest checks out
I went through the other claims rather than assuming they held:
- the
(ran, importable, ...)split does preserve each call site's behaviour, including the XPU inconclusive versus unreadable distinction - the marker,
+cuXXXtag, release, runtime family, XPU range and CPU GPU-build derivations are faithful ports of the inline scripts - the
test_untagged_cuda_build_is_left_alonechange is right._marker == "cuda"holds only whentorch.version.cudais set, which always yields a runtime family, so the old test asserted on a stdout line the subprocess could not emit
The five touched test files pass locally: 702 passed, 1 skipped.
Three fixes from simulating the shared probe against the pre-probe installer over [Linux, WSL, macOS, Windows] x [NVIDIA, AMD, Intel, CPU] x 23 installed-torch states, plus one memo-invalidation gap. All four are behaviour the per-path probes had and this one had lost. torch.version is reached through getattr now. A torch without that module made the child exit non-zero, which reads as "torch cannot import" and force-reinstalls a working venv. The old version probe only touched torch.__version__ and answered fine. The answer is printed behind a marker and parsed by that marker. "Last non-empty line" is only correct while nothing chatters AFTER the answer, and an atexit handler or a CUDA teardown notice does exactly that. version is None when no marked line came back, distinct from "" for an empty __version__. The XPU and CPU guards keyed off the empty string, so a venv with an unreadable version silently stopped being repaired where it used to be. pip_install_try() clears the memo too. It installs the Windows AMD ROCm trio, so "only pip_install changes what is installed" was not true, and a stale classification could answer for the previous build. Tests: the mocked probe stdout in test_cuda_repair.py and test_rocm_support.py carries the marker, and test_torch_probe_memoization.py gains the marker cases plus a real-subprocess one for the missing torch.version module, since that path crashes the installer rather than misrouting it.
|
Simulated this one against the pre-probe installer before trusting it, because the claim is "nine The harnessOne uv venv with no torch, a real stub 1089 cases: [Linux, WSL, macOS, Windows] x [NVIDIA, AMD, Intel, CPU] x 23 installed-torch states x {no pin, CUDA pin, XPU pin, CPU pin}, plus the wedged-driver paths driven with a really hanging The torch states cover cu118 through cu130, tagged and untagged, rocm6.3 / rocm7.2 / rocmsdk / ROCm flagged by version string only, +xpu in and out of the supported range, CPU tagged and untagged, macOS arm64, a torch that raises on import, one that segfaults, one that is absent, one with no What it foundFour divergences from the pre-probe behaviour, all now fixed in e0b6904:
The decode fix in c748445 came out of the same run: the pre-probe repair paths read bytes and decoded with After the fixes1089/1089 identical decisions, with two deliberate exceptions, each pinned against a twin scenario describing the same wheel without the awkwardness so that "better" cannot quietly mean "different":
Repo suites
Not coveredReal AMD, Intel and Windows hardware. The simulation drives those code paths, but it stubs what the host reports rather than asking a real driver, so the ROCm and XPU branches are still worth a human read. |
|
@codex review |
|
Codex Review: Didn't find any major issues. 🚀 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". |
Two things the hardening pass left behind. The old "last non-empty line" parser is still sitting after the return in _probe_torch_runtime, unreachable. Removed; asserted by a test so a future in-place replacement cannot leave one again. More importantly, nothing checked the part of this PR most able to be quietly wrong. Moving the five probes out of subprocess `-c` strings and into ordinary Python is meant to be a translation, but every existing test feeds the repair paths a MOCKED probe answer, so they exercise the new derivation only and would pass just as happily if it disagreed with the old one. test_torch_probe_classification_parity.py compares the two directly. The old expressions are reproduced verbatim from the merge base as reference implementations, cited by line. The new derivations are pulled out of the live module with ast rather than copied, so they cannot drift from what ships, and a rename fails extraction loudly instead of silently passing. 27 torch states, covering cu118 through cu130 tagged and untagged, rocm by hip and by version string, rocmsdk, +xpu in and out of range, CPU, empty, and hip plus cuda both set. Mutation-tested rather than assumed, since a parity test that cannot fail is worse than none. Dropping the rocm check from the CUDA marker, widening the XPU bound, dropping .lower() from the CPU predicate or the ROCm marker, and swapping the hip/cuda fields in the probe are each caught. The .lower() mutations initially passed. The matrix had no state where a substring test was the deciding factor, so the uppercase rows are there to make case actually matter rather than for completeness.
|
@codex review |
|
Worth being precise about this, because "de-duplication" is true of most of the diff and not true of the part that matters. What is de-duplicationThe classification logic. Before this, each of the nine call sites ran its own What is notThe memoization is a real semantic change, not a rewrite of the same thing. The probe result is cached for the life of the process, so torch is imported twice rather than nine times in a full install path. If torch changed underneath us between two call sites, the old code would see the new state and this code would not. That is why So: the derivations are pure de-duplication, the probe lifecycle is not, and it is the lifecycle that needed the review. Five real bugs turned up in it, all fixed in this branch and all listed in the comments above. The AST test you asked for
It does not re-implement the new logic. It pulls the live assignments and Matrix is 27 torch states across the four families, including the ones that only exist because a real build labels them that way: Verified the test itself by mutation rather than trusting that it passes. Five deliberate breaks introduced into the live source one at a time:
The first one escaped on the first attempt. No state in the matrix had a substring test as the deciding factor, so uppercase rows were added and it is caught now. Mentioning it because it is the reason to trust the other four. Separately, What this does not coverThe parity test proves the derivations agree with the old ones for a given probe result. It does not prove the probe result itself is right on hardware I do not have. ROCm, XPU and Windows are exercised only through synthetic probe output here. If anyone has a ROCm or Arc box, the install path is the thing worth a real run before merge. |
|
Codex Review: Didn't find any major issues. What shall we delve into next? 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". |
|
The four red checks here are not from this PR:
This PR only shares one memoized |
main gained the shared torch classification (unslothai#8779). It rewrote the same Linux ROCm block this branch moved into _linux_rocm_torch_plan(), so the two conflict textually while wanting the same thing. Kept this branch's plan structure and carried unslothai#8779 into it rather than either side wholesale: - _probe_rocm_torch() reads _probe_torch_runtime() instead of spawning its own interpreter. Its four values are a subset of the shared five, and a private probe would restore both the extra "import torch" and the extra independent 90s timeout on exactly the wedged-driver host this path exists to rescue. - The classification parity guard from unslothai#8779 fired on the move, which is what it is for. Re-checked the equivalence against the same reference implementation and retargeted it at _probe_rocm_torch, where the derivation now lives, rather than assuming it across the rename. - The fast-path source guard now asserts the bounded import where it moved to, and additionally fails if the fast path ever spawns its own subprocess again. - Probe mocks feed the shared marked line and drop the memo first. tests/studio/install: 2687 passed, 2 skipped. Both retargeted guards were mutation-tested: breaking the marker derivation fails 4 parity cases, and reintroducing a private subprocess fails 3 reconciliation cases.
…llers (#8795) * Studio tests: pin the torch probe invalidation contract to both installers #8779 made pip_install_try() drop the memoized torch classification, because it installs the Windows AMD ROCm trio and a memo it does not clear can answer for the build it just replaced. That fix shipped with no test: only pip_install() was covered, so reverting the pip_install_try() line kept the suite green. Three tests, each of which fails with that line removed: - pip_install_try() drops the memo, mirroring the pip_install() case - a real reinstall is really reclassified: two real torch packages on disk and a real probe subprocess either side of a real call into each installer, so the answer that replaces the memo is shown to come from the venv as it is now rather than from the mock that dropped it - every function that builds a pip or uv install command invalidates. Read out of the module with ast rather than listed here, so a third installer helper cannot be added without either invalidating or failing this test No production change. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Pin the torchao consumer to the reinstalled torch as well Folds in the one test #8796 had that this branch did not. The other two there duplicate what is already here, so #8796 closes in favour of this. _select_torchao_spec reads _probe_installed_torch_version() between the two repair points, which makes it the consumer that would actually read a memo left over from before a reinstall, and pin torchao against the torch that was just replaced. The existing cases assert on _probe_torch_runtime directly; this one goes through the accessor that the torchao path really calls. Fails with the _invalidate_torch_runtime_probe() line removed from pip_install_try, along with the three siblings, and passes with it. --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: danielhanchen <[email protected]>
Summary
_ensure_cuda_torch,_ensure_xpu_torch,_ensure_rocm_torchand_ensure_cpu_torcheach spawned their ownimport torchsubprocess to work out the same handful of facts about the installed wheel. The installer calls all four back to back at two separate repair points (after the base requirements, and again in the final repair pass), so a single Linux update started up to nine interpreters purely to classify torch: four repair paths at each of the two points, plus the torchao version probe.They all route through one memoized probe now.
What the probe returns
(ran, importable, version, hip, cuda), which covers everything the seven call sites were deriving individually:_probe_installed_torch_versiontorch.__version___installed_torch_is_windows_rocmrocmin the version_ensure_cuda_torch+cuXXXtag, release, runtime family_ensure_xpu_torch+xpuand the supported range_ensure_cpu_torch_ensure_rocm_torch(three of them)Timeout behaviour
This is the part that actually bit. Each probe was bounded at 90s independently, so a stalled GPU driver could hang an update for many minutes before the first on-disk fallback ran, and that is exactly the host these repair paths exist to rescue. It is now one 90s wait per repair point.
ranandimportableare kept distinct so no caller changes behaviour:ran = False(OSError or timeout) means fall back to the on-disk classifier, as beforeran = True, importable = Falseis the "installed but broken" signal that still forces the reinstallCache invalidation
pip_install()clears it. A pip operation is the only thing in this file that can change what is installed, so a repair that swaps torch is still followed by a fresh classification. The two repair points probe once each rather than sharing one stale answer.Cost
Measured locally, one
import torchis 4.5s and 610MB resident. Nine of those per update is the thing worth removing.Tests
New
tests/studio/install/test_torch_probe_memoization.pycovers parsing for CUDA, ROCm, CPU and untagged builds, import chatter on stdout, the timeout and OSError paths, one subprocess across repeated calls, no retry after a stall, and invalidation throughpip_install().Existing tests updated where they mocked the old per-probe wire formats:
test_cuda_repair.py: the mock renders a self-consistentversion|hip|cudaline from the same shorthand the tests already used, so the test bodies are unchangedtest_rocm_support.pyandtest_rocm_gfx_spoof_7331.py: probe stdout converted to the new field order, plus an autouse fixture resetting the memo between teststest_xpu_triton_swap.py: the source-text assertions follow the new structure, and the CPU predicate is still pulled out of the module source rather than copied into the testOne behavioural note worth a look during review.
test_untagged_cuda_build_is_left_aloneasserted that an untagged CUDA build is skipped, but that relied on a state the probe cannot produce:_marker == "cuda"meanstorch.version.cudais set, which always yields a runtime family, so_span is Noneis unreachable on that branch. The test now asserts the reachable behaviour, that the runtime family drives the architecture policy, and is renamed to match. The defensivereturnis left in place.Verification
tests/studio/andtests/python/pass apart from failures that are present onmainin this environment too, confirmed by stashing the branch and re-running:test_managed_node_runtime.py(3,UNSLOTH_STUDIO_HOMEpath assumptions),test_studio_text_descender_clipping.py(1), andtest_chat_thread_title_cas.py(8 errors).The ROCm, XPU and Windows paths are covered by unit test only. I do not have that hardware here, so those are the parts worth a closer read.