Repository navigation
AMD: Fix BF16 detection on gfx10 ROCm GPUs - #7682
danielhanchen merged 21 commits into
Conversation
|
Codex Review: Didn't find any major issues. 👍 Reviewed commit: ℹ️ About Codex in GitHubCodex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback". |
|
@sunjingwen21 pre-commit.ci is red because its autofix cannot push to your branch: "Allow edits by maintainers" is off, so re-running it will not clear the check. Please check that box in the right sidebar of this PR (only you can change it), then write a reply saying The PR otherwise looks good. |
|
pre-commit.ci autofix |
|
@oobabooga Thanks for the help! pre-commit.ci is now passing. @danielhanchen Could you take a look and approve the workflows when you have a chance? Thanks! |
The tests located the bf16 branch by AST: first top-level if whose test is a
plain comparison against "cuda", then exec its hip arm against a fake torch.
Main has since added
if DEVICE_TYPE == "cuda" and not torch.cuda.is_available():
in front of the chain. That test is a BoolOp, not a Compare, so the scraper
skips the real chain at line 317, walks on, and grabs the triton block at 359
whose hip arm is a bare pass. Executing pass defines nothing and all nine tests
die on KeyError: 'SUPPORTS_BFLOAT16'. They were not getting the wrong answer,
they were reading an unrelated part of the file.
arch_lacks_bf16() moves the decision into device_type.py as a pure string check,
so the tests call the real predicate directly. No AST, no exec, and no coupling
to the shape of an if/elif chain other people are editing.
The arch was also read from device 0 only while SUPPORTS_BFLOAT16 is
process-wide, so a gfx1100 at index 0 next to a gfx1030 at index 1 left the gate
open and the older card still died. hip_visible_archs() reads every visible
device and one gfx10 now disables bf16 for all of them.
Measured on an R9700 (gfx1201, Windows, ROCm 7.13, torch 2.11.0+rocm7.13.0):
SUPPORTS_BFLOAT16 stays True before and after, so the gate does not misfire on
RDNA 4. No gfx10 card here, so the failing direction is still unreproduced.
|
Took a look. The fix is right; the tests are what's blocking it. I pushed three commits: two merges of main (branch was 14 days behind) and one change. Happy to back it out if you'd rather make it yourself, @sunjingwen21. The gate itself is good. The tests, though:
Row three isn't the fix. The merge is clean and the fix comes through intact. The tests find the bf16 branch by AST, taking the first top-level if DEVICE_TYPE == "cuda" and not torch.cuda.is_available():in front of it. That's a boolean So I moved the decision into something the tests can just call: def arch_lacks_bf16(gcn_arch):
"""True for gfx10 (RDNA 1 and 2), which has no native bf16 arithmetic."""
return str(gcn_arch or "").split(":", 1)[0].strip().lower().startswith("gfx10")It lives in One other change. The arch came from device 0 only, but Two things I left alone. There is no closing keyword in the description, so GitHub shows no linked issues and merging leaves 7922 open.
What I ran. 21 files touching What I cannot vouch for. This box is an R9700, gfx1201. It cannot reproduce a gfx10 crash, so the above is a code read plus CPU-side test runs. The only real device row I have is the negative control, that the gate does not misfire on RDNA 4: Also worth knowing: nineteen workflows are still waiting on approval, so only pre-commit.ci has run, and Codex's clean pass was |
|
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". |
tests/python/test_rocm_bf16_capability.py imports arch_lacks_bf16 from unsloth.device_type at module scope. tests/conftest.py tries to preload the real module and, on any exception, silently falls back to _install_device_type_stub, whose attribute set is fixed and does not carry that name. On that path the new file raises ImportError during collection, which is an error for the whole run rather than a skipped file. The preload happens to succeed on the current CPU runner, so this is latent rather than breaking today, but it is the reason existing tests avoid importing named symbols from unsloth.device_type. Adding the two new names to the stub keeps the file collectable either way. The stub stands in for a non-HIP host, so hip_visible_archs() is empty and nothing is gated.
…fers (#1130) * Ask whether HIP supports bf16 before allocating bf16 offload buffers The gradient checkpointing offload path hardcodes SUPPORTS_BFLOAT16 = True on HIP and so pins its CPU buffers in bfloat16 on every AMD host. RDNA 1 and 2 (gfx101x, gfx103x) have no native bf16 arithmetic: Triton selects llvm.amdgcn.fdot2.bf16.bf16, LLVM cannot lower it for the target, and the process dies with no Python exception, which the user sees as training exiting at step 0. See unslothai/unsloth issue 7922. torch.cuda.is_bf16_supported() answers True on ROCm regardless, so on its own this line behaves exactly as before. It matters because unsloth patches that probe on HIP to consult the device arch, which makes this the last place in the two repos still deciding bf16 for AMD without asking. Pairs with unslothai/unsloth#7682, which is incomplete without it. * Cover the HIP bf16 probe, including the inertness this rests on The change had no test, and the claim it needs to carry is a pair that pulls in two directions: on a stock ROCm host the dtype must NOT move, and on a host where the probe has been patched it must. `torch.cuda.is_bf16_supported` returns True for `torch.version.hip` before it looks at the architecture at all, and never consults `including_emulation` on that path, so every AMD user today gets bfloat16 here and still will after this lands. A test that only asserted "float16 now" would be asserting a regression for all of them. `DEVICE_TYPE_TORCH` maps "hip" to "cuda", so the real initializer can be driven down its HIP branch on an NVIDIA box by spoofing one module global, and the buffers it allocates are real. Four behavioural checks plus one that reads the source, so the CPU lane still asserts the branch is asking rather than hardcoding. The CUDA check is the one that keeps the blast radius honest: it hands CUDA a probe answering False and requires the dtype to stay on compute capability. Mutation-tested both ways -- restoring `SUPPORTS_BFLOAT16 = True` fails three of the five, and leaking the probe into the CUDA branch fails the fourth. * Tighten the HIP bf16 comment * Comment pass: 45 comment lines to 18 Delete-first, per unslothai/scripts#230, redoing the earlier shorten-only pass. gradient_checkpointing.py 4 -> 4 (the rationale IS the change) tests 41 -> 14 TOTAL 45 -> 18 (60%) Below the 70% target and the reason is the denominator: 4 of the 45 lines are the production comment explaining why the probe is called, which is the whole point of the PR and cannot go. Excluding it, 41 -> 14 is 66%. Deleted the docstrings whose function name already said the same thing, and the paragraph describing how the test spoofs DEVICE_TYPE_TORCH, which the code shows. Kept: the gfx101x/gfx103x crash with its issue reference, and the inertness claim, since a test proving only 'float16 now' would prove a regression for every current ROCm user. comment_tools check --strip-docstrings FAILs the test file because _strip_docstrings blanks a docstring rather than removing the node, so deleting one reads as a code change. Verified independently: ASTs identical once docstrings and comments are stripped from both versions. * Run the HIP dtype decision on CPU, and put the file in a gate The four runtime assertions were behind `torch.cuda.is_available()` and the file was named by no pytest invocation, so `pytest tests/ --collect-only` was the only thing that ever touched it. That proves the module imports and nothing else: the probe could be swapped for another call, or the dtype picked the other way, and the suite stayed green. The gate step's own comment records this happening five times already. Stubbing device_count to 0 is what makes a CPU run possible. The function then allocates no device buffer, no stream and no event, so the dtype decision is all that is left, and torch.empty is unwrapped rather than reimplemented so the dtype under test is still the module's own choice. Every module global the call writes is restored afterwards, read from its own `global` statements so the list cannot fall behind: the gate runs this file in one process with thirty others, and USE_UNSLOTH_GC plus 200 buffers left behind would follow them. Four mutations caught: hardcoding True, calling is_available instead of the bf16 probe, letting CUDA consult the probe, and pinning the dtype to bfloat16. The whole gate list runs green in one process with the file added. * Shorten the new test's docstrings --------- Co-authored-by: danielhanchen <[email protected]> Co-authored-by: danielhanchen <[email protected]>
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
…reopen the bf16 gate
|
Codex Review: Didn't find any major issues. Keep them coming! 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". |
Comment-only change; no code touched. Added comment lines drop from 27 to 9. comment_tools.py check passes 4/4 (code unchanged, comments only), and tests/python/test_rocm_bf16_capability.py passes 20/20. Kept the gfx10 bf16 failure mode and the 5 character prefix constraint once in arch_lacks_bf16, the process-wide gate rationale at the _gpu_init call site, and the collection-error reason for the conftest stub entries.
# Conflicts: # unsloth/device_type.py
|
Consolidating my earlier comments into one summary and deleting the rest, to keep this reviewable. Validated on real AMD hardware (gfx1151 Strix Halo)CONFIRMED. Base versus head on a real ROCm 7.2.1 install:
Both readings matter. The second is the control: this is one character away from disabling bf16 on every RDNA3 card, and a fix that over-matches would look identical on the first row alone. I evaluated Honest limit: no gfx10 silicon was involved. The arch is presented to a real ROCm stack, so the code path is real, but the RDNA1/2 hardware from #7922 was not. The companion half is now on mainWhen I first looked, this PR was incomplete on its own: One thing I fixed on the branch
The comment pass above is comment-only, verified by |
The source-text assertions prove the hip branch is spelled right, not that it computes the right answer, and no CI runner has gfx10 silicon to answer that. These cases exec the real _gpu_init.py bf16 chain against a fake HIP device set: the patched probe under every call form torch's shifting signature allows, a mixed gfx1030+gfx1100 host, zero devices, an unreadable device count, a wedged device beside a gfx10, a reimport, and that none of it fires off hip.
|
Codex Review: Didn't find any major issues. Another round soon, please! 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". |
Delete restatements of the test names and the assertions, and collapse the remaining paragraphs to one line each. The gfx10 crash mechanism, the 5-char prefix, the per-device guard and the process-wide constant all keep a line.
|
Codex Review: Didn't find any major issues. Hooray! 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". |

Fixes #7922.
Problem
On an AMD Radeon RX 6600 (
gfx1032),torch.cuda.is_bf16_supported()returnsTrue, but RDNA 2 has no native BF16 arithmetic. Unsloth loads the model as BF16, Triton selects a BF16 dot-product intrinsic, and LLVM cannot lower it for gfx1032:The native process exits before Python can raise, so Studio shows only
Training process exited unexpectedlyat step 0. AMD's own feature table marks BF16 arithmetic unsupported on RDNA 1/2: https://rocm.docs.amd.com/projects/HIP/en/docs-6.3.2/reference/hardware_features.htmlOn ROCm,
is_bf16_supported()is a broad runtime check rather than a native-capability test, so readinggcnArchNameis the documented way to answer this. The ROCm branch is a bareif torch.version.hip: return Trueas the first statement of the function, unchanged in every release from 1.13 through 2.13 and main, so it never consults the device arch andincluding_emulation=Falsedoes not change its answer either.Fix
arch_lacks_bf16()gates HIP BF16 off forgfx10*(RDNA 1/2) regardless of what PyTorch reports.torch.cuda.is_bf16_supported()is patched with the corrected result, so Unsloth and Unsloth Zoo callers agree instead of each deciding separately.models/_utils.pyconsumes the corrected probe rather than unconditionally enabling BF16 on HIP.SUPPORTS_BFLOAT16is a single process-wide constant, so a mixed host cannot be judged per card: one gfx10 anywhere in the visible set disables BF16 for the process. That is the conservative direction, and it costs a mixed gfx1030 + gfx1100 box some speed rather than a crash.Affected gfx10 GPUs fall back to FP16. Every other HIP architecture keeps PyTorch's existing answer:
startswith("gfx10")matches gfx1010-1013 and gfx1030-1036 and nothing else, not gfx11xx, not gfx12xx, not gfx9xx. That boundary matches LLVM's own target definitions: thefdot2.bf16.bf16intrinsic is gated on thedot9-instsfeature, which gfx10 subtargets do not carry and gfx11 does.Scope
The other half of this path was
unsloth_zoo/gradient_checkpointing.py, which hardcodedSUPPORTS_BFLOAT16 = Trueon HIP and ignored the probe entirely, so a gfx10 host still allocated BF16 pinned offload buffers. That is fixed by unslothai/unsloth-zoo#1130, now merged, which routes the constant through this probe.That half is not required to stop the crash. Those buffers are pinned CPU memory, so on a pre-#1130 Zoo a gfx10 host still loads FP16 weights and still avoids the Triton intrinsic; it only pays a needless FP16 to BF16 round trip on the offloaded activations. #1130 ships in the next Zoo release (PyPI is still on 2026.8.16), so the
unsloth_zoo>=2026.8.16floor is deliberately left alone here.Validation
pytest tests/python/test_rocm_bf16_capability.py -q: 44 passed.arch_lacks_bf16()over every real AMD arch string plus:xnack+/:sramecc-suffixes, case and whitespace variants,None,"", and the near-miss inputsgfx10andgfx10foo._gpu_init.pyBF16 chain against a fake HIP device set, because asserting on the source text only proves the branch is spelled right and no runner has gfx10 silicon: the patched probe under no-arg, positional,including_emulation=and unknown-kwarg calls; mixed gfx1030+gfx1100 in both orders; zero devices; an unreadable device count; a wedged device beside a gfx10; a reimport; and that a gfx10 arch presented to the CUDA or XPU branch changes nothing._gpu_init.pyhunk fails 12 of those; the ones that still pass are the "nothing changed off gfx10" regression guards, which are meant to be insensitive to the fix.torch.float16,Bfloat16 = FALSE, forward, backward and bitsandbytes AdamW8bit step all succeeded.gcnArchName = "gfx1032"on that same real ROCm install flips head to FP16 while base still reports BF16 supported.DEVICE_TYPE=cuda, BF16 stays enabled, the CUDA branch still installs its ownincluding_emulationforwarding wrapper rather than the HIP constant, dtype resolves totorch.bfloat16, and 5 LoRA steps train with a falling loss.torch.cuda.is_bf16_supportedread from the installed wheel on torch 2.6.0, 2.7.0, 2.8.0, 2.9.1 and 2.13.0: signature is(including_emulation: bool = True)in all five and the ROCm short circuit precedes any use of that argument in all five, so replacing the function on HIP cannot change an answer any of those versions used to give.Not covered. No gfx10 silicon is available on any runner, so the crash itself is reproduced by presenting a gfx10 arch on real ROCm rather than end to end on an RDNA 2 card. gfx90c (Vega iGPU) also lacks native BF16 and is deliberately out of scope here. If
gcnArchNameis unreadable on every visible device the arch list is empty and PyTorch'sTruestill stands, which is fail-open by choice: guessingFalsethere would drop BF16 on any CDNA host whose probe hiccups.