Skip to content

Pick the attention backend per device on mixed-generation multi-GPU hosts - #13698

Merged
danielhanchen merged 8 commits into
mainfrom
r6/attention-backend-per-device
Oct 14, 2026
Merged

danielhanchen merged 8 commits into
mainfrom
r6/attention-backend-per-device

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 14, 2026 •

Copy link
Copy Markdown
Member

Problem

The attention backend is decided from CUDA device 0 at import, then used for every layer, including layers a device_map places on another card. On a host whose GPUs are different generations:

  • Flash Attention 2: HAS_FLASH_ATTENTION is set when device 0 is sm_80+. With an Ampere card at index 0 and a Turing / Pascal card holding part of an auto / balanced / sequential split, every flash call on the older card raises FlashAttention only supports Ampere GPUs or newer.
  • xformers sm_120 probe: this probe also runs only on device 0. An RTX 50 card that is not device 0 keeps an xformers op it cannot run.
  • fp32 downcast: the fp32 limit (_XFORMERS_FP32_UNSUPPORTED) is read only from device 0.
  • HF path: attn_implementation="flash_attention_2" is likewise chosen from device 0, so a vision / FastModel load spread onto a pre-Ampere card fails the same way.

Unsloth already checks every visible device for the NF4 kernels and flex attention, and the ROCm bf16 gate does the same. ComfyUI decides per device (should_use_bf16(device), supports_fp8_compute(device)).

Fix

Per-device table. At import, _per_device_backends() builds one row per CUDA device: whether flash runs, whether xformers runs, whether xformers rejects fp32, and whether there are bf16 kernels.

  • It returns None unless the capability classes (sm80+, sm100+, sm120+) differ across devices. Single-GPU and same-generation hosts never consult the table and take exactly today's branch.
  • A secondary sm_120 card's xformers probe runs on the first dispatch on that card, not at import, so torchrun ranks never open a context on another rank's GPU. It is never taken inside a traced region.

run_attention. When the table exists, it re-checks the backend against Q.device:

  • Flash on a pre-Ampere card uses SDPA.
  • xformers on a card where it cannot run, or with bf16 Q on a pre-Ampere card, uses SDPA.
  • The fp32 downcast flag is read per device.
  • If the rerouted backend cannot apply an attention softcap the model needs (Gemma 2), it raises a clear error instead of training on wrong logits.
  • It only ever steps down from the device-0 choice, never up.

HF path. Before the text core is extracted, fall_back_from_flash_attention_on_pre_ampere(model) reads hf_device_map:

  • A placement counts only when an attention module runs there. That is each attention module's most specific map entry, or an entry inside one, such as q_proj alone. An lm_head or embedding alone on an older card changes nothing.
  • A bare cuda placement is the current device.
  • If attention lands on a CUDA card below sm_80, every flash_attention* config in the tree moves to one answer, decided before any write:
    • eager if any config is SDPA-excluded, softcapped or already on eager, or if any tower class has no SDPA;
    • otherwise sdpa.
  • It prints why. Same-generation hosts never walk the modules.

Unchanged on purpose.

  • SUPPORTS_BFLOAT16 and the pre-Volta compile guard still read device 0. Taking the minimum over every visible card would downgrade people who only use device 0 of a mixed host, so that needs a load-time design of its own.
  • When device 0 cannot run xformers, the other cards stay on SDPA, as today.

Tests

New tests/utils/test_attention_dispatch_mixed_devices.py (33 cases, 2 need CUDA)

  • Dispatch, with capabilities mocked per device:
    • a homogeneous host gets no table and no probe;
    • sm_86 + sm_75 reroutes flash and bf16 xformers only on the older card;
    • sm_120 at index 1 is probed lazily, and never while tracing;
    • the fp32 flag is per device;
    • the softcap error.
  • HF fallback:
    • which placements count: attention only, fine-grained q_proj, hierarchical maps, bare cuda, CPU / disk offload;
    • SDPA-excluded, softcapped (incl. a T5Gemma-shaped child), eager-only (Donut-shaped) and no-SDPA towers.

Base vs this branch

  • 29 test files that touch attention selection: 506 passed / 258 skipped on both sides (CPU).
  • A broader 43-file run gave 5 failed / 851 passed / 138 skipped on both sides, with identical failing IDs (pre-existing).
  • On a B200 through the GPU queue, the new file gives 33 passed.
  • Staging (ubuntu-latest, macos-15, windows-latest with torch, transformers, peft, trl and unsloth-zoo) is green, with 31 passed / 2 skipped on each OS.

Compile and parity

  • torch.compile(fullgraph=True) over run_attention gives 0 graph breaks, both without a table and with an injected mixed table.
  • A tiny Llama and a tiny Qwen3 LoRA forward + backward give bit-identical loss and grad norm on base and on this branch.

