Repository navigation
Studio: verify the flash-attn import after installing it - #8465
Conversation
|
Codex Review: Didn't find any major issues. Bravo. 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: 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". |
|
Codex Review: Didn't find any major issues. Swish! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
worker.py imports six utils.* submodules and calls activate_native_tls() at import time; _load_worker_module stubbed five of them. The file therefore loaded only when another test had already imported the real utils.native_tls, so it passed in a full run and failed on its own with "No module named 'utils.native_tls'". Reproduced on upstream main at aaf9948, so this predates this branch: running the file alone, or in any narrow selection, errors during collection. Cross-platform CI runs the PR's own test files as a narrow selection, which is how it surfaced.
Rejecting a wheel that installed but would not import left the broken distribution in
site-packages, and the fallback installed over it rather than replacing it. pip reports
it as already satisfied and uv audits it as no change, both exiting 0, and that exit
code reached an unconditional return True. Long-context training then continued with an
unusable extension, which is the failure the wheel check was meant to stop.
Measured against a real flash_attn 2.8.1 install:
pip install --no-build-isolation --no-deps flash-attn
-> "Requirement already satisfied: flash-attn ... (2.8.1)", exit 0
uv pip install --no-build-isolation --no-deps flash-attn
-> "Audited 1 package", "Would make no changes", exit 0
So pass --force-reinstall (pip) / --reinstall (uv) on the fallback when a wheel was
rejected, and verify the import afterwards instead of trusting rc=0. The flag is gated on
the rejection so the ordinary path keeps installing over nothing and does not rebuild.
test_runtime_flash_attn_falls_back_to_pypi mocked an install that exits 0 without ever
making the module importable, which under the post-install check is a failed install, not
a successful one. It now flips the import stub when the install runs.
… out of process
Two problems with the previous commit.
--force-reinstall was the wrong tool. pip documents it as "Reinstall all packages even
if they are already up-to-date" and uv's --reinstall as "Reinstall all packages": both
scope to the whole resolved transaction, not the named one. flash-attn depends on torch,
so on the plain fallback path (which carries no --no-deps) that could reinstall or
downgrade the torch the worker is currently running on. Measured with a stand-in whose
metadata resolves, since flash-attn's sdist cannot build metadata here:
pip install --dry-run requests -> 0 packages
pip install --force-reinstall --dry-run requests -> 5 packages
(requests + its whole closure)
It also fails outright on that path: --force-reinstall makes pip rebuild flash-attn from
sdist, and the plain branch passes no --no-build-isolation, so the build dies on
"No module named 'torch'". This file already pairs --force-reinstall with --no-deps
elsewhere for the same reason.
So remove the rejected distribution and leave the fallback command untouched. Nothing is
reported as already satisfied afterwards, the transaction stays exactly as wide as it was
before, and no rebuild flags change.
Second, the post-install probe now runs in a child. A wheel built for the wrong arch can
abort or segfault inside the extension's initialiser rather than raising, and except
Exception cannot catch that: it would kill the worker and take the fallback with it. The
child turns it into a return code, negative for a fatal signal. install_python_stack
already probes this way; the worker now matches it. The cheap in-process check stays for
"is it already installed", which costs no spawn on every training start and imports the
module the worker wants imported anyway.
The module name is passed as argv rather than formatted into the -c body.
The worker bounds this same untrusted import at 300s and handles TimeoutExpired; the installer probe had no timeout, so a native extension that hangs in its initialiser rather than failing would leave setup waiting forever and never reach the warning. The asymmetry arrived with the post-install probe added earlier in this branch, which is exactly the call that hands an unvalidated wheel to the import machinery. Bound it the same way and treat a hang, or a probe that cannot be spawned, as an unusable wheel. The timeout is a named constant on both sides so the two paths cannot drift apart again silently.
The setup path warned and continued while leaving the unusable distribution in
site-packages, so "Continuing without flash-attn" was not true. unsloth/models/_utils.py
gates on _package_available("flash_attn"), which reads metadata rather than importing,
and then does an in-process "from flash_attn.flash_attn_interface import ...". A wheel
that aborts during native initialisation therefore takes the training process down, and
that is exactly the wheel this branch has just rejected.
Confirmed with a package that calls os.abort() at import: importing it in process kills
the interpreter with SIGABRT, while the out-of-process probe returns rc -6 and survives.
Uninstalling a properly installed distribution removes it cleanly.
The worker path already uninstalls before its fallback; the installer now matches.
…iled removal Two problems in the cleanup added in the previous commit. It hard-coded "uv pip uninstall --python". _bootstrap_uv sets UV_NEEDS_SYSTEM exactly when the --python probe FAILED and --system succeeded, so on those hosts the cleanup used the one mode already known not to work there: the uninstall fails, the unusable wheel stays in site-packages, and unsloth/models/_utils.py still finds it by metadata and imports it in process. Mirror the install mode instead. uv documents --system as "Use the system Python to uninstall packages". It also printed "removed it" unconditionally, so a failed removal produced two contradicting warnings in the same run: "Could not remove the unusable flash-attn install" followed by "...; removed it". The helper now returns whether the package is actually gone, and the caller says which happened. A wheel still installed is not the same state as never having installed one, so the failure case says so and points at the manual uninstall.
The PyPI fallback returned False without removing the distribution it had just rejected, so the unusable extension stayed where unsloth/models/_utils.py finds it: that gate reads package METADATA and then imports the native module in process, which is exactly the import the isolated probe could not survive. Two ways in: a failed uninstall leaves the wheel "already satisfied" so the fallback no-ops, or the source build itself produces an incompatible extension. This is the third round on the same defect, in a third place, so fix the shape rather than the instance. _reject_install is now the single discard path: it uninstalls, and it reports which state we actually ended in. _uninstall_package returns whether the distribution is gone rather than only logging. The pre-fallback uninstall stays a plain call: a failure there is not fatal, because the fallback then no-ops on "already satisfied", the probe rejects it, and _reject_install reports the real state.
The timeout and install-failure exits returned without discarding the rejected distribution, so a wheel that had already failed its import check stayed where unsloth/models/_utils.py finds it: that gate reads METADATA and only then imports the native module in process. The comment added last round claimed the fallback path would clean up on its own, and that is only true when the fallback exits 0. This is the fourth defect of the same shape, each one an exit somebody did not think to clean up, so enforce the invariant structurally rather than adding a fourth call. _install_package_wheel_first now keeps the two "touch nothing" guards (already importable, offline) and delegates the rest to _attempt_package_install, discarding whatever is left in a finally. Any unsuccessful exit, including ones added later, is covered. The discard is state-based so it is safe to run everywhere: _distribution_present reads metadata via importlib.metadata without importing, so it never loads an extension that would abort, and _reject_install no-ops when there is nothing installed. Verified on the B200 that a working flash-attn 2.8.1 is still untouched: three consecutive runs return True with zero install or uninstall subprocesses, and it stays importable.
Two rejection tests asserted on the discard status message without pinning _distribution_present, so after the discard became state-based they only passed where flash-attn happened to be installed. That was true in the venv I had been running them in and false on a clean runner, where the discard correctly no-ops and no status is sent. Cross-platform CI caught it on ubuntu-latest; the same two tests fail in a fresh venv here and pass with the state pinned. No production change: the invariant holds either way. The tests were reading the machine rather than the code.
8c1e725 to
96c28a9
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 96c28a9cc5
ℹ️ 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".
| if _model_offline_mode_enabled(): | ||
| logger.info("Skipping %s installation while offline", display_name) | ||
| return False |
There was a problem hiding this comment.
Clean up broken packages even in offline mode
When an installed fast-path distribution exists but its import raises an ABI/architecture OSError or RuntimeError, the new _is_importable() converts that failure to False, but an offline run returns here before _reject_install() can remove the metadata. The worker then reports that it is continuing without the package, while the later metadata-based availability gate still imports the broken native extension in-process and can terminate training. Offline mode should prevent network installation, not bypass local cleanup; either reject the unusable distribution here or fail before model loading.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Disagreeing with this one. The control flow you describe is right, offline does return before the cleanup, but the impact does not follow, and acting on it would make things worse.
The stated consequence is that the metadata gate imports the broken extension in process and can terminate training. That import is guarded. unsloth/models/_utils.py:2125-2145 wraps it in try/except and the handler prints "Your Flash Attention 2 installation seems to be broken. Using Xformers instead", stubs is_flash_attn_2_available to False, and sets HAS_FLASH_ATTENTION = False. So a distribution whose import RAISES, which is the OSError/RuntimeError case you name, is already handled and training continues on Xformers.
The only import that can actually terminate the process is one that aborts or segfaults, and that cannot reach the offline branch: the in-process _is_importable pre-check runs before it and would have taken the worker down first. So there is no path where skipping cleanup offline causes the crash described.
Against that, uninstalling while offline is destructive and unrecoverable: there is no network to reinstall from, so we would delete a package the user may have deliberately staged, to protect against a failure mode that is already handled. Offline meaning "change nothing" is the safer contract, and it is why the guard sits outside the cleanup rather than inside it.
Happy to revisit if you can point at an unguarded in-process import of a fast-path package that is reachable offline.
install_wheel always targets sys.executable: its uv command passes --python in addition to --system, and its pip fallback runs that interpreter directly. The cleanup passed --system INSTEAD of --python, so on a UV_NEEDS_SYSTEM host it uninstalled from the system Python while the wheel sat in the venv, and setup then reported the wheel removed when it was still there for the metadata gate to import. Pass both, so the removal mirrors the install rather than half of it. The earlier test asserting the --system-only command is replaced, since it pinned the broken command. The worker path already targets --python sys.executable on both sides and needs no change.
|
Codex Review: Didn't find any major issues. Delightful! 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 |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 038f952135
ℹ️ 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".
| "removed; uninstall flash-attn manually before training", | ||
| _cyan, | ||
| ) | ||
| break |
There was a problem hiding this comment.
Retry the wheel after removing an already-satisfied install
When a non-importable flash-attn distribution has the same version as the selected wheel—for example, after moving a virtual environment between architectures—the ordinary uv/pip commands in install_wheel can exit successfully without replacing it. This branch then removes the stale distribution and immediately breaks, leaving setup without flash-attn even though the selected wheel may work once installed cleanly; retry that wheel once after removal. I confirmed the CLI semantics from the local help: pip's --force-reinstall “Reinstall[s] all packages even if they are already up-to-date,” while uv's --reinstall installs regardless of whether the package is already present.
Useful? React with 👍 / 👎.
| sys.executable, | ||
| "-c", | ||
| "import importlib, sys; importlib.import_module(sys.argv[1])", | ||
| import_name, | ||
| ], |
There was a problem hiding this comment.
Preserve the Windows ROCm DLL setup in import probes
On Windows ROCm, the worker deliberately uses os.add_dll_directory because subprocesses do not inherit those registrations, but this new python -c probe does not repeat that setup. A newly installed mamba_ssm is still validated on Windows (only causal-conv1d is skipped), so the child can fail while loading Torch with a missing amdhip64.dll even though the real worker can import it; the valid package is then rejected and uninstalled, breaking training for the SSM models that require it. Initialize the ROCm DLL directories inside the probe or otherwise propagate them to the child.
Useful? React with 👍 / 👎.
| if shutil.which("uv"): | ||
| cmd = ["uv", "pip", "uninstall", "--python", sys.executable, pypi_name] |
There was a problem hiding this comment.
Fall back to pip when uv cannot uninstall the target
When Studio runs under a system Python and uv is merely present on PATH, uv requires system mode to modify that interpreter. install_wheel can fall back from the refused uv command to pip and install the candidate, but this cleanup always chooses uv without --system and never tries pip, so a rejected wheel remains installed and the subsequent source fallback selects the same unusable uv path. This repository already tracks the required UV_NEEDS_SYSTEM mode in install_python_stack.py; local uv pip uninstall --help likewise describes --system as using the system Python. Preserve the successful installer/mode or retry removal with sys.executable -m pip.
Useful? React with 👍 / 👎.
A prebuilt wheel can install with exit code 0 and then fail to load, so the exit code on its own is not proof the install is usable. We have now hit that twice on Blackwell, from both directions:
has_blackwell_gpu()was added to skip the install.return False.Neither fix addressed what both failures actually had in common, which is that nothing checked whether the installed wheel could be imported.
What this changes
Verify the import after a zero exit code, in the two paths that did not, and treat a failure as not installed.
ssm_runtime._install_kernelalready did exactly this, for the same reason:So this is that existing check applied to
install_python_stack._ensure_flash_attnandworker._install_package_wheel_first, rather than a new pattern.worker._is_importable()catches any exception rather than onlyImportError. An arch or ABI mismatch surfaces asOSError/RuntimeError("undefined symbol", "no kernel image is available"), which the oldexcept ImportErrorpre-check would have let escape mid-training.Drop
has_blackwell_gpu()and its two call sites. It has returnedFalseunconditionally since 03cbe21, so both blocks were already unreachable and removing them changes no behaviour at all. I left a comment inwheel_utils.pyrecording why there is no arch gate, since the dead code reads like an oversight otherwise. An arch gate encodes a snapshot of what upstream publishes and goes stale silently in both directions; the import check catches a wheel that will not load whatever the cause, and needs no table of who ships what.The xFormers path in
diffusion_attention.pyis deliberately left alone: it already handles ABI mismatch by resolving the URL against the running torch.Verification
Checked on an 8x B200 host (
compute_cap 10.0).The wheel this resolver builds for cu13 / torch2.10 / cp313 carries Blackwell kernels.
cuobjdump --list-elf:It installs through
wheel_utils.install_wheel()itself and runs:The new check discriminates correctly against that install:
Truein the venv holding the working wheel,Falsewhere it is absent.Live probe of the URL matrix the resolver builds (torch 2.8 to 2.12, cu12/cu13, cp311/312/313): 30 URLs built, 17 live, 13 return 404.
url_exists()is what decides whether anything installs, which is also why the arch gate was redundant by the time it was removed.Unrelated but worth recording, since I checked it while probing: torch 2.9 + cp313 returns 404 because upstream only ever built cp312 for torch 2.9, across v2.8.1, v2.8.2, v2.8.3 and v2.8.3.post1. The resolver is correct there and the PyPI fallback is the right outcome, so nothing to change.
Tests
Targeted suites: 176 passed, 5 skipped. Three tests are new, one per behaviour:
test_runtime_flash_attn_prefers_prebuilt_wheelneeded updating: it mockedinstall_wheelto return rc=0 while stubbing__import__to always fail, which under the new semantics is a broken wheel, not a working one. It now flips the import stub when the install runs, which is what "the wheel worked" actually means.Full sweep of
tests/pythonandstudio/backend/tests, same command before and after:+3 passedis exactly the new tests. The 668 failures and 360 errors are pre-existing missing-dependency failures in that venv, identical on main.One caveat rather than a clean claim: the two failure lists differ by 2 entries, both in
test_stt_broken_runtime_falls_back.py. All 5 tests in that file fail in isolation onModuleNotFoundError: No module named 'jwt', and which subset the full run reports shuffles with ordering; two consecutive runs on main also differed by one. That file has no reference to anything touched here.