Skip to content

Core: decide bfloat16, compile and TMA options from every visible NVIDIA GPU on mixed hosts - #13923

Merged
danielhanchen merged 8 commits into
mainfrom
r7a-core-mixed-nvidia-caps
Oct 16, 2026
Merged

danielhanchen merged 8 commits into
mainfrom
r7a-core-mixed-nvidia-caps

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 15, 2026 •

Copy link
Copy Markdown
Member

Problem

On a host with NVIDIA GPUs of different generations, several process-wide decisions were made from device 0 only. Older cards later in the list were ignored:

  • bfloat16: SUPPORTS_BFLOAT16 and torch.cuda.is_bf16_supported() read get_device_capability() for the current device (_gpu_init.py, models/_utils.py). With an RTX 3090 at index 0 and a T4 or V100 at index 1, a model split with device_map="auto" gets bfloat16 on the old card.
  • torch.compile kill switches: the pre-Volta switch (device_type.py) and the gfx906 switch read device 0 only. An sm_61 card at index 1 keeps compile on.
  • GRPO compile options: the persistent TMA matmul and the cutlass TMA options were enabled when device 0 is sm90+, even if another visible card is not.
  • Capability cache: torch.cuda.get_device_capability was replaced process-wide by functools.cache(...). A call with no arguments is cached once, so after torch.cuda.set_device(1) every later no-argument call, in any library, still returned device 0's answer.

