Skip to content

[models] Report the missing backend per Attention Gym kernel - #5500

Merged
tianyu-l merged 2 commits into
pytorch:mainfrom
mkhilari:attn-gym-per-kernel-errors
Oct 19, 2026
Merged

tianyu-l merged 2 commits into
pytorch:mainfrom
mkhilari:attn-gym-per-kernel-errors

Conversation

@mkhilari

@mkhilari mkhilari commented Oct 18, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Follow up to #5467 (review point 2 there). The facade recorded backend import errors per attn_gym module, but every placeholder raised the first recorded error, so with, say, attn_gym.sparse failing on cutlass and the GDN modules importing fine, GDNKernel.Config().build() reported cutlass although GDN would have worked.

  • Exports of a module whose backend is missing now resolve to a _MissingKernel subclass carrying that module's error (one subclass per module, cached, named _MissingKernel[<attn_gym module>]). Calling it, .apply, or .from_fragments raises a fresh ModuleNotFoundError with that backend's name and message.
  • is_missing_kernel() (a TypeGuard) replaces the is not _MissingKernel identity checks in kda.py, gdn.py, linear_attention.py and cp_linear_attention.py, so the subclasses are also kept out of SPMD registration.
  • require_attn_gym(kernel, *kernels) checks the given exports and each module calls it from __init__ with every export it uses, so a build error names the backend that module needs: KDAKernel (chunk_kda, bound_gate, l2norm), GDNKernel (chunk_gdn, recurrent_gdn, l2norm), InnerKDA / InnerGDN (causal_conv1d), ContextParallelInnerKDA / ContextParallelInnerGDN (context_parallel_kda / context_parallel_gdn, context_parallel_conv_history, ContextParallelRouting, and l2norm for GDN). The zero argument form from [models] Let the attn_gym facade defer missing-backend import errors #5467, which raised on any error recorded so far, is gone.
  • No change when attn_gym is missing (the placeholders are the base class and raise the install hint) or when every backend imports.

Not in this PR: attn_gym resolves causal_conv1d and the other attn_gym.linear.short_conv exports lazily (attn_gym.linear._lazy) and raises a plain ImportError at attribute access, which _load_module never sees, so on a machine without cutlass gdn.py / kda.py still fail to import and 18 CPU test modules do not collect. I have that fixed on top of this branch and will open it next, the causal_conv1d checks here are what make it fail at build rather than at the first forward.

Test plan

tests/unit_tests/cpu/models/common/test_optional_imports.py:

  • new test_attention_modules_report_their_own_backend_at_build: a fake attn_gym whose modules all import except the broken ones. With attn_gym.linear.short_conv failing on cutlass, KDAKernel / GDNKernel build and InnerKDA, InnerGDN and their CP variants fail at build with cutlass, with the three context parallel modules failing on triton, the inner modules build and the CP variants fail with triton. Fails without the __init__ checks.
  • mixed case extended: …l2norm_fwd fails on triton and attn_gym.linear.kda.impl.fused on cutlass in one process, _L2Norm() raises triton, _ChunkKDA() / .apply raise cutlass, require_attn_gym(_ChunkKDA) raises cutlass, require_attn_gym(real, _L2Norm) raises triton, require_attn_gym(real, real) passes, the placeholder is named after its module.
  • broken backend case asserts the placeholders are subclasses and that none reached the SPMD registry.
  • existing [cutlass-*] build cases now go through require_attn_gym(kernels) and still see error.name == "cutlass".

