Skip to content

[Attn] Store varlen SDPA backends as names so --print-config works - #5814

Merged
tianyu-l merged 2 commits into
pytorch:mainfrom
andrewliu2001:claude/pytorch-torchtitan-contrib-5vpnz1
Nov 5, 2026
Merged

tianyu-l merged 2 commits into
pytorch:mainfrom
andrewliu2001:claude/pytorch-torchtitan-contrib-5vpnz1

Conversation

@andrewliu2001

Copy link
Copy Markdown
Contributor

Summary

--print-config crashes on main for every recipe that uses varlen attention,
including llama3_debugmodel. #5152 put SDPBackend values (a pybind11 enum)
into VarlenInnerAttention.Config, and pprint can't format them. This PR
stores the backend names in the config instead and converts them to
SDPBackend when the module is built, so the config stays plain data and the
backend order is unchanged. I reproduced the crash on main with torch nightly,
confirmed --print-config works with the fix, and checked that loss and
grad_norm are bitwise identical over 20 steps on an L40.

Why

--print-config crashes on main for every recipe that uses varlen attention,
which includes the default llama3_debugmodel.

Since #5152, VarlenInnerAttention.Config.sdpa_backends holds SDPBackend
values. SDPBackend is a pybind11 enum, and its __repr__ is an
instancemethod, which is unhashable. When an object does not fit on one
line, pprint looks up type(obj).__repr__ in a dict to pick a formatter,
so formatting the backend list raises. At the config's nesting depth the list
never fits on one line.

Example.

$ python -m torchtitan.train --module torchtitan_recipes.tests.models.llama3 \
      --config llama3_debugmodel --print-config
...
  File ".../pprint.py", line 181, in _format
    p = self._dispatch.get(type(object).__repr__, None)
TypeError: unhashable type: 'instancemethod'

After this PR the same command prints the config and exits 0:

inner_attention=Config(sdpa_backends=['CUDNN_ATTENTION',
                                      'FLASH_ATTENTION']),

The same field also makes Config.to_dict() (used by debug.print_config
and debug.save_config_file) log "Config field value of type SDPBackend may
not be JSON serializable" once per layer, 12 times for the debug model.

What changed

  • VarlenInnerAttention.Config.sdpa_backends is now a list of SDPBackend
    member names (Literal["CUDNN_ATTENTION", "FLASH_ATTENTION"], the two
    backends varlen_attn selects between). VarlenInnerAttention.__init__
    maps them to SDPBackend with getattr. The default order (cuDNN, then
    Flash) is unchanged. Sliding-window, Ulysses, and all-gather-KV varlen
    variants inherit the field and the conversion.
  • test_varlen_attention.py: mechanical update of the three places that set
    the field to [SDPBackend.FLASH_ATTENTION].
  • New test test_print_config_prints_and_exits in test_config_loader.py.

Alternatives considered

  • Print with json.dumps(config.to_dict()) instead of pprint: loses the
    config class names, which is how implementations are selected, and still
    leaves a non-serializable value in the config.
  • Catch the TypeError in the loader: hides the problem for the next pybind
    value someone puts in a config.

User-facing changes

Before After
sdpa_backends=[SDPBackend.FLASH_ATTENTION] sdpa_backends=["FLASH_ATTENTION"]

No in-repo recipe sets the field; only tests did.

Numerics

