Skip to content

Handle unavailable FlashAttention backends safely - #5546

Merged
tianyu-l merged 5 commits into
pytorch:mainfrom
janbernloehr:jbernloehr/fix-flash-attention-fallback
Oct 24, 2026
Merged

tianyu-l merged 5 commits into
pytorch:mainfrom
janbernloehr:jbernloehr/fix-flash-attention-fallback

Conversation

@janbernloehr

Copy link
Copy Markdown
Contributor

Fixes #5536.

Default Varlen attention currently activates FA3 on Hopper and FA4 on Blackwell without checking whether the corresponding wheel is installed. With a missing wheel, model construction raises ModuleNotFoundError, including for models that can use PyTorch's built-in FA2.

This change checks backend availability and uses FA2 with a warning when the architecture's wheel is absent. Outer attention constructors validate the head dimensions through a shared inner-attention interface. DeepSeek-V3 and Kimi K3 MLA configurations with unequal Q/K and V dimensions fail during construction with the detected SM, dimensions, and required module in the error message. Flex attention remains available for these layouts.

Backend activation is shared between training and the vLLM generator. Existing activation is reused, and broken installations retain their original exception as the cause of an actionable error instead of silently falling back. Architecture selection stays within PyTorch's supported families: Hopper uses FA3 and Blackwell uses FA4; a missing FA4 wheel does not select FA3 on Blackwell, and later SM families are not assumed to support FA4.

The change does not alter attention arithmetic, model parameters, or checkpoint keys. The new fallback can change numerical results relative to FA3/FA4, so it emits a warning.

Numerical evidence

Compared the fallback with explicit PyTorch FA2 on an NVIDIA L4 using PyTorch 2.14.0a0+4fdf77b940.nv26.08, CUDA 13.4, BF16 inputs, seed 42, and strict deterministic algorithms. The input has two packed sequences of 32 tokens, four heads, and head dimension 64. Backend selection and missing-wheel discovery are simulated for FA3 and FA4; attention forward and backward run on the real CUDA device.

Missing wheel Execution Max output difference Loss difference Max Q/K/V gradient difference
FA3 Eager 0 0 0
FA3 torch.compile(fullgraph=True) 0 0 0
FA4 Eager 0 0 0
FA4 torch.compile(fullgraph=True) 0 0 0

All four comparisons passed with atol=0, rtol=0. Each produced attention loss 0.19502778351306915 and combined input-gradient L2 norm 0.012680011801421642.

Reproduce the comparisons with:

python -m pytest tests/unit_tests/gpu/models/common/test_varlen_attention.py \
  -k backend_setup_matches_explicit_backend -vv

The two installed-FA3/FA4 cases were skipped on L4; actual Hopper/Blackwell backend execution is not covered by these results. The test now runs the missing-wheel comparisons on the default A10 GPU CI runner as well.

Full-training loss and optimizer grad_norm comparisons were not run. This patch changes backend setup and constructor validation, while leaving attention forward code unchanged; the focused comparison checks the new fallback's output, loss, and every input gradient against its intended backend. A training convergence rerun would add little evidence for this setup change. Cross-backend bitwise equality is not expected.

@pytorch-bot pytorch-bot Bot added ciflow/fake-pg Run 1-GPU Fake PG integration tests ciflow/rl labels Oct 19, 2026
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Oct 19, 2026
@pytorch-bot

pytorch-bot Bot commented Oct 19, 2026 •

Copy link
Copy Markdown

Workflows were awaiting approval. CI has now been triggered for the ciflow labels on this PR.

@pytorch-bot

pytorch-bot Bot commented Oct 19, 2026

Copy link
Copy Markdown

The following ciflow label(s) have been added but CI has not been triggered yet because the workflows are awaiting approval:

  • ciflow/rl
  • ciflow/fake-pg

Once a maintainer approves the workflows (scroll to the bottom of the PR page), the corresponding CI jobs will be triggered automatically. Please ping one of the reviewers if you do not have access to approve and run workflows.

@tianyu-l

Copy link
Copy Markdown
Contributor

@claude 450 LoC PR for a safety check sounds insane -- what's going on

@claude

claude Bot commented Oct 19, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 53s —— View job


Why it's ~450 LoC