Not covered

No real mixed-generation pair was available. The rerouting is tested with mocked per-device capabilities, plus real CUDA tensors with an injected table.

…osts

Flash Attention, the xformers sm_120 probe and the xformers fp32 limit were read from device 0
and applied to layers a device_map places on other cards. On a mixed host (e.g. sm_86 + sm_75)
flash then raised on the older card. run_attention now re-checks the backend against Q's device
from a per-device table that only exists when cards differ, and the HF path falls back from
flash_attention_2 when the loaded device map reaches a pre-Ampere card.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 14, 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-14T13:35:21.287601Z f1a6885 Manual request
🔒 Security Review ⚠️ Failed 2026-10-14T09:13:14.342442Z e2bc1a6 PR opened
ℹ️ 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

danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Oct 14, 2026

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

ℹ️ 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/_utils.py Outdated
pre_ampere = _pre_ampere_cuda_devices(getattr(model, "hf_device_map", None))
if not pre_ampere:
return False
fallback = "sdpa" if getattr(type(model), "_supports_sdpa", False) else "eager"

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Keep known-broken SDPA models on eager fallback

When an explicitly requested Flash Attention 2 model such as Gemma 3 is split onto a pre-Ampere GPU, this check selects sdpa solely from the class flag and bypasses _is_sdpa_excluded and _declares_no_sdpa, even though the existing resolver deliberately forces Gemma 3's known-wrong SDPA implementation to eager. The new fallback can therefore replace a clear Flash Attention failure with incorrect attention results; apply the same model-specific SDPA eligibility checks used by resolve_attention_implementation.

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 fb2a67b: the fallback now applies the resolver's SDPA eligibility per config: the class flag, _declares_no_sdpa and _is_sdpa_excluded(model_type). A model whose SDPA is known to be wrong goes to eager, not sdpa. Tested with gpt_oss.

Comment thread unsloth/models/_utils.py Outdated
Comment on lines +1623 to +1625
for placement in device_map.values():
if isinstance(placement, int):
indices.add(placement)

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 Ignore pre-Ampere placements with no attention layers

When a device map puts only a non-attention module such as lm_head or the input embedding on a pre-Ampere card while all decoder attention blocks remain on Ampere, collecting every placement here still causes the helper to rewrite every Flash Attention config to SDPA/eager. Flash Attention would never execute on the older card in that layout, so this unnecessarily removes it from all capable layers and can substantially slow the model; the fallback should be triggered only by placements that cover attention-bearing modules.

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 fb2a67b: only device-map entries whose module subtree holds an attention module count, so an lm_head or embedding on a pre-Ampere card leaves Flash Attention on the rest. An entry that cannot be resolved still counts, to stay safe. Tested.

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

ℹ️ 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/vision.py Outdated
_cast_text_only_prequantized_params(model, torch_dtype)
# transformers 5 leaves remote code's non-persistent buffers (RoPE inv_freq, decay slopes) uninitialised.
restore_remote_code_non_persistent_buffers(model)
fall_back_from_flash_attention_on_pre_ampere(model)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Preserve the device map when extracting the text core

In FastBaseModel's text-only composite path, this runs after _text_trainable_core has replaced the loaded wrapper with its child core. _carry_loader_state_to_core does not transfer or remap the wrapper's hf_device_map, so _pre_ampere_cuda_devices sees no map and leaves Flash Attention enabled when that core's attention layers were dispatched to a pre-Ampere GPU. Such models still fail on their first Flash Attention forward; run the fallback before extracting the core or carry the relevant map onto it.

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 303e4e1: the flash fallback now runs on the loaded wrapper, which still carries hf_device_map, before _text_trainable_core extracts the text core. The core shares those config objects, so it keeps the rewritten attention implementation.

Comment thread unsloth/models/_utils.py Outdated
module = model.get_submodule(name) if name else model
except Exception:
return True
return any("attention" in type(m).__name__.lower() for m in module.modules())

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 Check attention ancestors for fine-grained device maps

With a valid fine-grained map that assigns entries such as ...self_attn.q_proj, k_proj, v_proj, and o_proj to a pre-Ampere GPU, each resolved subtree is only a Linear, so this test reports that none holds attention. The Q/K/V tensors—and therefore the parent attention computation—can still reside on that GPU, but its index is omitted and Flash Attention remains enabled until it fails at runtime. The check should also recognize mapped modules whose ancestors are attention modules.

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 303e4e1: a device-map entry also counts when one of its ancestors is an attention module, so a fine-grained map that places q_proj / k_proj / v_proj alone on a pre-Ampere card triggers the fallback. Tested.

Comment thread unsloth/models/_utils.py Outdated
impl = _config_get(config, "_attn_implementation", None)
if isinstance(impl, str) and impl.startswith("flash_attention"):
model_type = (_config_get(config, "model_type", "") or "").lower()
fallback = "sdpa" if class_sdpa and not _is_sdpa_excluded(model_type) else "eager"

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Keep softcapped models on eager fallback

