Repository navigation
[models] Let the attn_gym facade defer missing-backend import errors - #5467
Conversation
…The attn_gym facade treats only a missing attn_gym package as optional. When attn_gym is installed but one of the kernel backends it imports at module import time (cutlass, triton) has no wheel on the platform, the ModuleNotFoundError escaped from the facade and importing torchtitan.models.common failed, so no CPU unit test could collect on macOS. Record such errors per attn_gym module, resolve the export to _MissingKernel as for a missing package, and re raise the recorded backend error (same name and message) when a kernel is built or require_attn_gym() is called.
|
Hi @mkhilari! Thank you for your pull request and welcome to our community. Action RequiredIn order to merge any pull request (code, docs, etc.), we require contributors to sign our Contributor License Agreement, and we don't seem to have one on file for you. ProcessIn order for us to review and merge your suggested changes, please sign at https://code.facebook.com/cla. If you are contributing on behalf of someone else (eg your employer), the individual CLA may not be sufficient and your employer may need to sign the corporate CLA. Once the CLA is signed, our tooling will perform checks and validations. Afterwards, the pull request will be tagged with If you have received this in error or have any questions, please contact us at [email protected]. Thanks! |
|
|
|
The following ciflow label(s) have been added but CI has not been triggered yet because the workflows are awaiting approval:
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. |
|
Thank you for signing our Contributor License Agreement. We can now accept your code for this (and any) Meta Open Source project. Thanks! |
|
Thank you for signing our Contributor License Agreement. We can now accept your code for this (and any) Meta Open Source project. Thanks! |
|
@claude review |
|
Claude finished @tianyu-l's task in 1m 9s —— View job Review: attn_gym facade deferring missing-backend import errors
Summary: The approach is sound. It fixes the problem once in the facade instead of patching each call site (#5181 does the latter). It keeps the 1. The new catch also hides real errors inside attn_gym (main concern)
if name.split(".")[0] != "attn_gym":
raise
_BACKEND_ERRORS.setdefault(name, error)
return NoneThis checks the module being imported (
Narrowing the check to failures outside the attn_gym namespace keeps the intended behaviour (cutlass/triton/cudnn missing) and still raises on internal breakage: except ModuleNotFoundError as error:
if error.name == "attn_gym":
return None
if error.name is None or error.name.split(".")[0] == "attn_gym":
raise
# attn_gym is installed but this module needs a backend that is not ...
_BACKEND_ERRORS.setdefault(name, error)
return None( 2. The error reported depends on which modules failed first, not on the kernel called
A cheap improvement is to give 3. Nits
4. Tests
VerdictLooks good once #1 is fixed. That change is small and keeps today's "fail loudly on real breakage" behaviour on the main CUDA path. #2 can be a follow-up. |
|
@mkhilari please fix |
Review follow up for pytorch#5467. _load_module deferred every ModuleNotFoundError raised while importing an attn_gym module, so a moved attn_gym submodule or a typo in _EXPORTS would have become a placeholder kernel instead of failing at import. Decide on error.name instead, a missing attn_gym module still raises, only a missing backend (cutlass, triton, ...) is recorded. Also: simplify _raise_missing, document why it builds a fresh exception, note the coarseness of require_attn_gym(), update the module docstring, and add tests for the mixed case (available exports stay real and are registered with SPMD, failing ones defer) and for the internal-module case. kimi_k2_7 joins the model lists of both import tests.
80ef21a to
44aaca5
Compare
Thanks @tianyu-l for the review. Pushed a follow up commit addressing it:
On macOS without cutlass/triton: |
|
@claude review again |
|
Claude finished @tianyu-l's task in 1m 2s —— View job Re-review: attn_gym facade deferring missing-backend import errors
Summary: Every point from the last review is fixed or tracked with a TODO. I found no new blocking issues. LGTM once CI is green. Previous findings
#1 in detail (
So a submodule moved in a new attn_gym release, or a typo in New observations (none blocking)
VerdictApprove-ready from my side. The design keeps the "fail loudly on real breakage" behaviour on the main CUDA path and fixes test collection on platforms without cutlass/triton wheels. The per-placeholder error reporting (#2) is a reasonable follow-up PR, since it needs changes at the |
## 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 #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.
…#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.
Test Plan: tests/test_filesystem_storage_direct_io.py patches _O_DIRECT to None and checks that the writer falls back, that a storage write/read round trip works, and that a ReadArgs(direct_io=True) read is served by a plain buffered file. On macOS 15 (Apple Silicon, torch 2.16 nightly CPU) tests/test_checkpoint_writer.py tests/test_checkpoint_reader.py tests/test_checkpoint_manager.py go from 12 failed to 2 failed / 68 passed, the two left fail on torch.mps lacking current_device under torch.accelerator.current_stream() in staging.py, which is separate. torchtitan's tests/unit_tests/cpu/components/checkpointer goes from 2 failed to 125 passed (torchtitan pins dcbb3a5, see pytorch/torchtitan#5467). Internal (added on import): a `genai_uv_test` target for the new test file in `torch_checkpointing/tests/BUCK`, which fixes the `buck_verification` orphan-file failure. `BUCK` is stripped on export, so the exported commit contains only the PR's two files. `buck2 test fbsource//genai/msl/checkpointing/torch_checkpointing/tests:test_filesystem_storage_direct_io fbsource//genai/msl/checkpointing/torch_checkpointing/tests:test_local_filesystem fbsource//genai/msl/checkpointing:torch_checkpointing-static-type-checking fbsource//genai/msl/checkpointing:buck_verification`: Pass 125, Fail 0, including both new tests and `__orphan_files__`. https://www.internalfb.com/intern/testinfra/testrun/28991922656875489 fbshipit-source-id: 024e146ce3802dc90b48eb61d606ba21751f813b
Summary
#5231 made the models importable when
attn_gymis absent. On a machine whereattn_gymis 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_gymitself imports fine and its submodules raiseModuleNotFoundError(name="cutlass")/(name="triton")at import time. The facade's_load_moduleonly tolerateserror.name == "attn_gym", so the error escapes,torchtitan.models.commonfails to import, and none oftests/unit_tests/cpucan collect.This keeps the existing contract from #5231 and extends it to that case:
_load_modulerecords aModuleNotFoundErrorraised from inside anattn_gym.*import (keyed by module) and resolves the export to_MissingKernel, so the identity checks inkda.py/gdn.py/linear_attention.py/cp_linear_attention.pystill skip SPMD registration._raise_missingre-raises the recorded backend error (samenameand message) when a placeholder kernel is called, andrequire_attn_gym()raises it when a kernel is built. The existingtest_linear_attention_reports_missing_dependency[cutlass-*]cases therefore still seeerror.name == "cutlass".attn_gymis 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 thelinear_attention.pyimport that still fails without it.Test plan
New
test_common_attention_imports_with_broken_attention_gym_backend[cutlass|triton]intests/unit_tests/cpu/models/common/test_optional_imports.py: an installedattn_gymwhose submodules all fail on the backend import, the common package and every model debug config still import/build,_MissingKernelis not registered with SPMD, and calling a kernel,require_attn_gym(), or buildingKDAKernel/GDNKernelraises the backend's ownModuleNotFoundError.On macOS 15 (Apple Silicon, torch 2.16.0.dev20261014+cpu, attn-gym 0.0.17 without cutlass/triton):
pytest tests/unit_tests/cpu/components/checkpointer→ 2 errors during collection (No module named 'cutlass', then'triton')tests/unit_tests/cpu/models/common/test_optional_imports.py11 passed;tests/unit_tests/cpu/components/checkpointer120 passed, 2 failed (unrelated: torch_checkpointing usesos.O_DIRECT, reported separately);torchtitan/experiments/torchft/tests26 passedpre-commit run --fileson both files: all hooks pass (flake8, µfmt, pydoclint, codespell, pyrefly)