Skip to content

Make the KDA attention import optional - #5181

Closed
githubsgi wants to merge 1 commit into
pytorch:mainfrom
githubsgi:sg/optional-kda-import
Closed

githubsgi wants to merge 1 commit into
pytorch:mainfrom
githubsgi:sg/optional-kda-import

Conversation

@githubsgi

Copy link
Copy Markdown
Contributor

Summary

torchtitan/models/common/attention/__init__.py imports .kda unconditionally:

from .kda import KDAAttentionMetadata

kda.py in turn imports attn_gym.linear.short_conv, whose kernels are written in CuTeDSL and live behind the attn-gym[linear] extra. That extra resolves to nvidia-cutlass-dsl[cu13], which is CUDA-only by construction:

Provides-Extra: linear
Requires-Dist: nvidia-cutlass-dsl[cu13]>=4.6.0; (sys_platform == 'linux') and extra == 'linear'

The result is that a CUDA-only dependency sits on the import path of every model. On a non-CUDA accelerator, import torchtitan.models.common raises, so llama3, qwen3, deepseek_v3, flux, etc. cannot be imported at all -- even though none of them touch KDA.

Repro on XPU, current main:

  File ".../torchtitan/models/common/attention/__init__.py", line 30, in <module>
    from .kda import KDAAttentionMetadata
  File ".../torchtitan/models/common/attention/kda.py", line 14, in <module>
    from attn_gym.linear._delta_rule.gate import _FusedGate
ModuleNotFoundError: No module named 'attn_gym'

Installing base attn-gym (pure Python, depends only on torch) gets as far as line 21 and then hits the backend guard:

  File ".../torchtitan/models/common/attention/kda.py", line 21, in <module>
    from attn_gym.linear.short_conv import causal_conv1d
ImportError: causal_conv1d requires the optional CuTeDSL backend: pip install attn-gym[linear]

Why this looks unintended

The rest of the codebase already treats attn_gym as optional:

  • attention.py guards its own kda import behind if TYPE_CHECKING: and uses a string annotation.
  • tests/unit_tests/cpu/test_qwen3_6.py and test_qwen3_8.py call pytest.importorskip("attn_gym").
  • tests/unit_tests/gpu/test_kda_attention.py guards on importlib.util.find_spec("attn_gym").
  • tests/integration_tests/models.py carries the comment "short_conv's CuTe/CUTLASS kernel (attn_gym) is CUDA-only."

The runtime import in __init__.py is the one place that does not. It was introduced in #4639, which moved kda.py from models/kimi_k3/ into the shared models/common/attention/ package. Before that move the dependency was confined to a leaf module that only Kimi K3 imported, so the blast radius was contained.

Change

Fall back to an inert placeholder when the import fails. The union alias, __all__, and the models/common/__init__.py re-export all keep working untouched, because the name stays bound either way -- this is a single hunk in a single file.

Constructing the placeholder re-raises the original ImportError, so KDA models fail at build time with an actionable message rather than every model failing at import time. isinstance() checks against it (e.g. models/kimi_k3/model.py) still evaluate correctly, to False.

One except ImportError covers both failure modes, since ModuleNotFoundError subclasses ImportError.

cp_kda.py needs no change -- it is not imported by the package __init__, only by tests and two function-local imports in torchtitan_recipes/tests/suites/h100.py.

This does not make KDA, DSV4's CSA path, or torchtitan/rl/model/kda.py work on non-CUDA accelerators -- those kernels genuinely are CUDA-only. It only stops unrelated models from paying for them.

Test plan

Verified on Intel XPU (torch 2.15.0.dev20260907+xpu), branched off 286578760:

  • attn_gym absent. import torchtitan.models.common fails on main with ModuleNotFoundError: No module named 'attn_gym'; succeeds on this branch.
  • attn_gym present, CuTeDSL absent. Import succeeds. The placeholder captures ImportError: causal_conv1d requires the optional CuTeDSL backend: pip install attn-gym[linear], and constructing it re-raises exactly that error.
  • AttentionMetadata union still forms, and isinstance() against the placeholder returns False rather than raising.
  • pre-commit run passes on the changed file (flake8, ufmt, pydoclint, codespell, license, AST).
  • pyrefly 0.45.1 check on the changed file: 0 errors.

No numerics impact: on CUDA with attn-gym[linear] installed the try branch is taken and behavior is byte-identical to main.

`torchtitan/models/common/attention/__init__.py` imports `.kda`
unconditionally. `kda.py` in turn imports `attn_gym.linear.short_conv`,
whose kernels are written in CuTeDSL and live behind the
`attn-gym[linear]` extra, which resolves to
`nvidia-cutlass-dsl[cu13]` -- CUDA-only by construction.

That places a CUDA-only dependency on the import path of *every* model.
On a non-CUDA accelerator `import torchtitan.models.common` raises, so
llama3, qwen3, and friends cannot be imported at all, even though none
of them touch KDA.