On macOS without cutlass/triton, rebased on e61df55, 15 passed, tests/unit_tests/cpu/components/checkpointer 123 passed (2 known, meta-pytorch/torch_checkpointing#9), pre commit on all files passes every hook except pyrefly, which reports the same pre existing diagnostics as main in files this PR does not touch.

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

pytorch-bot Bot commented Oct 18, 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 18, 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 review

@claude

claude Bot commented Oct 18, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 1m 25s —— View job


Review: per-kernel backend errors for the attn_gym facade

The change is correct and fixes the problem it targets: when one attn_gym module fails on a backend, that failure no longer blocks kernels from other modules. Turning placeholders into per-module subclasses, cached in _BACKEND_KERNELS, is a small and clean way to do it. Switching to is_missing_kernel() everywhere also keeps the subclasses out of SPMD registration. I checked the whole repo outside tests/ and no is _MissingKernel identity checks are left. My comments are below, most important first.

1. The narrower build check lets CP backend failures through until forward (worth deciding on purpose)

ContextParallelInnerKDA / ContextParallelInnerGDN build KDAKernel / GDNKernel through InnerKDA / InnerGDN. Those now check only chunk_kda, bound_gate, l2norm or chunk_gdn, recurrent_gdn, l2norm. Their own kernels are not checked:

  • context_parallel_kda / context_parallel_gdn
  • context_parallel_conv_history and ContextParallelRouting (attn_gym.linear.context_parallel)
  • the short-conv exports

Before this PR, importing cp_kda.py touched context_parallel_kda at import time. So a backend failure there was recorded, and the old coarse require_attn_gym() raised at build. Now the build succeeds and the error only appears at the first forward, after model init, sharding and possibly checkpoint load. The error message is still correct; it just shows up later.

Suggestion: have each CP inner module call require_attn_gym(context_parallel_kda, context_parallel_conv_history, ContextParallelRouting) in its __init__ (same for GDN). Then the "fails at build" contract holds for CP too. If late failure on CP is acceptable, add a sentence to the PR description saying so.

Fix this →

2. Kernel lists are copied by hand from forward

attention/kda.py:74 and attention/gdn.py:223 restate which exports forward / prepare_inputs / _recurrent_gdn_fwd call. If someone adds a kernel call and forgets to update the list, nothing fails; the build check just gets weaker. I don't see an easy way to enforce this mechanically. At minimum, a short comment at each require_attn_gym(...) call ("must list every attn_gym export used by forward") would help reviewers catch drift.

3. Calling with zero arguments silently switches to the coarse check

require_attn_gym(*kernels) with no arguments means "fail if anything recorded so far failed", which is a different and stricter check. A caller passing an empty, computed tuple would get it without noticing. No production callers use the zero-argument form any more; only the test at test_optional_imports.py:299/441 does. Per CLAUDE.md's "no speculative" guidance, consider dropping the coarse branch and keeping one meaning. If it stays, the docstring should state the split more directly.

4. TypeGuard would remove the cast (nit)

from typing import TypeGuard

def is_missing_kernel(kernel: object) -> TypeGuard[type[_MissingKernel]]:
    return isinstance(kernel, type) and issubclass(kernel, _MissingKernel)

Then require_attn_gym can use kernel._error directly, and the cast import goes away.

5. Every subclass has the same name (nit)

type("_MissingKernel", ...) gives each per-module subclass the same __name__ / __qualname__ as the base, so reprs and tracebacks can't tell them apart. Something like f"_MissingKernel[{module_name}]", or a name that includes error.name, would make debugging easier. It costs nothing, since identity checks are gone.

6. Small points (fine as they are)

  • _raise_for(None) falling back to "first recorded backend error" is now only reachable through the zero-argument require_attn_gym(). The base _MissingKernel is only handed out when attn_gym is absent, and in that case _BACKEND_ERRORS is empty. If you drop the coarse branch (Add metrics to collect during training #3), this fallback can go too.
  • _BACKEND_ERRORS.setdefault combined with the cached subclass means a second export from the same failed module reuses the first error. That is the correct behaviour.
  • The tests are thorough. The mixed triton/cutlass case in a single process covers the original bug directly.

Not verified

I couldn't run pytest here because the command needed permission this job doesn't have. The review is based on reading the code only.

  • Read the PR diff and the full attn_gym.py
  • Audited callsites (kda, gdn, linear_attention, cp_linear_attention, cp_kda, cp_gdn, tests)
  • Posted review

@tianyu-l

Copy link
Copy Markdown
Contributor

@mkhilari could you address comments

@mkhilari

Copy link
Copy Markdown
Contributor Author

@mkhilari could you address comments

Thanks @tianyu-l for the review. Pushed a follow up commit addressing it:

  1. ContextParallelInnerKDA / ContextParallelInnerGDN now check the exports they call in __init__ (context_parallel_kda / context_parallel_gdn, context_parallel_conv_history, ContextParallelRouting, plus l2norm for GDN), and InnerKDA / InnerGDN check causal_conv1d, so every module keeps the fails at build contract. New test_attention_modules_report_their_own_backend_at_build covers both directions, with the CP modules broken the inner modules build and the CP ones fail with the CP backend, with short_conv broken the kernels build and the inner modules fail. It fails on the previous revision. InnerGDN only needs causal_conv1d on its packed sequence and CP paths (the no cu_seqlens path is pure torch), I kept one rule, check every export the module can call, rather than special casing that path, happy to narrow it if you prefer. The causal_conv1d checks only bite once the lazy export follow up lands, today a missing cutlass fails at import of kda.py / gdn.py, as the description notes.
  2. Every require_attn_gym call has a keep in sync comment.
  3. Dropped the zero argument form, require_attn_gym(kernel, *kernels). The first recorded error fallback in _raise_for went with it (your point 6).
  4. is_missing_kernel returns TypeGuard[type[_MissingKernel]], no cast.
  5. Placeholder subclasses are named _MissingKernel[<attn_gym module>].

Verified on macOS without cutlass/triton, test_optional_imports.py 15 passed, pre commit passes every hook except pyrefly, which reports the same pre existing diagnostics as main in files this PR does not touch.

@tianyu-l

Copy link
Copy Markdown
Contributor

@claude review again

@claude

claude Bot commented Oct 19, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 1m 38s —— View job


Re-review after f51e271

I have no blocking comments. All five points from the first review are addressed, and the new commit reads cleanly.

  • Read the diff (e61df55..HEAD)
  • Check how the earlier review points were addressed
  • Look for new issues
  • Post the review

Earlier points

# Point Status
1 CP failures surfaced only at forward ✅ ContextParallelInnerKDA / ContextParallelInnerGDN check their exports in __init__, and InnerKDA / InnerGDN check causal_conv1d. MRO is fine: CPInnerAttention has no __init__, so super().__init__(config) reaches InnerKDA / InnerGDN.__init__, which then builds the kernel. All three layers are checked, outermost first.
2 Kernel lists can drift from forward ✅ Each call has a keep-in-sync comment
3 Zero-argument coarse form ✅ Removed. The signature require_attn_gym(kernel, *kernels) makes an empty call a TypeError
4 TypeGuard ✅ No cast remains
5 Placeholder names ✅ Placeholders are named _MissingKernel[<module>]

Checks on the lists against actual call sites

  • KDAKernel: chunk_kda (forward), plus bound_gate and l2norm (prepare_inputs). Complete.
  • GDNKernel: chunk_gdn and l2norm (forward), and recurrent_gdn (inside _recurrent_gdn_fwd). Complete.
  • InnerKDA / InnerGDN: causal_conv1d, also reached through _causal_conv1d_varlen. Complete. Applying the rule uniformly, including the pure-torch no-cu_seqlens path in GDN, seems right to me. A model that can only build in some layouts would be surprising.
  • ContextParallelInnerKDA: context_parallel_conv_history (short_convolution), context_parallel_kda (kda_core), and ContextParallelRouting (via prepare_linear_attention_cp_metadata, which calls ContextParallelRouting.from_fragments). Complete.
  • ContextParallelInnerGDN: the same exports plus l2norm in gdn_core. Complete.
  • When attn_gym is not installed, the old _load_module("attn_gym") is None branch is no longer needed. Every export then resolves to the base _MissingKernel with _error = None, so require_attn_gym still raises the install hint.
  • No is _MissingKernel / is not _MissingKernel identity checks remain outside tests.

Remaining nits (optional)

  1. The CP case in the new test can't catch a dropped export. In the context_parallel parametrization, all three CP modules fail with the same backend (triton). Removing, say, context_parallel_conv_history or ContextParallelRouting from the cp_kda.py list would still pass, because context_parallel_kda raises triton first. To make each entry load-bearing, break one module per case and give each its own backend name. For example: attn_gym.linear.context_parallel → "backend_a" should fail both CP modules, and attn_gym.linear.kda.context_parallel → "backend_b" should fail only cp_inner_kda. This is the test-side half of point 2: the comment documents the contract, and this would enforce it.
    Fix this →
  2. The vLLM inner modules still fail late (out of scope, pre-existing). VLLMInnerKDA and VLLMInnerGDN (torchtitan/rl/generator/vllm/{kda,gdn}.py) call paged_chunk_kda, paged_causal_conv1d, causal_conv1d_decode, recurrent_*_decode, l2norm and bound_gate, but never call require_attn_gym. A missing backend therefore only shows up at the first generator step. They never had the check, so this PR doesn't regress them. It could go into the lazy-short_conv follow-up if you want the build-time guarantee to cover the generator too.

Not verified

I couldn't run pytest, because this job doesn't have permission for that command. This review is based on reading the code only.

@tianyu-l
tianyu-l merged commit efdde5e into pytorch:main Oct 19, 2026
tianyu-l pushed a commit that referenced this pull request Oct 24, 2026
…#5565)

## Summary

Follow up to #5467 and #5500. attn_gym resolves its backend backed
exports on first attribute access (`attn_gym.linear._lazy`),
`causal_conv1d`, `causal_conv1d_decode` and `paged_causal_conv1d` come
from `attn_gym.linear.short_conv`, which imports fine, only the
`getattr` imports `attn_gym.linear.short_conv.cute` and raises
`ImportError("causal_conv1d requires the optional CuTeDSL backend:
...")` chained from `ModuleNotFoundError(name="cutlass")`. #5467 only
deferred a `ModuleNotFoundError` raised by the module import itself, so
`gdn.py` / `kda.py` still failed to import on a machine without cutlass,
and with them everything that imports `torchtitan.models.common`, 18 of
the CPU test modules did not collect on macOS.

- `__getattr__` resolves exports through `_load_export`, an
`ImportError` whose cause is a backend's `ModuleNotFoundError` is
recorded under `"<module>.<export>"` and the export becomes a
placeholder carrying that error, exactly like an export of a module that
failed to import. A missing attn_gym module, or an `ImportError` that is
not a missing module, still raises at import.
- The install hint now names attn gym 0.0.17, the version
`.ci/docker/requirements.txt` pins (noted in the #5467 review).
- No change when every backend imports, `getattr` succeeds and nothing
is recorded.

On a machine without cutlass the models now import, `causal_conv1d` is a
placeholder, so `InnerKDA` / `InnerGDN` (which check it in `__init__`
since #5500) fail at build with the cutlass error instead of at the
first forward, and `KDAKernel` / `GDNKernel` still build when their own
backends import.

Also takes the optional note from the #5500 re review, the build test
now breaks one thing per case, so each entry of the `require_attn_gym`
lists is load bearing.

## Test plan

`tests/unit_tests/cpu/models/common/test_optional_imports.py`:

- New `test_attention_gym_lazy_exports_with_missing_backend`, a fake
`attn_gym.linear.short_conv` resolves `causal_conv1d` lazily and fails
on cutlass. `gdn` imports, `gdn.causal_conv1d` is a placeholder (not
`_MissingKernel` itself), calling it and
`require_attn_gym(causal_conv1d)` raise
`ModuleNotFoundError(name="cutlass")`, an `ImportError` chained from a
missing attn_gym module, and one that is not a missing module, still
raise and leave no placeholder. Fails without the facade change (the
`ImportError` escapes at import), passes with it.
- `test_attention_modules_report_their_own_backend_at_build` is
reparametrized over 11 cases, each breaking exactly one thing on a
backend of its own, the `attn_gym.linear.short_conv` module, or one of
the 10 exports the `require_attn_gym` lists name (`causal_conv1d`,
`chunk_kda`, `bound_gate`, `l2norm`, `chunk_gdn`, `recurrent_gdn`,
`context_parallel_kda`, `context_parallel_gdn`,
`context_parallel_conv_history`, `ContextParallelRouting`), broken
through the lazy export path. Each case asserts the placeholder is named
after what failed and exactly which of `KDAKernel`, `GDNKernel`,
`InnerKDA`, `InnerGDN`, `ContextParallelInnerKDA`,
`ContextParallelInnerGDN` fail at build. Dropping
`ContextParallelRouting` from the `cp_kda.py` list fails only the
`[ContextParallelRouting]` case, without the facade change the 10 export
cases fail and the module case passes.
- The two install hint asserts updated to 0.0.17.

On macOS 15 (attn-gym 0.0.17, no cutlass/triton), rebased on a4a62b3,
`pytest tests/unit_tests/cpu --collect-only` goes from 1371 tests
collected / 23 errors to 1640 / 5. The 18 errors fixed were all the
`causal_conv1d` `ImportError`, the 5 that remain are
`experiments/graph_trainer/paged_stash_memory_policy.py` importing
triton at module level (3) and an older `renderers` in my env (2),
neither touched here. Of the 18 modules, 16 run standalone, 210 passed,
2 fail for platform reasons (`qwen3_8` builds a model whose inner
modules need cutlass and gets the deferred cutlass error at build,
`test_lora_forward` runs torch.compile on CPU), the other 2
(`kimi_k3/test_kimi_k3_config.py`,
`recipes/test_debug_config_defaults.py`) hit the graph_trainer triton
import when run on their own. `test_optional_imports.py` 25 passed, pre
commit on both files passes every hook except pyrefly, which reports the
same pre existing diagnostics as main.
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.

2 participants