When a native softcapped model such as Gemma 2 is loaded through FastBaseModel and an attention layer reaches a pre-Ampere GPU, its class advertises SDPA support and its model type is not excluded, so this selects sdpa. That backend does not apply the model's attention-logit softcap, silently changing logits and gradients; fresh evidence in the current tree is _configured_softcap in attention_dispatch.py, which explicitly documents that SDPA cannot reproduce softcapping and raises rather than making this swap. Detect attn_logit_softcapping here and use eager instead.

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 303e4e1: a config with attn_logit_softcapping set falls back to eager, not sdpa, so Gemma 2's softcap is kept exact. Tested.

Comment thread unsloth/utils/attention_dispatch.py Outdated
Comment on lines +95 to +96
if xformers_ok and index > 0 and not flash and capability[0] >= 12:
xformers_ok = probe(f"cuda:{index}", supports_bf16 = True)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Avoid probing every secondary GPU during import

When Flash Attention is absent and xFormers is installed on a multi-GPU sm_120 host, this import-time loop allocates a tensor and synchronizes every secondary GPU before ultimately discarding the table as homogeneous. Under torchrun, where every rank commonly sees every GPU, each process therefore initializes CUDA contexts and allocator state on all peer GPUs; those contexts persist and can consume enough memory to prevent the owning ranks from loading their models. Reuse the already completed device-0 result for homogeneous capabilities or probe a secondary device lazily only when attention actually reaches it.

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 303e4e1: the table is skipped before any probe when every card is in device 0's capability class (sm >= 8 / >= 10 / >= 12), so a homogeneous multi-GPU host, sm_120 included, never touches a secondary GPU at import. Only a mixed host probes, and only its sm_120 cards that differ from device 0. Tested.

… count, softcapped models stay on eager, no probe on same-class cards
@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: 303e4e1ef7

ℹ️ 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/_utils.py Outdated
Comment on lines +1682 to +1684
sdpa_ok = class_sdpa and not _is_sdpa_excluded(model_type) and not softcap
fallback = "sdpa" if sdpa_ok else "eager"
_write_attn_impl(config, fallback)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Evaluate child configs before rewriting the composite

For a composite whose root config has no softcap but declared children do, such as T5Gemma with softcapped encoder/decoder configs, model.modules() visits the root first and selects sdpa; assigning it through _write_attn_impl invokes Transformers' recursive _attn_implementation setter and changes those children to sdpa, so their later iterations are skipped because they are no longer marked as flash. Fresh evidence in the current tree is this scalar parent write despite the per-config softcap check: on a mixed-device T5Gemma load it bypasses the intended eager fallback and SDPA silently omits the children's attention-logit softcap, changing logits and gradients. Determine child fallbacks before mutating the parent, or preserve them with a per-subconfig mapping.

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 201f266: the fallback now gathers every config (module configs plus declared sub_configs) and decides one answer before writing anything: sdpa only when the class supports it and no config is SDPA-excluded or softcapped, otherwise eager for the whole tree. A composite's recursive setter therefore cannot carry a softcapped child onto sdpa. T5Gemma-shaped test added.

@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: 201f266751

ℹ️ 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/utils/attention_dispatch.py Outdated
xformers_ok = HAS_XFORMERS
# Device 0 was probed above; xformers only serves another sm_120 card when flash cannot.
if xformers_ok and index > 0 and not flash and capability[0] >= 12:
xformers_ok = probe(f"cuda:{index}", supports_bf16 = True)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Probe secondary xFormers devices lazily

On a mixed host with xFormers but no Flash Attention—for example, Ampere at cuda:0 and an sm_120 card at cuda:1—this still runs the probe on the secondary GPU during module import. Under torchrun, every process commonly sees the full device set, so every rank initializes a persistent CUDA context and allocator state on cuda:1, consuming memory needed by its owning rank and potentially preventing model loading. Fresh evidence after the homogeneous-host fix is that the current branch still calls probe("cuda:1", ...) eagerly whenever capability classes differ; defer this probe until attention is actually dispatched to that device.

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 0cc4c14: import now leaves that cell unknown, and the probe runs on first dispatch of xformers to that card, cached per index. Import therefore opens no context on another rank's GPU, and a rank that never sends attention there never probes it. Inside a traced region it does not probe and takes SDPA for that call. Tested.

@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: 0cc4c14af8

ℹ️ 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/_utils.py Outdated
continue # "cpu" / "disk" offload
if device.type != "cuda":
continue
index = device.index or 0

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Resolve indexless CUDA placements to the current device

