Repository navigation
[attention] Share varlen metadata with CP variants - #5745
Conversation
|
@claude review |
There was a problem hiding this comment.
Verdict: Approve -- I found no correctness problems. Every constructor and _replace callsite in the repo is updated, and the pytree registration is tested for both metadata types. There is one optional simplification below. A maintainer still needs to review, since this touches models/common.
What this PR does. It turns VarlenAttentionMetadata from a NamedTuple into a frozen, slotted, keyword-only dataclass registered as a pytree. AllGatherKVVarlenAttentionMetadata becomes a subclass that adds inverse_permutation, instead of a wrapper around a varlen_metadata field. VarlenInnerAttention and SlidingWindowVarlenInnerAttention become generic in their metadata type, and the kernel call moves into _forward_varlen.
Example.
# before
md = VarlenAttentionMetadata(cu, cu, 8, 8)._replace(window_size=(3, 0))
cp = AllGatherKVVarlen.prepare_cp_metadata(md, permutation=None)
cp.varlen_metadata.cu_seq_q # nested
# after
md = replace(VarlenAttentionMetadata(cu_seq_q=cu, cu_seq_k=cu, max_q=8, max_k=8),
window_size=(3, 0))
cp = AllGatherKVVarlen.prepare_cp_metadata(md, permutation=None)
cp.cu_seq_q # same tensor object as md.cu_seq_q
isinstance(cp, VarlenAttentionMetadata) # now TrueShould consider
torchtitan/models/common/attention/attention.py:343-- the generic plus theforward/_forward_varlensplit and theassert isinstance(self, ...)in the CP mixin only add static typing. Keeping just the dataclass inheritance would be about 40 lines smaller (see inline).
Questions
- Did the Muse Glimmer FSDP2+CP2 numerics run use
torch.compile? Under CP,_chunk_metadatanow builds a frozen, slotted dataclass inside the forward, which used to be a NamedTuple. The description lists the compiled-attention GPU test but doesn't mention compile for the end-to-end run.
Details
- Callsite audit: I found no positional
VarlenAttentionMetadata(...)constructors,._replaceon metadata, or.varlen_metadatareads left intorchtitan/,torchtitan_recipes/, ortests/. The_replaceintransformers_modeling_backend/model.pyis an unrelated Config method. Model signatures that annotateVarlenAttentionMetadataneed no change. - Mixing types is safe: CP metadata now passes
isinstance(..., VarlenAttentionMetadata), so a non-CP varlen module would no longer reject it. ButDecoderkeys metadata by inner-attention class (decoder.py:445), so CP metadata only ever reaches its own CP module. - Pytree: the base class used to flatten automatically as a NamedTuple and now needs
register_dataclass. The extendedTestVarlenMetadataCudaGraphInputsnow covers the base-only case, which guards that registration. prepare_cp_metadatacopies the base fields by reference throughfields(VarlenAttentionMetadata). That's correct, and it avoidsasdict, which deep-copies tensors.- The graph_trainer helpers that walk
(list, tuple)operate on FX meta values after pytree flattening, so losing tuple-ness doesn't affect them.
Not verified: Dynamo/compile handling of the slotted frozen dataclass (needs a GPU run).
| ) | ||
|
|
||
|
|
||
| class VarlenInnerAttention(InnerAttention, Generic[_VarlenMetadataT]): |
There was a problem hiding this comment.
Should consider: the Generic[_VarlenMetadataT] parameterization is the larger half of this PR. It brings the typing_extensions import (the first in the repo), a forward that only asserts and forwards to _forward_varlen (plus a 13-line docstring), and assert isinstance(self, VarlenInnerAttention) in the CP mixin (cp_attention.py:370) so the checker can resolve self._forward_varlen. What it buys is narrower static types on overrides and direct .forward calls. As the description says, module(...) calls stay untyped, and the CP forward already raises ValueError on the wrong metadata type at runtime.
A smaller version keeps only the dataclass inheritance:
VarlenInnerAttention.forwardstays typedVarlenAttentionMetadata.AllGatherKVVarlen.forwardtakesVarlenAttentionMetadataand keeps its existingisinstance->ValueErrorcheck.- CP keeps calling
super().forwardwith the chunk metadata, so_forward_varlenand the self-assert go away.
That's roughly 40 fewer lines, with the same runtime behavior. #5746 would follow the same pattern for _SelectiveGatherVarlenMetadata. If you keep the generic for the typing benefit, consider dropping the parameter-restating docstring. The old forward had none, and nothing in it is non-obvious.
|
|
||
|
|
||
| class VarlenInnerAttention(InnerAttention): | ||
| register_dataclass(VarlenAttentionMetadata) |
There was a problem hiding this comment.
cudagraph use pytree and this will ensure that our dataclass work correctly with pytree. Will add a comment.
Stacked PRs: * #5746 * #5745 * #5744 * __->__#5743 * #5742 --- --- --- [tools] Fix CUDA Graph dependency arrows ## Summary (human-written) Fix a bug of cudagraph dependency arrow. The AI summary shows an example that can cause errors. This PR fixes the issue. ## Why The trace compactor matches GPU dependency arrows to kernel start times. An arrow's source is at the source kernel's end. This can attach the arrow to the next kernel or make compaction fail. ```text Kernel A: [10, 12] Kernel B: [12, 14] At time 12, an arrow source belongs to A and a destination belongs to B. ``` ## What changed - Match GPU arrow sources to slice ends and destinations to slice starts. - Accept one adjacent floating-point value when matching a source timestamp. This handles rounding in timestamp + duration. - Keep errors for endpoints that cannot be matched. ## Numerics / performance This tool processes saved profiler traces. Kernel timestamps and durations are preserved. Training code is outside the change. ## Testing - Six tests pass: `python -m unittest discover -s .claude/skills/cuda_graph_trace_compaction/scripts -p test_compact_cuda_graph_trace.py`. - The regression test checks adjacent kernels, a rounded source timestamp, and preservation of the arrow timestamp. - Saved Muse Glimmer trace validation maps all 4228 and 3372 GPU flow endpoints.
0f6738f to
3b3644c
Compare
Stacked PRs: * #5746 * #5745 * #5744 * __->__#5771 --- --- --- [tools] Fix CUDA Graph dependency arrows Reland #5743, accidentally land #5743 to an incorrect branch. ## Summary (human-written) Fix a bug of cudagraph dependency arrow. The AI summary shows an example that can cause errors. This PR fixes the issue. ## Why The trace compactor matches GPU dependency arrows to kernel start times. An arrow's source is at the source kernel's end. This can attach the arrow to the next kernel or make compaction fail. ```text Kernel A: [10, 12] Kernel B: [12, 14] At time 12, an arrow source belongs to A and a destination belongs to B. ``` ## What changed - Match GPU arrow sources to slice ends and destinations to slice starts. - Accept one adjacent floating-point value when matching a source timestamp. This handles rounding in timestamp + duration. - Keep errors for endpoints that cannot be matched. ## Numerics / performance This tool processes saved profiler traces. Kernel timestamps and durations are preserved. Training code is outside the change. ## Testing - Six tests pass: `python -m unittest discover -s .claude/skills/cuda_graph_trace_compaction/scripts -p test_compact_cuda_graph_trace.py`. - The regression test checks adjacent kernels, a rounded source timestamp, and preservation of the arrow timestamp. - Saved Muse Glimmer trace validation maps all 4228 and 3372 GPU flow endpoints.
Stacked PRs: * #5746 * #5745 * __->__#5744 --- --- --- [config] Remove the CP import cycle ## Summary (human-written) config/__init__.py shouldn't import parallelism, this causes a circular import and this PR remove it. ``` context_parallel -> config/__init__.py -> config/parallelism -> context_parallel ``` ## Why A CP-first import fails on main. CP imports Configurable, but config/__init__.py eagerly imports ParallelismConfig, which reads the unfinished CP module. ```python from torchtitan.distributed.context_parallel import ContextParallelLoadBalancer ``` ## What changed - Remove the eager parallelism exports from config/__init__.py. Keep the direct load-balancer type annotation. - Mechanical: update ten test files to import from config.parallelism. - Add one fresh-process regression test for CP-first imports and runtime type hints. ## User-facing changes | Before | After | | --- | --- | | Import ParallelismConfig or FSDPSymmMemScope from torchtitan.config | Import from torchtitan.config.parallelism | ## Alternatives considered - A type-only CP import avoids the cycle but breaks get_type_hints(ParallelismConfig). - A lazy export adds a compatibility layer that the repo does not require. ## Numerics Imports only. No tensor math or training behavior changes. GPU numerics were not rerun. ## Testing - `python -m pytest -q tests/unit_tests/cpu/config -k 'not test_every_cp_recipe_passes_the_gate'`: 206 pass. - The regression test fails on unmodified main at ff96670 and passes with this fix. - Eight affected test files collect 155 tests. LoRA collection fails on both main and this change because torchvision::nms is missing. - Targeted Pyrefly reports zero errors. All non-typechecking pre-commit hooks pass. - Whole-worktree Pyrefly reports the same 179 errors as before this change.
## Summary (human-written)
VarlenAttentionMetadata is namedtuple because we want to avoid
pytree.register_dataclass. However, this design make the typing
harder and confusing. This PR makes VarlenAttentionMetadata a
dataclass so that other CP variation can inherits from
it -- you cannot do this with namedtuple.
## Why
All-gather and selective-gather varlen CP share document offsets and window limits, but need different prepared metadata. Their forward signatures should state that requirement. Shared metadata subclasses and generic attention classes preserve the sliding-window inheritance and each variant's input type. The selective-gather PR uses this contract for _SelectiveGatherVarlenMetadata. This checks direct forward calls and overrides; PyTorch module calls remain untyped.
```python
class AllGatherKVVarlenInnerAttention(
AllGatherKVVarlen,
VarlenInnerAttention[AllGatherKVVarlenAttentionMetadata],
): ...
```
## What changed
- Use frozen dataclasses for varlen metadata. Copy all base fields into CP metadata without copying tensors. Register both types as PyTrees through torch.export.register_dataclass.
- Make full and sliding-window varlen attention generic in their metadata type. Default to VarlenAttentionMetadata. Share the kernel call through _forward_varlen so CP can pass chunk metadata without widening its public input type.
- Mechanical: update metadata constructors, field access, and dataclasses.replace calls in Flux and existing tests.
## Alternatives considered
- Dataclass inheritance alone cannot narrow an overridden method's input type.
- A separate inner module adds indirection and breaks the sliding-window class relationship.
## User-facing changes
| Before | After |
| --- | --- |
| metadata._replace(...) | dataclasses.replace(metadata, ...) |
| cp_metadata.varlen_metadata.cu_seq_q | cp_metadata.cu_seq_q |
## Numerics
Loss and grad_norm match exactly against a3b242533 for all 10 steps. Checked Muse Glimmer on four H100s with FSDP2+CP2, head-tail balancing, CUDA Graphs, full activation recompute, seed 42, and deterministic mode. Compared full-precision TensorBoard metrics with scripts/loss_compare.py.
## Testing
- Review fixes: 36 CPU tests pass, including base and CP metadata graph inputs. The three changed source files pass Pyrefly.
- 300 CPU tests pass across varlen attention, CP attention, and config validation. The run excludes the shipped-recipe gate and the Flux import test listed below.
- 34 GPU tests pass, including forward/backward, compiled attention, Ulysses, and CUDA Graph replay with changed document offsets. Extend the existing graph-input test to cover base and derived metadata registration.
- The three changed source files pass Pyrefly. All non-typechecking hooks pass in pre-commit run --all-files.
## Local check failures
- The Flux CPU test cannot import CLIPTextModel because torchvision::nms is missing. The same failure occurs on the parent commit.
- Whole-worktree Pyrefly reports dependency mismatches and errors in untracked scratch files. One scratch constructor still passes metadata fields positionally.
stack-info: PR: #5745, branch: fegin/stack/5
…5814) ## 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. --------- Signed-off-by: Andrew Liu <[email protected]>
Stacked PRs:
[attention] Share varlen metadata with CP variants
Summary (human-written)
VarlenAttentionMetadatais namedtuple because we want to avoidpytree.register_dataclass. However, this design make the typingharder and confusing. This PR makes
VarlenAttentionMetadataadataclass so that other CP variation can inherits from
it -- you cannot do this with namedtuple.
Why
All-gather and selective-gather varlen CP share document offsets and window limits, but need different prepared metadata. Their forward signatures should state that requirement. Shared metadata subclasses and generic attention classes preserve the sliding-window inheritance and each variant's input type. The selective-gather PR uses this contract for _SelectiveGatherVarlenMetadata. This checks direct forward calls and overrides; PyTorch module calls remain untyped.
What changed
Alternatives considered
User-facing changes
Numerics
Loss and grad_norm match exactly against a3b242533 for all 10 steps. Checked Muse Glimmer on four H100s with FSDP2+CP2, head-tail balancing, CUDA Graphs, full activation recompute, seed 42, and deterministic mode. Compared full-precision TensorBoard metrics with scripts/loss_compare.py.
Testing
Local check failures