The fix for #5536 needs about 15 lines. The rest of the PR is three other changes plus tests for them.

Bucket +LoC Needed for #5536?
Tests (test_tools_utils.py, two test_varlen_attention.py, bitwise parity) ~320 Partly. A CPU test that mocks find_spec is enough
tools/utils.py: new _cuda_flash_attention_backend, activate_cuda_flash_attention, validate_flash_attention_head_dims ~95 About 15 lines of it
New InnerAttention.validate_head_dims interface, called from 9 outer-attention constructors in 8 files ~30 No
vLLM generator moved onto the shared helper net −17 Optional cleanup

What goes beyond the fix

  1. A new validate_head_dims contract on InnerAttention. It adds a base-class method and calls it from GQA, DSv3, DSv4, Kimi K3, gpt_oss, qwen3_5, flux (3 sites) and vLLM. Six of those nine calls pass validate_head_dims(head_dim, v_head_dim=head_dim), which can never fail. Only the two MLA models (and vLLM's diff-KV path) have unequal dims.
    • This is a separate feature: "MLA + varlen on FA2 should fail at construction". That was already true on A100/L4 before this PR, so it has nothing to do with a missing wheel.
    • It also conflicts with CLAUDE.md add AC/selective AC to the model #7 (no speculative defensive checks). Without it, PyTorch's FA2 kernel raises its own error at forward time.
  2. Detecting broken installs. get_cuda_flash_attention_impl parses ModuleNotFoundError.name to tell "package missing" from "a dependency of the package is missing". That edge case adds a lot of branching.
  3. Behavior change in architecture selection. It replaces has_cuda_capability(10, 0) with an exact-major lookup {9: FA3, 10: FA4}. As a result, SM 11.x/12.x (e.g. consumer Blackwell RTX 50xx) no longer select FA4 even when the wheel is installed. This silently changes behavior for existing users. It is a reasonable change to discuss, but it belongs in its own PR.
  4. Repeated checks. torch.cuda.is_available() or torch.version.hip appears 3 times. activate_cuda_flash_attention calls _cuda_flash_attention_backend() and then get_cuda_flash_attention_impl(), which calls it again.

What the minimal fix looks like

Return None (so the caller stays on FA2) when the wheel isn't importable, and warn once. Both existing callers (VarlenInnerAttention.__init__ and the vLLM impl) already handle None:

def get_cuda_flash_attention_impl() -> str | None:
    if torch.version.hip is not None:
        return None
    if has_cuda_capability(10, 0):
        impl, module = "FA4", "flash_attn.cute"
    elif has_cuda_capability(9, 0):
        impl, module = "FA3", "flash_attn_interface"
    else:
        return None
    try:
        found = importlib.util.find_spec(module) is not None
    except ModuleNotFoundError:  # parent package `flash_attn` missing
        found = False
    if not found:
        warn_once(logger, f"{impl} not installed ('{module}'); falling back to FA2.")
        return None
    return impl

Add one CPU unit test that patches has_cuda_capability/find_spec, and the whole PR comes to roughly 40–60 LoC.

Recommendation

Cut this PR down to the snippet above plus a small test. If the MLA head-dim error and the SM≥11 FA4 policy are wanted, open each as its own PR so the change in item 3 gets its own review.

Comment thread torchtitan/tools/utils.py Outdated
Comment on lines +60 to +62
if not found:
warn_once(logger, f"{impl} not installed ('{module}'); falling back to FA2.")
return None

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

can we error out -- we don't want people to implicitly get bad perf and think it's because of torchtitan

@tianyu-l
tianyu-l merged commit 89e4339 into pytorch:main Oct 24, 2026
25 checks passed
tianyu-l added a commit that referenced this pull request Oct 29, 2026
… route PRs to area experts (#5667)

## Why

PR volume has outgrown review capacity. Of the 1,429 PRs merged since
April, one maintainer approved 1,066 (75%), and October alone had 351
merged PRs. Many PRs are agent-generated, and the agents (and `@claude`)
follow `.claude/CLAUDE.md`, which in several places contradicts how PRs
are actually reviewed:

- Principle 5 says to flag BC breakage. The maintainers deliberately
don't promise BC.
- config.md says "emit a warning" when config is silently skipped.
Review comments almost always say "just error out".
- PR expectations say "new features need CPU unit tests at minimum". In
~1,000 reviews the maintainer almost never asked for a new unit test,
and often asked for tests to be removed or folded into existing ones.

The result: across 130 PRs, the current `@claude` cited CLAUDE.md at
least 38 times, mostly to escalate. That produced 16+ BC concerns, 9+
"add a warning" suggestions and 23+ test requests. It also missed the
most common real review question: should this change exist in this form
at all?

This PR rewrites the rules from what reviewers actually say. The source
data:
- 3,391 inline comments, 289 review bodies and 383 PR comments from
Jul-Oct 2026.
- 48 refactor PRs, used to extract structural preferences.
- A comparison of 196 `@claude` runs against the human review on the
same PRs.

It then adds a torchtitan review skill, builds on PyTorch's `pr-review`
skill, and routes PRs to area experts without making them blocking
owners.

**Example: one past PR, as reviewed by the new skill** (#5546, at the
commit that was originally reviewed; blind, with no access to the real
comments):

```
Verdict: Request changes -- The problem is real, but the fix swaps a hard error for a
warn-and-continue fallback to FA2 ... It also adds a head-dim hook to 9 call sites,
7 of which can never fire.
Must fix
1. torchtitan/tools/utils.py:95-104 -- a missing wheel on Hopper/Blackwell now means a
   warning plus a silent switch to a slower kernel with different numerics ...
   Smallest fix (~15 lines): ... raise a clear error that names the module to install.
```
The human review of that PR: "450 LoC PR for a safety check sounds
insane" and "can we error out -- we don't want people to implicitly get
bad perf".

## What changed

**1. Rules** (`.claude/CLAUDE.md`, `.claude/rules/`):
- Core principles rewritten:
  - start from the problem, not the patch;
  - minimal by default;
  - PyTorch-native and upstream first;
  - reuse, but don't bend shared code for one consumer;
  - keep core oblivious to features;
- no BC promises, but protect numerics, HF loading, metric keys and
main-path perf;
  - raise instead of warn;
  - hardware-agnostic.
- Naming additions: overloaded terms, one name per concept, `_private`.
- PR expectations: descriptions must convince a human; tests must earn
their cost; one concern per PR.
- `config.md` rewritten:
  - each component owns its `X.Config`;
  - select implementations by config type;
  - `X.Config | None` instead of `enable_*`;
  - no post-hoc config mutation;
  - few knobs;
  - validate in `__post_init__`.
- `distributed.md`: spmd_types first, parallelism combinations, hidden
D2H syncs, hardware.
- New rules files:
  - `design.md`: structural rules distilled from past refactors.
- `tests.md`: when to add tests, preferring extensions of existing
coverage, placement, golden files.
- `direction.md`: current migrations. This needs maintainers to keep it
current.

**2. `pr-review` skill** (`.claude/skills/pr-review/`):

| Step | What it does |
| --- | --- |
| Context | Applicable rules, maintainer comments addressed or not,
earlier bot findings, overlapping open PRs. |
| Necessity/design gate | Is the problem real on main? Root cause vs
symptom? Right layer, or upstream? Should torchtitan own this?
Superseded? Smallest alternative? Value evidence? |
| Deep review | A quick sweep of every hunk (scope, placement, new knobs
and tests), then the checklist, split by lens for large PRs. |
| Consolidate and fact-check | Dedupe by root cause and fix; drop BC,
"add a warning", generic "add tests", lint and praise; verify must-fix
items. |
| Output | Verdict first, plain-words summary, a concrete before/after
example, at most a few must-fix items, details collapsed, unverified
claims labeled. |
| Modes | Full review, "review again" (only the delta), "review my
review", or answer a specific question first. |
| Posting | Line-anchored findings as inline comments (with `suggestion`
blocks for small fixes, at most ~10, posted only by the main agent after
fact-check), then one formal review via `gh pr review` (`--approve` /
`--request-changes` / `--comment`) with the verdict and one-line
pointers. |

**3. PR descriptions:**
- `pr-description` skill and `.github/pull_request_template.md`: Why
(with a simple example) -> What changed -> user-facing before/after ->
numerics -> testing.
- CONTRIBUTING.md updated to match.

**4. `@claude` workflow** (`claude-code.yml`):
- Always uses the skill.
- Allows read-only `gh issue view` / `gh pr view` / `gh pr diff` / `gh
pr list`, plus `gh pr review` and the action's inline-comment tool (it
cannot approve). `gh api` stays blocked.
- `effort=low|max` and `fable` comment keywords; default effort `high`.
- 55-minute timeout.

**5. Review routing:**
- `CODEOWNERS`:
- `*`: `tianyu-l` `fegin` `wwwjn` `shuhuayu` `acisseJZhong`
`felipemello1`.
- graph_trainer paths: core plus `SherlockNoMad` `aditvenk`
`sanketpurandare`.
  - torchft paths: core plus `d4l3k`.
- Every path has an owner, so a bot approval can never satisfy branch
protection on its own.
- `.github/area_reviewers.yml` and `workflows/area_reviewers.yml`
request at most 3 area experts as non-blocking reviewers, based on which
areas the changed files touch. The workflow runs on
`pull_request_target`, reads only the file list through the API, and
never checks out PR code.

## Alternatives considered

- **Copy PyTorch's skill as-is.** Its "missing tests -> Request Changes"
and BC section are exactly what produced noise here.
- **PyTorch-style per-directory `REVIEW.md` files.** The existing
glob-scoped `.claude/rules/` already do this, without more `.md` sprawl.
- **Deterministic lint hooks** for `torch.cuda.*`, `isinstance(..,
DTensor)` and `enable_*` fields. Every pattern already has hits on main
(12, 15 and 7 files), so they would need allowlists. The skill checks
them on the diff instead.
- **Making area experts code owners.** That makes them blocking;
auto-requesting reviews routes PRs without adding gates.

## Testing

**Backtest.** The new skill reviewed 7 past PRs blind, each at the
commit that was originally reviewed, and the output was compared with
the real human review. The skill was then fixed for the misses, and the
affected cases were re-run.

| PR | Human review's main point | New skill |
| --- | --- | --- |
| #5546 | too big for a safety check; error out | Hit both |
| #5153 | does this happen on main? don't violate the `nn.Module`
contract | Hit; proposed the fix that eventually landed |
| #4754 | workaround, not a fix; move the test | Hit the root cause (the
same fix the author later proposed); missed the test move, now covered
by the sweep |
| #5463 | motivation first; `LocalCompileConfig` design | Hit the design
and unused kwargs; motivation is a must-fix after the re-run |
| #5183 | NCCL-specific knob in core; TODO; `<0` semantics | Hit |
| #4474 | approve; DSv4 should fix the model/loss | Approve; partly
raised the model point |
| #4421 | approve; "how much e2e?" | Originally requested changes;
approves with items after the re-run |