When hf_device_map contains the valid placement "cuda" or torch.device("cuda"), its missing index denotes the current CUDA device, not device 0. Treating it as zero can miss a pre-Ampere placement when a framework changes the current device after Unsloth was imported—for example, import on Ampere cuda:0, select Turing cuda:1, then load with {"": "cuda"}—so Flash Attention remains enabled and fails on the first forward. Use torch.cuda.current_device() when device.index is None.

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 f1a6885. A bare cuda placement (string or torch.device) now resolves through torch.cuda.current_device() instead of 0. Test: test_bare_cuda_placement_reads_the_current_device (current device Ampere keeps flash, current device Turing falls back).

Comment thread unsloth/models/_utils.py Outdated
ancestors = [model.get_submodule(".".join(parts[:i])) for i in range(1, len(parts))]
except Exception:
return True
return any("attention" in type(m).__name__.lower() for m in (*ancestors, *module.modules()))

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 Respect child overrides in hierarchical device maps

For a hierarchical map such as {"": 1, "model.layers": 0}, where cuda:1 is pre-Ampere, the root entry's subtree structurally contains attention modules even though the more-specific child entry places every attention layer on cuda:0. _holds_attention therefore reports cuda:1 as attention-bearing and the caller rewrites the whole model to SDPA/eager unnecessarily. Determine whether any attention module's effective longest-prefix placement is this entry rather than counting all modules below the mapped name.

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 f1a6885. The check now works from the attention modules: each one counts the placement of its longest-prefix device-map entry, plus any entry inside it (a fine-grained q_proj placement). {"": 1, "layers": 0} with every attention layer under layers keeps flash; {"": 1, "lm_head": 0} still falls back. Modules are only walked when some placement is actually pre-Ampere, so same-generation hosts skip it. Test: test_hierarchical_maps_follow_the_most_specific_entry.

Comment thread unsloth/models/_utils.py Outdated

# One answer for the whole tree, decided before any write: a composite's setter recurses into
# its children, so a parent rewritten to sdpa would carry a softcapped child with it.
changed = "sdpa" if class_sdpa and all(_sdpa_ok(c) for c in configs) else "eager"

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Preserve eager-only child configurations during fallback

For a composite with a flash-capable root but an eager-only child—such as the VisionEncoderDecoderModel/DonutSwin case already handled by _flash_unsupported_sub_configs—the root class can advertise SDPA while the child explicitly does not. _sdpa_ok checks only model-type exclusions and softcapping, so this chooses sdpa; writing that value to the root recursively overwrites the child's intentional eager setting and can route the child through an unsupported or incorrect implementation when any attention placement reaches a pre-Ampere GPU. Include each child model class's _supports_sdpa result when choosing the tree-wide fallback, using eager if any child requires it.

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 f1a6885. The tree-wide answer is eager when any config is already on eager (the DonutSwin tower set by _flash_unsupported_sub_configs) or when any PreTrainedModel in the model has no SDPA support, so the recursive root write can no longer move an eager-only child to SDPA. Tests: test_hf_fallback_keeps_an_eager_only_tower_on_eager, test_hf_fallback_reads_sdpa_support_of_every_tower.

table = []
for index, capability in enumerate(capabilities):
flash = HAS_FLASH_ATTENTION and capability[0] >= 8
xformers_ok = HAS_XFORMERS

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 Retain xFormers availability independently per device

On a host without Flash Attention where cuda:0 is an sm_120 card whose xFormers probe fails and cuda:1 is an Ampere card, the import-time probe sets the global HAS_XFORMERS to false. Copying that global result into every row marks xFormers unavailable on the Ampere card too; moreover, select_attention_backend then chooses SDPA up front, so _backend_for_device never gets an opportunity to correct the decision. This unnecessarily routes supported secondary devices through the slower and potentially much heavier packed-SDPA path. Track package availability separately from device 0's probe result and determine xFormers support for each device.

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.

Leaving this as is. When device 0 is an sm_120 card whose xformers probe fails, main already turns xformers off for the whole process and runs SDPA everywhere, and this PR keeps that. SDPA is valid on every device, so nothing breaks. Picking xformers for a secondary card when device 0 cannot run it would mean choosing a different backend (and building a different mask) per layer, which is a speed change rather than the crash this PR fixes. Here the per-device table only steps down from the device-0 choice, never up.

…ice-map entry wins, eager-only towers keep eager
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Already looking forward to the next diff.

Reviewed commit: f1a6885238

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

@danielhanchen
danielhanchen merged commit 77245f1 into main Oct 14, 2026
@danielhanchen
danielhanchen deleted the r6/attention-backend-per-device branch October 14, 2026 16:29
Stanley00 pushed a commit to stanley-fork/unsloth that referenced this pull request Oct 16, 2026
…DIA GPU on mixed hosts (unslothai#13923)

## 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 (unslothai#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 unslothai#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.

---------

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