Repository navigation
Conversation
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]>
|
|
|
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. |
|
@claude review |
|
Claude finished @acisseJZhong's task in 1m 18s —— View job Approve (please address the items before merging): review |
There was a problem hiding this comment.
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
tests/unit_tests/cpu/config/test_config_loader.py:88-- the assertion depends onpprintline 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) setsinner_attention.sdpa_backends = [SDPBackend.FLASH_ATTENTION]. Once this PR lands,getattr(SDPBackend, <SDPBackend>)raisesTypeErrorthere. 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 ofconfig.sdpa_backends(attention.py:385). The sliding-window, Ulysses, and all-gather-KV variants inherit both the field and__init__.convert_config_typecopies the list through unchanged, as the existing CPU test checks. No in-repo recipe sets the field. TheSDPBackenduses inscripts/checkpoint_conversion/and the GPU tests callsdpa_kerneldirectly and aren't affected. - Validation: a misspelled name raises
AttributeErrorin__init__rather thanValueErrorat config time. TheLiteralannotation 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 |
There was a problem hiding this comment.
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.
| assert "sdpa_backends=['CUDNN_ATTENTION'," in capsys.readouterr().out | |
| assert "sdpa_backends=" in capsys.readouterr().out |
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
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. |
|
@claude should pprint know how to print pprint reprs or should sdpbackned really be a |
|
Claude finished @drisspg's task in 58s —— View job Short answer: the fix belongs in PyTorch, and it should make DetailsWhy
|
Summary
--print-configcrashes on main for every recipe that uses varlen attention,including
llama3_debugmodel. #5152 putSDPBackendvalues (a pybind11 enum)into
VarlenInnerAttention.Config, andpprintcan't format them. This PRstores the backend names in the config instead and converts them to
SDPBackendwhen the module is built, so the config stays plain data and thebackend order is unchanged. I reproduced the crash on main with torch nightly,
confirmed
--print-configworks with the fix, and checked that loss andgrad_norm are bitwise identical over 20 steps on an L40.
Why
--print-configcrashes on main for every recipe that uses varlen attention,which includes the default
llama3_debugmodel.Since #5152,
VarlenInnerAttention.Config.sdpa_backendsholdsSDPBackendvalues.
SDPBackendis a pybind11 enum, and its__repr__is aninstancemethod, which is unhashable. When an object does not fit on oneline,
pprintlooks uptype(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.
After this PR the same command prints the config and exits 0:
The same field also makes
Config.to_dict()(used bydebug.print_configand
debug.save_config_file) log "Config field value of type SDPBackend maynot be JSON serializable" once per layer, 12 times for the debug model.
What changed
VarlenInnerAttention.Config.sdpa_backendsis now a list ofSDPBackendmember names (
Literal["CUDNN_ATTENTION", "FLASH_ATTENTION"], the twobackends
varlen_attnselects between).VarlenInnerAttention.__init__maps them to
SDPBackendwithgetattr. The default order (cuDNN, thenFlash) 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 setthe field to
[SDPBackend.FLASH_ATTENTION].test_print_config_prints_and_exitsintest_config_loader.py.Alternatives considered
json.dumps(config.to_dict())instead ofpprint: loses theconfig class names, which is how implementations are selected, and still
leaves a non-serializable value in the config.
TypeErrorin the loader: hides the problem for the next pybindvalue someone puts in a config.
User-facing changes
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
typingimport line.Testing
On 1x NVIDIA L40, torch 2.16.0.dev20261102+cu132, torchao
0.19.0.dev20261103, Python 3.12:
--print-configonllama3_debugmodeltests/unit_tests/gpu/models/common/test_varlen_attention.pyCPU (torch 2.15.0, torchao 0.18.0, Python 3.13):
tests/unit_tests/cpu1843 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.pywas excluded because itimports a module only in torchao nightly. On the L40 with the nightlies above,
test_config_loader.pyand the CPUtest_varlen_attention.pypass (45 passed).The new test fails on main with the
TypeErrorabove and passes here. Noexisting test runs
--print-config, which is why #5152 did not catch this.