The rest of the codebase already treats attn_gym as optional:
`attention.py` guards its own kda import behind `TYPE_CHECKING` and uses
a string annotation, the CPU qwen3 tests call
`pytest.importorskip("attn_gym")`, `test_kda_attention.py` guards on
`find_spec`, and `tests/integration_tests/models.py` notes that
"short_conv's CuTe/CUTLASS kernel (attn_gym) is CUDA-only". The runtime
import in `__init__.py` is the one place that does not.

Fall back to an inert placeholder when the import fails, so the union
alias, `__all__`, and the `models/common/__init__.py` re-export keep
working untouched. Constructing the placeholder re-raises the original
ImportError, so KDA models fail at build time with an actionable message
instead of every model failing at import time. `isinstance()` checks
against it still evaluate correctly.

Catches both failure modes: `ModuleNotFoundError` when attn_gym is
absent, and `ImportError: causal_conv1d requires the optional CuTeDSL
backend` when it is present without the extra.

Test plan:
- XPU, attn_gym absent: `import torchtitan.models.common` fails on main
  with `ModuleNotFoundError: No module named 'attn_gym'`; succeeds here.
- XPU, attn_gym present without CuTeDSL: import succeeds, placeholder
  captures `ImportError: causal_conv1d requires the optional CuTeDSL
  backend: pip install attn-gym[linear]`, and constructing it re-raises
  that error.
- `pre-commit run` passes on the changed file; pyrefly reports 0 errors.
@pytorch-bot pytorch-bot Bot added ciflow/fake-pg Run 1-GPU Fake PG integration tests ciflow/rl labels Oct 8, 2026
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Oct 8, 2026
@pytorch-bot

pytorch-bot Bot commented Oct 8, 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.

@mkhilari

Copy link
Copy Markdown
Contributor

Thanks for tracking this down, I hit the same failure on macOS (attn-gym installs, cutlass/triton have no wheels, so torchtitan.models.common can't import and no CPU unit test collects). Since #5231 the facade in torchtitan/models/common/attn_gym.py owns the "attn_gym missing" case, and the linear_attention.py import goes through it too, so I put the same deferral there for every export in #, keeping the error name/message the facade tests expect.

@tianyu-l

Copy link
Copy Markdown
Contributor

#5231

@tianyu-l tianyu-l closed this Oct 17, 2026
tianyu-l pushed a commit that referenced this pull request Oct 18, 2026
…5467)

## Summary

#5231 made the models importable when `attn_gym` is **absent**. On a
machine where `attn_gym` is **installed but one of its kernel backends
is not** (cutlass and triton have no macOS wheels, the same happens on
any non CUDA box without them), `attn_gym` itself imports fine and its
submodules raise `ModuleNotFoundError(name="cutlass")` /
`(name="triton")` at import time. The facade's `_load_module` only
tolerates `error.name == "attn_gym"`, so the error escapes,
`torchtitan.models.common` fails to import, and none of
`tests/unit_tests/cpu` can collect.

This keeps the existing contract from #5231 and extends it to that case:

- `_load_module` records a `ModuleNotFoundError` raised from inside an
`attn_gym.*` import (keyed by module) and resolves the export to
`_MissingKernel`, so the identity checks in `kda.py` / `gdn.py` /
`linear_attention.py` / `cp_linear_attention.py` still skip SPMD
registration.
- `_raise_missing` re-raises the recorded backend error (same `name` and
message) when a placeholder kernel is called, and `require_attn_gym()`
raises it when a kernel is built. The existing
`test_linear_attention_reports_missing_dependency[cutlass-*]` cases
therefore still see `error.name == "cutlass"`.
- No change when `attn_gym` is missing, and no change when every backend
imports.
- `require_attn_gym()` is deliberately coarse, any recorded backend
failure makes it raise, which matches the previous behaviour where the
module import itself failed. Per kernel granularity can come later if a
backend mix (e.g. cuDNN present, cutlass absent) turns out to matter.

Related: #5181 (@githubsgi) handles the same symptom for the KDA import
in `attention/__init__.py`, this does it once at the facade for every
export, including the `linear_attention.py` import that still fails
without it.

## Test plan

New
`test_common_attention_imports_with_broken_attention_gym_backend[cutlass|triton]`
in `tests/unit_tests/cpu/models/common/test_optional_imports.py`: an
installed `attn_gym` whose submodules all fail on the backend import,
the common package and every model debug config still import/build,
`_MissingKernel` is not registered with SPMD, and calling a kernel,
`require_attn_gym()`, or building `KDAKernel` / `GDNKernel` raises the
backend's own `ModuleNotFoundError`.

On macOS 15 (Apple Silicon, torch 2.16.0.dev20261014+cpu, attn-gym
0.0.17 without cutlass/triton):
- before: `pytest tests/unit_tests/cpu/components/checkpointer` → 2
errors during collection (`No module named 'cutlass'`, then `'triton'`)
- after: `tests/unit_tests/cpu/models/common/test_optional_imports.py`
11 passed; `tests/unit_tests/cpu/components/checkpointer` 120 passed, 2
failed (unrelated: torch_checkpointing uses `os.O_DIRECT`, reported
separately); `torchtitan/experiments/torchft/tests` 26 passed
- `pre-commit run --files` on both files: all hooks pass (flake8, µfmt,
pydoclint, codespell, pyrefly)
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.

3 participants