Bitwise-identical loss and grad_norm vs. base commit 0f34815
(scripts/loss_compare.py 0f34815 c954ab5 --steps 20 --metrics loss,grad_norm --assert-equal, llama3_debugmodel, seed checkpoint, deterministic).
Measured at c954ab5 on 0f34815, before rebasing onto 22047b1 (#5745); the
rebase only conflicted on the typing import line.

Config GPUs Result
llama3_debugmodel, 20 steps 1x L40 loss and grad_norm bitwise identical at every step

Testing

On 1x NVIDIA L40, torch 2.16.0.dev20261102+cu132, torchao
0.19.0.dev20261103, Python 3.12:

Check main (0f34815) this PR
--print-config on llama3_debugmodel TypeError, exit 1 exit 0
tests/unit_tests/gpu/models/common/test_varlen_attention.py 31 passed, 1 skipped 31 passed, 1 skipped

CPU (torch 2.15.0, torchao 0.18.0, Python 3.13): tests/unit_tests/cpu
1843 passed, 139 skipped. 4 tests failed because they download from
huggingface.co, which was unreachable from that machine; they fail the same
way on main. quantization/test_quantization.py was excluded because it
imports a module only in torchao nightly. On the L40 with the nightlies above,
test_config_loader.py and the CPU test_varlen_attention.py pass (45 passed).

The new test fails on main with the TypeError above and passes here. No
existing test runs --print-config, which is why #5152 did not catch this.

VarlenInnerAttention.Config.sdpa_backends held SDPBackend values since
instancemethod, and pprint looks up type(obj).__repr__ in a dict whenever
an object does not fit on one line. --print-config therefore raised
TypeError for every recipe that uses varlen attention, including
llama3_debugmodel. Config.to_dict() also warned once per layer that the
value may not be JSON serializable.

Store SDPBackend member names in the config and map them to SDPBackend
when the module is built. The default order (cuDNN, then Flash) is
unchanged.

Signed-off-by: Andrew Liu <[email protected]>
@pytorch-bot pytorch-bot Bot added ciflow/fake-pg Run 1-GPU Fake PG integration tests ciflow/rl labels Nov 4, 2026
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Nov 4, 2026
@pytorch-bot

pytorch-bot Bot commented Nov 4, 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 Nov 4, 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.

@acisseJZhong

Copy link
Copy Markdown
Contributor

@claude review

@claude

claude Bot commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @acisseJZhong's task in 1m 18s —— View job


Approve (please address the items before merging): review

@claude claude Bot left a comment

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.

Verdict: Approve -- please address the items below before merging. The problem is real on main, the config is the right layer to fix it (keep it plain data), and the change is small. A maintainer still needs to review, because this touches models/common/attention.

What this PR does. #5152 put SDPBackend pybind11 enum values into VarlenInnerAttention.Config.sdpa_backends. pprint can't format them once the list wraps, so --print-config crashes for every varlen recipe. The PR stores the backend names as a Literal list and converts them to SDPBackend in VarlenInnerAttention.__init__. The default order and the runtime value passed to sdpa_kernel(..., set_priority=True) stay the same, so numerics don't change. The PR reports bitwise-identical loss and grad_norm over 20 steps.

Example.

# before
VarlenInnerAttention.Config(sdpa_backends=[SDPBackend.FLASH_ATTENTION])
python -m torchtitan.train ... --config llama3_debugmodel --print-config
-> TypeError: unhashable type: 'instancemethod'

# after
VarlenInnerAttention.Config(sdpa_backends=["FLASH_ATTENTION"])
-> prints "inner_attention=Config(sdpa_backends=['CUDNN_ATTENTION', 'FLASH_ATTENTION'])", exit 0

Must fix

  1. tests/unit_tests/cpu/config/test_config_loader.py:88 -- the assertion depends on pprint line wrapping and on the default backend order. The exit-code check already guards the regression (see inline).

Should consider

  • Open draft #5706 ([muse_spark] Use varlen attention in the CP-16 LoRA SFT recipe) sets inner_attention.sdpa_backends = [SDPBackend.FLASH_ATTENTION]. Once this PR lands, getattr(SDPBackend, <SDPBackend>) raises TypeError there. The failure is loud, but you may want to tell @felipemello1 that it should become ["FLASH_ATTENTION"].
Details
  • Callsites audited: VarlenInnerAttention.__init__ is the only reader of config.sdpa_backends (attention.py:385). The sliding-window, Ulysses, and all-gather-KV variants inherit both the field and __init__. convert_config_type copies the list through unchanged, as the existing CPU test checks. No in-repo recipe sets the field. The SDPBackend uses in scripts/checkpoint_conversion/ and the GPU tests call sdpa_kernel directly and aren't affected.
  • Validation: a misspelled name raises AttributeError in __init__ rather than ValueError at config time. The Literal annotation already catches typos in Python recipes (via pyrefly) and in CLI overrides (via tyro choices), so a __post_init__ check would be a "just in case" check. I'm not asking for one.
  • The new test runs on CPU only, loads a config without building a model, and guards an invariant nothing else covered: that a default recipe config can be printed. It earns its cost.

Not verified: the GPU numerics run (taken from the PR description).

)

assert exit_info.value.code == 0
assert "sdpa_backends=['CUDNN_ATTENTION'," in capsys.readouterr().out

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.

This assertion depends on how pprint wraps lines at this nesting depth, and on the default backend order. If someone moves inner_attention one level deeper, or switches the default order to Flash first, the test fails even though --print-config still works. The invariant this test guards is "--print-config on a varlen recipe exits 0", and exit_info.value.code == 0 already checks that: on main the TypeError propagates out of load(). I'd drop this line. If you want to confirm something was printed, a looser check such as "sdpa_backends=" in out is enough.

Suggested change
assert "sdpa_backends=['CUDNN_ATTENTION'," in capsys.readouterr().out
assert "sdpa_backends=" in capsys.readouterr().out

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.

