Skip to content

AMD: Fix BF16 detection on gfx10 ROCm GPUs - #7682

Merged
danielhanchen merged 21 commits into
unslothai:mainfrom
sunjingwen21:agent/fix-rocm-gfx10-bf16-detection
Sep 1, 2026
Merged

danielhanchen merged 21 commits into
unslothai:mainfrom
sunjingwen21:agent/fix-rocm-gfx10-bf16-detection

Conversation

@sunjingwen21

@sunjingwen21 sunjingwen21 commented Jul 31, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #7922.

Problem

On an AMD Radeon RX 6600 (gfx1032), torch.cuda.is_bf16_supported() returns True, 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:

LLVM ERROR: Cannot select: intrinsic %llvm.amdgcn.fdot2.bf16.bf16

The native process exits before Python can raise, so Studio shows only Training process exited unexpectedly at 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.html

On ROCm, is_bf16_supported() is a broad runtime check rather than a native-capability test, so reading gcnArchName is the documented way to answer this. The ROCm branch is a bare if torch.version.hip: return True as 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 and including_emulation=False does not change its answer either.

Fix

  • arch_lacks_bf16() gates HIP BF16 off for gfx10* (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.py consumes the corrected probe rather than unconditionally enabling BF16 on HIP.
  • The probe reads every visible device. SUPPORTS_BFLOAT16 is 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: the fdot2.bf16.bf16 intrinsic is gated on the dot9-insts feature, which gfx10 subtargets do not carry and gfx11 does.

Scope

The other half of this path was unsloth_zoo/gradient_checkpointing.py, which hardcoded SUPPORTS_BFLOAT16 = True on 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.16 floor 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 inputs gfx10 and gfx10foo.
    • The rest exec the real _gpu_init.py BF16 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.
    • Reverting the _gpu_init.py hunk 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.
  • Real AMD Radeon RX 6600 / Windows / ROCm 7.13 / Torch 2.11, Qwen2 0.5B QLoRA: dtype torch.float16, Bfloat16 = FALSE, forward, backward and bitsandbytes AdamW8bit step all succeeded.
  • Self-hosted gfx1151 (Strix Halo) / Linux / ROCm 7.2.1, base vs head: CONFIRMED. On the real host BF16 stays enabled and a real LoRA step runs on both base and head, so nothing regresses; presenting gcnArchName = "gfx1032" on that same real ROCm install flips head to FP16 while base still reports BF16 supported.
  • NVIDIA B200 / Linux / Torch 2.9.1+cu128, Llama-3.2-1B QLoRA: DEVICE_TYPE=cuda, BF16 stays enabled, the CUDA branch still installs its own including_emulation forwarding wrapper rather than the HIP constant, dtype resolves to torch.bfloat16, and 5 LoRA steps train with a falling loss.
  • torch.cuda.is_bf16_supported read 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 gcnArchName is unreadable on every visible device the arch list is empty and PyTorch's True still stands, which is fail-open by choice: guessing False there would drop BF16 on any CDNA host whose probe hiccups.

@sunjingwen21
sunjingwen21 marked this pull request as ready for review July 31, 2026 11:00
@LeoBorcherding LeoBorcherding changed the title Fix BF16 detection on gfx10 ROCm GPUs AMD: Fix BF16 detection on gfx10 ROCm GPUs Jul 31, 2026
@LeoBorcherding LeoBorcherding self-assigned this Jul 31, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 👍

Reviewed commit: 163a990a1f

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

@oobabooga

Copy link
Copy Markdown
Member

@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 pre-commit.ci autofix. Or do it locally, it is one change in unsloth/_gpu_init.py:

pip install pre-commit
pre-commit run --files unsloth/_gpu_init.py

The PR otherwise looks good.

@sunjingwen21

Copy link
Copy Markdown
Contributor Author

pre-commit.ci autofix

@sunjingwen21

Copy link
Copy Markdown
Contributor Author

@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!

xxxxxxxxxxxxx and others added 3 commits August 27, 2026 17:41
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.
@LeoBorcherding

Copy link
Copy Markdown
Collaborator

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. gfx10* is exactly RDNA 1 and 2 and leaves gfx11xx/gfx12xx alone, the :sramecc- suffix gets stripped, and _gpu_init patches the probe before models/_utils reads it, which holds because _utils can only be imported through unsloth/__init__.py.

The tests, though:

test_rocm_bf16_capability.py
main, with this PR's test file 9 failed
PR head 2935216 9 passed
2935216 merged with main 8 failed
after my commit 20 passed

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 whose test is a plain == "cuda" comparison and execing its hip arm. Main has since added

if DEVICE_TYPE == "cuda" and not torch.cuda.is_available():

in front of it. That's a boolean and, not a plain comparison, so the scraper walks past the bf16 chain at line 317 and grabs the triton block at 359 instead, whose hip arm is a bare pass. Nothing gets defined and all nine die on KeyError: 'SUPPORTS_BFLOAT16'. They weren't getting the wrong answer, they were reading a different part of the file.

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 unsloth/device_type.py. No AST, no exec, nothing coupled to the shape of an if/elif chain people keep editing. Nine tests to twenty, covering RDNA 1 through 4, CDNA, case and whitespace, and the unreadable-arch case.

One other change. The arch came from device 0 only, but SUPPORTS_BFLOAT16 is process-wide. 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() now reads every visible device, and one gfx10 turns bf16 off for all of them.

Two things I left alone.

There is no closing keyword in the description, so GitHub shows no linked issues and merging leaves 7922 open. Fixes #7922 would do it. For the record that is one issue, not three: 7923 and 5337 are both closed as duplicates of it.

unsloth_zoo/gradient_checkpointing.py:631 still hardcodes SUPPORTS_BFLOAT16 = True on HIP and never asks torch, so the monkeypatch does not reach it. You get there through patch_unsloth_smart_gradient_checkpointing() with no dtype, where it picks the dtype for the pinned offload buffers. Different repo, separate PR.

What I ran. 21 files touching device_type / _gpu_init / SUPPORTS_BFLOAT16, one file per process, main against branch. Identical except the new file. Three failures on both, so they are main's: the two test_rocm_support.py::TestInstallShStructure cases and test_hardware_dispatch_matrix.py::test_studio_detect_hardware_matches_profile[nvidia_cuda]. ruff and the kwarg formatter are clean on all three touched files.

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: SUPPORTS_BFLOAT16 stays True before and after, Windows 11, ROCm 7.13, torch 2.11.0+rocm7.13.0, real import unsloth. @sunjingwen21's RX 6600 run is still the only evidence for the direction that actually matters, and nobody else has reproduced the crash.

Also worth knowing: nineteen workflows are still waiting on approval, so only pre-commit.ci has run, and Codex's clean pass was 163a990a, four commits back.

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 7c03510b27

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

@LeoBorcherding

LeoBorcherding commented Aug 28, 2026 •

Copy link
Copy Markdown
Collaborator

all staged ci failures are unrelated to this pr
image

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.
danielhanchen added a commit to unslothai/unsloth-zoo that referenced this pull request Aug 31, 2026
…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]>
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Aug 31, 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-01T03:44:21.634462Z c6bf4f6 Manual request
ℹ️ 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[bot]