None of the 10 reviews raised BC or asked for a warning.

**Other checks:**
- **Reviewer routing:** the area-reviewer logic was replayed on 1,429
merged PRs. Peak load is about 50 requests/month per person (graph
trainer, PP, MoE).
- **Workflow script:** dry-run with mocked GitHub objects on a real PR's
file list. The author is excluded, existing reviewers are skipped, and a
non-collaborator failure doesn't fail the run.
- **YAML and lint:** all YAML parses, the inline JS passes `node
--check`, and `pre-commit` passes.

## Known issues / follow-ups

- Comment-triggered workflows run from `main`, so `claude-code.yml` and
the skill only take effect after merge. Try `@claude review` on a real
PR right after.
- Not verified: whether the Claude GitHub App has write access. If it
does, its approvals count toward the 1 required approval (but never as a
code-owner approval), and its REQUEST_CHANGES blocks merging until it
re-approves or someone dismisses it. If it doesn't, its reviews are
advisory. The first real review will show which.
- `direction.md` and `area_reviewers.yml` are only useful if they are
kept current.
- Not included:
- PyTorch's time-budget hook (reviews that hit the 55-minute limit are
lost);
- auto-review on every push, which needs the PyTorch CI owners' hardened
setup.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/fake-pg Run 1-GPU Fake PG integration tests ciflow/rl CLA Signed This label is managed by the Meta Open Source bot.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

get_cuda_flash_attention_impl() selects FA3/FA4 by compute capability alone, so attention init raises ModuleNotFoundError when the wheel is absent

2 participants