The HIP branch already checks every visible GPU for bfloat16 and the gfx10 workarounds (#7922). This brings CUDA in line.

Fix

  • New cuda_visible_capabilities() in device_type.py: returns the capability of every visible CUDA device. It is guarded per device like hip_visible_archs(): an unreadable card is skipped, and only a failed device count returns [].
  • New cuda_gate_capabilities(): what the process-wide gates judge: every card that could be read. That always includes the current device when it is readable, so a gate is never less strict than the rule before this PR, and a known old card beside an unreadable one still counts.
  • bfloat16: enabled only when every visible card is sm80+. On a mixed host one line says which GPUs turn it off and how to keep bfloat16: hide them with CUDA_VISIBLE_DEVICES.
  • Compile kill switches: the pre-Volta switch uses the lowest visible major, and any visible gfx906 disables compile. The gfx906 switch now also sets the live Dynamo config, like the pre-Volta one, so regions compiled while unsloth_zoo imported are turned off too.
  • GRPO TMA options: require every visible card to be sm90+.
  • Capability cache: keyed per resolved device index. No argument means the current device. An int, "cuda:N", "cuda" or a torch.device resolve through torch.device, which Dynamo traces, so get_device_capability(Q.device) inside a fullgraph=True region still compiles. Non-CUDA or unparsable devices are passed through uncached.
  • Flash Attention 2 probe: still uses the current device. Mixed placements keep the existing per-placement handling from Pick the attention backend per device on mixed-generation multi-GPU hosts #13698.

Homogeneous hosts get exactly the same flags and messages, because "every visible card" and "device 0" agree there. CUDA_VISIBLE_DEVICES="" and UNSLOTH_ALLOW_CPU=1 still take the existing no-device branches.

Tests

  • New tests/test_mixed_nvidia_capabilities.py:
    • spoofed capabilities for sm80x2, sm86+sm75 in both orders, sm90+sm61, and sm61 alone;
    • both bfloat16 chains, the notice and the pre-Volta switch;
    • gfx906 in either position;
    • set_device(1) after a no-argument call;
    • device spellings, an unreadable card (the gates still judge every readable card), and the GRPO options.
  • Base vs head: 10 cases fail on main and pass here. The rest pass on both sides, since device 0 is already the weakest card in those shapes.
  • Related suites (driverless import, compile options, flex attention, xformers and fp8 gates, pre-Volta fast inference, ROCm bf16): unchanged on both sides.
  • On a B200, test_capability_cache_traces_in_fullgraph compiles the wrapper with fullgraph=True for no argument, 0, "cuda:0", torch.device("cuda") and x.device: 5 passed. The previous version of the wrapper failed 3 of them.

SUPPORTS_BFLOAT16, is_bf16_supported(), the pre-Volta and gfx906 torch.compile
switches and the GRPO TMA compile options now hold on the weakest visible card,
matching the HIP bf16 branch. The get_device_capability cache is keyed on the
resolved device index so a no-arg call follows torch.cuda.set_device.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 15, 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-10-15T22:32:51.631326Z 855dde1 Manual request
🔒 Security Review ✅ Completed 2026-10-15T20:08:48.371025Z f2291ea 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.

@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: 1bddf7ea12

ℹ️ 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 unsloth/models/rl.py Outdated
cuda_options = """
"triton.enable_persistent_tma_matmul": torch.cuda.get_device_capability()[0] >= 9,"""
# TMA only if every visible card is sm90+: compile options are process-wide.
all_sm90 = "min((torch.cuda.get_device_capability(i)[0] for i in range(torch.cuda.device_count())), default = 0) >= 9"

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 Handle unreadable GPUs when deriving GRPO TMA options

When device_count() includes a GPU whose capability query raises, this generator is evaluated while create_new_function imports the generated GRPO module, so patching the trainer aborts instead of safely disabling TMA. This is the same partial-device-failure case that cuda_visible_capabilities() deliberately handles, and it regresses hosts where the current GPU is healthy but another visible GPU is unreadable; derive the option through a guarded probe and default it to false when any required capability cannot be read.

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.

Fixed in f2291ea. The generated option now goes through cuda_visible_capabilities() and is True only when every visible card was read and is sm90+, so an unreadable card turns TMA off instead of aborting the import. Covered by a new parametrized test with one unreadable card.

Comment thread unsloth/_gpu_init.py Outdated
_cuda_caps = cuda_visible_capabilities()
SUPPORTS_BFLOAT16 = bool(_cuda_caps) and all(major >= 8 for major, _ in _cuda_caps)
if not SUPPORTS_BFLOAT16 and any(major >= 8 for major, _ in _cuda_caps):
_old = [i for i, (major, _) in enumerate(_cuda_caps) if major < 8]

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 CUDA device indices in the bf16 warning

If an earlier visible GPU raises during get_device_capability, cuda_visible_capabilities() skips it and compacts the returned list, so enumerating _cuda_caps no longer yields CUDA device indices. For example, if device 0 is unreadable and device 2 is pre-Ampere, this reports device 1 and tells the user to hide the wrong GPU; retain each successful probe's original index when constructing this diagnostic.

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.

Fixed in f2291ea. cuda_visible_capabilities(with_index = True) keeps each card's real device index, and the notice uses it. Tested with device 0 unreadable and device 2 pre-Ampere: the notice names 2.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex security review

@chatgpt-codex-connector

Copy link
Copy Markdown

🛡️ Codex Security Review

Security review completed. No security issues were found in this pull request.

Reviewed commit: f2291ea8a6

View security finding report

Only the user who started this review can view the report in Codex.

ℹ️ About Codex security reviews in GitHub

This is an experimental Codex feature. Security reviews are triggered when:

  • You comment "@codex security review"
  • A regular code review gets triggered (for example, "@codex review" or when a PR is opened), and you’re opted in so security review runs alongside code review

Once complete, Codex will leave suggestions, or a comment if no findings are found.

@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: f2291ea8a6

ℹ️ 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 unsloth/device_type.py
Comment on lines +200 to +201
except Exception:
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.

P2 Badge Track incomplete CUDA capability scans

When device_count() reports multiple GPUs but get_device_capability(i) raises for one, this continue returns a nonempty partial list. The new bfloat16 gates in _gpu_init.py and models/_utils.py consequently treat the readable entries as every visible card, so one readable Ampere GPU can set SUPPORTS_BFLOAT16=True even when the omitted GPU is pre-Ampere; the pre-Volta compile gate can similarly remain enabled. The GRPO path now correctly checks len(caps) == device_count(), so preserve scan completeness or apply the same check before enabling these other process-wide features.

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.

Fixed in dbb97c6. The bf16 and pre-Volta gates now go through cuda_gate_capabilities(), which judges every visible card only when all of them were read, and otherwise falls back to the current device as before this PR. The notice can only fire on a complete scan, so its indices are real device indices. Added test_a_partial_scan_falls_back_to_the_current_device for both bf16 chains.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Chef's kiss.

Reviewed commit: dbb97c6afe

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

shimmyshimmer pushed a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Oct 15, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 855dde1778

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

shimmyshimmer pushed a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Oct 15, 2026
@danielhanchen
danielhanchen merged commit 2b72467 into main Oct 16, 2026
@danielhanchen
danielhanchen deleted the r7a-core-mixed-nvidia-caps branch October 16, 2026 04:58
danielhanchen added a commit to danielhanchen/unsloth-zoo-staging that referenced this pull request Oct 16, 2026
…ype, compile, memory and arch decisions (unslothai#1804)

## Problem

On hosts with more than one GPU, several zoo decisions read device 0, or
cached the first device's answer:

- **bfloat16 offload buffers:** in `gradient_checkpointing.py` the dtype
came from `get_device_capability()` of the current device only. An
Ampere device 0 beside a T4 or V100 gave bf16 buffers for layers on the
old card.
- **Inductor kill switch:** `OLD_CUDA_ARCH_VERSION` in `compiler.py`
looked at the current device only.
- **Tiled MLP and fused cross-entropy:** `tiled_mlp.py` read
`mem_get_info(0)`. Under DDP every rank opened a context on GPU 0, and
chunk sizes were budgeted from the wrong card.
- **AMD arch caches:** `_detect_gfx_arch`,
`get_amd_attention_implementation` and `get_amd_flash_attn_func` were
`functools.cache`d with no device argument. After
`torch.cuda.set_device(1)` on a host with two different AMD archs, the
first card's answer was reused.
- The rocminfo / hipconfig fallback took the first gfx in the output and
ignored `HIP_VISIBLE_DEVICES`.
- **llama.cpp GPU bundle:** `_detect_gpu_target` read device 0. An sm80
device 0 with an sm75 card beside it was offered an sm80-only bundle.

## Fix

- **New `_visible_cuda_capabilities()` in `device_type.py`:** returns
every visible device's capability. An unreadable card is skipped; the
readable ones include the current device, so a gate is never less strict
than before and still sees a known old card. bf16 offload buffers need
every visible card to be sm80+, and `OLD_CUDA_ARCH_VERSION` is set if
any visible card is pre-Turing. This matches what core does in
unslothai/unsloth#13923, so core and zoo agree on the dtype.
- **Tiled MLP and fused cross-entropy:** `_default_target_gb(device)`
reads free memory from the activations' device, otherwise the current
device. Fused cross-entropy passes the lm_head's device, and its cached
chunk multiplier is keyed on that device, so each GPU keeps its own
budget. `mem_get_info(0)` no longer appears in zoo.
- **AMD caches:** the three AMD helpers take an optional device and are
cached per HIP device index. With no argument they answer for the
current device, and on NVIDIA they never touch CUDA. If the runtime
cannot report the current device (outside compile), they fall back to
rocminfo / sdpa as before. The aiter attention patch and the compiled
SDPA rewrite pass `query.device`.
- The rocminfo fallback splits the output per GPU agent and maps the
device through `HIP_VISIBLE_DEVICES` / `CUDA_VISIBLE_DEVICES`, like
Studio's `_pick_rocm_gfx_target`. rocminfo is already ROCR-filtered, so
that mask is not applied again.
- **llama.cpp target:**
- **CUDA:** the target uses the lowest visible SM, and on a mixed host
only bundles covering every visible SM are offered. Homogeneous hosts
get the same tuple as before.
- **ROCm:** mixed bundle families fall back to the source build, which
already targets every visible arch. Shadowing iGPUs (Raphael, Phoenix
and the rest of Studio's `SHADOWING_INTEGRATED_GFX` list) are left out
of that comparison, and a current shadowing iGPU defers to the discrete
card (the installer's #7776 rule), so an RDNA3 card beside a Raphael
iGPU still gets its prebuilt.
- An unreadable card is skipped and the readable ones still count,
instead of giving up.
- On Windows, where llama.cpp source builds are CUDA only, a
mixed-family ROCm host keeps the current card's prebuilt, as before.

Homogeneous hosts are unchanged. The "any GPU is integrated" rule for
Tegra and gradient checkpointing double buffering is left as it is: it
is process-wide, and switching it to "all" would slow training on an
integrated GPU that sits beside a discrete one.

## Tests

- **New `tests/test_per_device_gpu_detection.py`, 42 tests, spoofed
devices:**
  - mixed capabilities in both orders;
  - `set_device` switches for the AMD caches (gfx942 to gfx1100);
  - the rocminfo mask mapping;
  - `mem_get_info` on the right device;
- the bundle target and coverage, including a shadowing iGPU and an
unreadable card;
  - a partial capability scan;
- fused cross-entropy budgeting the lm_head's device, and the aiter
getters asking for the query's device.
- **Base vs head:** 23 fail on main and pass here. The rest are
homogeneous guards, and cases where device 0 is already the weaker card.
- **37 related zoo test files** (gradient checkpointing, offload, tiled
MLP, cross entropy, llama.cpp prebuilt and cmake flags, AMD aiter,
compiler, temporary patches, NPU, driverless import): 793 passed, 18
skipped, 0 failed.
- **torch.compile:** `get_amd_flash_attn_func()` inside a
`fullgraph=True` compiled function gives 0 graph breaks.
danielhanchen added a commit to Imagineer99/unsloth that referenced this pull request Oct 16, 2026
## Problem

unslothai#13923 replaced `functools.cache(torch.cuda.get_device_capability)` with
a per-device wrapper, so a no-argument call follows
`torch.cuda.set_device`. On a host with one visible GPU that correctness
gain cannot apply, but every cache hit now runs Python code (resolve the
device, then a dict lookup) instead of the C-level `functools.cache`
hit. The attention helpers call `get_device_capability(Q.device)` on
every eager forward, so single-GPU runs pay a small cost for nothing.

Measured on the cache itself (CPU, 300k calls, best of 7):

| call | main before unslothai#13923 | after unslothai#13923 | this PR |
|---|---|---|---|
| `get_device_capability(Q.device)` | 0.073 us | 0.502 us | 0.096 us |

The last column is the same `functools.cache` object as before unslothai#13923;
the residual difference is timer noise.

## Fix

`_cache_device_capability` returns the plain `functools.cache` wrapper
when `torch.cuda.device_count() <= 1`, exactly what main had before
unslothai#13923. With one visible device every spelling (no argument, `0`,
`"cuda:0"`, `torch.device("cuda")`, `x.device`) names the same card, so
caching the call is exact. The per-device wrapper is kept for hosts with
two or more visible devices, where it is needed.

## Tests

- New `test_capability_cache_single_device_keeps_the_plain_cache`: a
one-device host gets a `functools.cache` object, probed once per
distinct argument, and re-wrapping does not stack.
- `tests/test_mixed_nvidia_capabilities.py`: 36 passed (the multi-device
cases still use the per-device wrapper).
- On one B200, `test_capability_cache_traces_in_fullgraph` (no argument,
`0`, `"cuda:0"`, `torch.device("cuda")`, `x.device` under
`fullgraph=True`): 5 passed.
- Related suites (bnb NF4 override, compile, context parallel, CE
eviction hints, pre-Volta fast inference, int4, fp8): 209 passed,
unchanged.
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Oct 25, 2026
… where the weights landed after loading (unslothai#14622)

## Summary
Follow-up to unslothai#13923 from a post-merge review. unslothai#13923 decided bfloat16
and the torch.compile switches from the weakest visible NVIDIA card. On
a mixed host (an RTX 4090 or A100 at index 0 next to a T4, V100 or GTX
10xx display card), with the model entirely on device 0:
- automatic dtype became float16 instead of bfloat16;
- an explicit `dtype = torch.bfloat16` was silently turned into float16;
- `TrainingArguments(bf16 = True)` raised, because the patched
`torch.cuda.is_bf16_supported()` answered False;
- a pre-Volta card anywhere in the visible set turned Dynamo off for the
whole process.

PyTorch answers bf16 for the current device (`torch/cuda/__init__.py`),
inductor rejects only graphs placed on an old card, ComfyUI decides per
device and vLLM only warns. Unsloth was stricter than all of them, which
cost bf16 and compile on hosts that never used the old card.

## What changes
- `SUPPORTS_BFLOAT16` answers for the current device, and the patched
`torch.cuda.is_bf16_supported()` returns torch's own answer again. An
explicit bf16 dtype is kept when the current card supports it. The
"visible GPUs lack bfloat16" import notice is gone.
- The pre-Volta and gfx906 compile switches read only the current device
(`cuda_current_capability()`, `hip_current_arch()`,
`arch_breaks_compile()`).
- New `check_mixed_gpu_placement(model, dtype)`, called right after the
Hugging Face load in `llama.py` and `vision.py`: weights on a pre-Volta
or gfx906 card turn Dynamo off before the first forward with a notice
naming the card (an explicit `TORCHDYNAMO_DISABLE=0` still wins); bf16
weights on a card without native bf16 get a warning, nothing changes
silently. One-GPU hosts and loads entirely on the current device do
nothing.
- The capability cache uses the plain `functools.cache` on single-GPU
hosts and on hosts whose cards share one capability; a mixed host fills
its per-card cache from one scan.
- Unchanged on purpose: the GRPO TMA options (still need every card
sm90+), the HIP gfx10 bf16 rule, XPU.

Pairs with unslothai/unsloth-zoo#1951 (LM head fusion follows the
current device); either can merge first.

## Tests
- `tests/test_mixed_nvidia_capabilities.py` (rewritten for the
current-device rule and the placement check): 42 pass here, 18 fail on
main. Spoofed `{0: (8, 9), 1: (7, 5)}` and `{0: (8, 9), 1: (6, 1)}` with
current device 0 keep bf16, explicit bf16 and Dynamo; current device 1
gives the old card's answers; a load placing layers on a pre-Volta
cuda:1 turns Dynamo off with a notice; homogeneous and single-GPU hosts
are identical.
- Related core suites (20 files): no new failures (one pre-existing
xformers attention dispatch failure on both sides).
- B200, base and head interleaved: SFT and MoE losses bit-identical,
same bf16 flag, dtype, generated text and grouped GEMM call count.

Not run on a real mixed-generation host (none available); proven with
spoofed capabilities.

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
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.

1 participant