what about just deleting this test?

Per review: with sdpa_backends typed as backend names, the config no longer
holds a value pprint cannot format, so the test only re-checks printing.

Signed-off-by: Andrew Liu <[email protected]>

@tianyu-l tianyu-l left a comment

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.

curious -- would this fix it or not?
pytorch/pytorch#200977

@andrewliu2001

Copy link
Copy Markdown
Contributor Author

curious -- would this fix it or not? pytorch/pytorch#200977

It doesn’t. #200977 sets SDPBackend.qualname, which fixes pickling, but the crash comes from repr: pybind11 gives the enum an instancemethod repr, which is unhashable, and pprint looks up type(obj).repr in a dict when an object doesn’t fit on one line. The nightly I reproduced on (2.16.0.dev20261102) already includes #200977, and on torch 2.15 setting qualname by hand still gives TypeError: unhashable type: 'instancemethod':

import pprint
from torch.nn.attention import SDPBackend

SDPBackend.__qualname__ = "SDPBackend"   # what #200977 adds
pprint.pformat([SDPBackend.CUDNN_ATTENTION, SDPBackend.FLASH_ATTENTION], width=20)
# TypeError: unhashable type: 'instancemethod'

A fix upstream would need SDPBackend to become a native Python enum (e.g. py::native_enum). Even then I think the config should hold names: it keeps it plain data for to_dict/save_config_file too, which currently log a “may not be JSON serializable” warning per layer for this field.

@drisspg

drisspg commented Nov 5, 2026

Copy link
Copy Markdown
Contributor

@claude should pprint know how to print pprint reprs or should sdpbackned really be a StrEnum, not sure if pybind 11 supports this and we arnt on python 3.11 + yet

@claude

claude Bot commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @drisspg's task in 58s —— View job


Short answer: the fix belongs in PyTorch, and it should make SDPBackend a native Python enum (py::native_enum), not a StrEnum. Changing pprint wouldn't help us in practice. I'd still land this PR as is, because storing names is what torchtitan's config should do whichever way upstream goes.

Details

Why pprint breaks

When an object doesn't fit on one line, pprint looks up self._dispatch.get(type(obj).__repr__). pybind11's py::enum_ installs __repr__ as an instancemethod. instancemethod defines rich comparison but no tp_hash, so it is unhashable, and that dict lookup raises TypeError. You could call this a CPython wart, either pprint assuming __repr__ is hashable or instancemethod being unhashable, and a try/except TypeError in pprint would be a reasonable CPython patch. But it would only ship in a future Python release (3.15 at the earliest) and never reach the versions people run today, so it doesn't fix --print-config now.

Should SDPBackend be a real enum? Yes, but IntEnum rather than StrEnum

  • pybind11 3.x has py::native_enum<T>(m, "Name", "enum.IntEnum"), which builds a real enum.Enum subclass. Its __repr__ is an ordinary function, so pprint, pickling and copy all work. As far as I know this is the supported replacement for py::enum_. I haven't checked which pybind11 version PyTorch currently pins.
  • IntEnum fits better than StrEnum: the C++ sdp::SDPBackend is int-backed (error=-1, math=0, flash_attention=1, ...), and IntEnum keeps int(backend) and integer comparisons working for existing callers. StrEnum would change the semantics of every existing comparison.
  • The Python version isn't a blocker on our side: torchtitan already requires >=3.11 (pyproject.toml). It only matters for PyTorch's own minimum Python version, and native_enum doesn't need 3.11 unless you ask for enum.StrEnum.
  • As @andrewliu2001 noted, fix sdp pickling pytorch#200977 only sets __qualname__. That fixes pickling but not __repr__, so it doesn't fix this crash.

Why I'd keep names in the torchtitan config anyway

Even with an IntEnum SDPBackend, Configurable.to_dict() (torchtitan/config/configurable.py:63) takes the int branch for it, so save_config_file would write 3 instead of "CUDNN_ATTENTION". A Literal[...] of names gives readable JSON, readable --print-config output, and simple --override values, and it works on every torch release we support today. VarlenInnerAttention.__init__ is the only place that needs the real enum, which matches the "config is plain data" rule.

Suggested next step: open a PyTorch issue or PR to move _SDPBackend from py::enum_ to py::native_enum(..., "enum.IntEnum"). No TODO is needed in this PR, because the name-based config remains the right design after that upstream change.

I couldn't run Python in this job, so I didn't repro this locally. The instancemethod behavior is based on the author's repro above and the CPython and pybind11 sources.

@tianyu-l
tianyu-l merged commit 29f784e into pytorch:main Nov 5, 2026
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.

5 participants