This comment was marked as resolved.

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 58a0f7d80e

ℹ️ 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-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
@danielhanchen

Copy link
Copy Markdown
Member

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:

base head
device presented as gfx1032 bf16 reported supported bf16 correctly withheld
real gfx1151 bf16 supported bf16 still supported

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 startswith("gfx10") against every real AMD arch string; it matches exactly gfx1010-1013 and gfx1030-1036, and nothing else.

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 main

When I first looked, this PR was incomplete on its own: unsloth_zoo/gradient_checkpointing.py hardcoded SUPPORTS_BFLOAT16 = True for HIP, so a gfx10 host still allocated bf16 offload buffers. unslothai/unsloth-zoo#1130 is merged, and zoo now defers to the probe this PR patches. The two are correctly coupled and this is no longer half a fix.

One thing I fixed on the branch

378997aa kept the device_type stub in tests/conftest.py in step with the new gate. Without it the new test file died at collection rather than skipping, which takes down the whole CPU suite rather than one file.

The comment pass above is comment-only, verified by comment_tools check and independently at AST level. Where it conflicted with your new per-device guard I kept your wording and trimmed it, since it documents the behaviour you added.

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.
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Another round soon, please!

Reviewed commit: 70ac487fa5

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

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.
@danielhanchen
danielhanchen merged commit 1aa9744 into unslothai:main Sep 1, 2026
1 check passed
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 1, 2026
@unslothai unslothai deleted a comment from oobabooga Sep 1, 2026
@unslothai unslothai deleted a comment from LeoBorcherding Sep 1, 2026
@unslothai unslothai deleted a comment from LeoBorcherding Sep 1, 2026
@unslothai unslothai deleted a comment from LeoBorcherding Sep 1, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Hooray!

Reviewed commit: 1aa9744400

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug] fine-tuning with AMD gfx1032 crashes

6 participants