Repository navigation
[CP] Support Kimi K3 KDA CP - #4639
Conversation
|
This PR replaces #4500; the earlier review history remains available there. |
3d14dcc to
bf79cf4
Compare
|
|
||
|
|
||
| @dataclass(kw_only=True, slots=True) | ||
| class KDAContextParallelTransform(ModelConfigTransform): |
There was a problem hiding this comment.
Not clear why we should keep this separate from ContextParallelTransform
- it makes that name ambiguous
- what if I have a hybrid model that applies one but not the other?
| # Kimi K3 validation rejects PTRR, so a non-None balancer is head-tail. | ||
| input_dict["kda_cp_routing"] = _build_kda_context_parallel_routing( | ||
| cu_seqlens_global=cu_seqlens_global, | ||
| conv_kernel_size=backend_config.conv_kernel_size, |
There was a problem hiding this comment.
this is confusing -- you have conv_kernel_size in the config
- why making this a class method? If it's instance method you'd easily access the field
- why this method belongs to Attn not Attn.Config?
There was a problem hiding this comment.
make cp_shard_metadata a method of Config. This
- makes decoder logic simpler as we don't need to find owner class and call
owner.cp_shard_metadata, we just callconfig.cp_shard_metadata - no longer need to pass
backend_config.
| block_residual_TND: torch.Tensor, | ||
| attention_masks: KimiK3AttentionMaskDict | None = None, | ||
| positions: torch.Tensor | None = None, | ||
| kda_cp_routing: ContextParallelRouting | None = None, |
There was a problem hiding this comment.
Instead of keep adding things to the list, sounds that we should enhance attention_masks to be a general holder of such info, e.g. context_metadata.
There was a problem hiding this comment.
created KimiK3AttentionMetadata for this
| dt_bias_HK: torch.Tensor, | ||
| *, | ||
| cu_seqlens: torch.Tensor | None, | ||
| routing: ContextParallelRouting | None, |
There was a problem hiding this comment.
add docstring at least for public methods
2d5b496 to
58158de
Compare
58158de to
e06dcbe
Compare
e06dcbe to
5e3f5be
Compare
5e3f5be to
1fa9f30
Compare
1fa9f30 to
c9bad36
Compare
ca91264 to
8505d24
Compare
8505d24 to
f71bd4f
Compare
f71bd4f to
72f96e2
Compare
|
|
||
|
|
||
| @dataclass(frozen=True, slots=True) | ||
| class KDAAttentionMetadata: |
There was a problem hiding this comment.
remove
also KDA should be put in attention/kda.py?
There was a problem hiding this comment.
turns out we still need num_conv_history_tokens to build the context routing object
| ve_cfg, | ||
| *, | ||
| projector_norm: Literal["pre_norm", "post_norm"] = "pre_norm", | ||
| include_cp_axis: bool = False, |
| layers = getattr(model, "layers", None) | ||
| if not isinstance(layers, list): | ||
| raise ValueError("ContextParallelTransform requires decoder layers.") | ||
|
|
||
| mtp_layers = getattr(model, "mtp_layers", None) or [] | ||
| for layer in layers + mtp_layers: | ||
| for _, traversed, parent, field_name in layer.traverse( | ||
| InnerAttention.Config | ||
| ): | ||
| assert parent is not None and field_name is not None | ||
| convert(traversed, parent, field_name) |
There was a problem hiding this comment.
seems a bit fragile
cc @jinsooihm in case you'd like to address later
|
|
||
|
|
||
| @dataclass(frozen=True, slots=True) | ||
| class KDAAttentionMetadata: |
There was a problem hiding this comment.
remove
also KDA should be put in attention/kda.py?
| type[InnerAttention], | ||
| FlexAttentionMetadata | VarlenAttentionMetadata | KDAAttentionMetadata, |
There was a problem hiding this comment.
we should use AttentionMetadata as alias for this long thing
There was a problem hiding this comment.
we already had AttentionMetadata as the mapping, which is returned from _get_attention_metadata.
There was a problem hiding this comment.
then why don't you use it here?
There was a problem hiding this comment.
oh I mean we already have
AttentionMetadata = Mapping[
type[InnerAttention],
FlexAttentionMetadata | VarlenAttentionMetadata | KDAAttentionMetadata,
]
If we use AttentionMetadata as alias for FlexAttentionMetadata | VarlenAttentionMetadata | KDAAttentionMetadata, and use AttentionMetadataMap as the Mapping, then we need to update other places. Like _get_attention_metadata should really be _get_attention_metadata_mapping, and
| if spmd.is_type_checking(): | ||
| spmd.mutate_type( | ||
| num_local_tokens_per_expert_E, | ||
| src=spmd.P, | ||
| dst={"dp": spmd.V, "cp": spmd.V, "tp": spmd.V}, | ||
| ) |
There was a problem hiding this comment.
why introducing in this PR?
There was a problem hiding this comment.
With CP enabled and EP=1, router produces local per-expert counts as Partial. i believe this was missing before.
There was a problem hiding this comment.
With CP enabled and EP=1, router produces local per-expert counts as Partial.
Sure, could you say more about what's wrong with it?
all-to-all dispatcher needs to mutate because "reinterpret mesh" requires them to all be V; o/w "dp V, cp P, tp P" couldn't be reinterpreted as "edp V, ep V".
There was a problem hiding this comment.
if we don't have this mutate type here, we would have cp P, but num_local_tokens_per_expert_E is consumed as rank local offsets which shouldn't be reduced?
There was a problem hiding this comment.
I think it makes sense
cumsumshould be able to consume P and return P https://github.com/pytorch/torchtitan/blob/main/torchtitan/models/common/moe.py#L126- it'd be a local spmd region regardless of enable_ep or not
- I guess it's because grouped mm requires operand to be spmd.V instead of mixed V (matmul a, b) and P (offsets) https://github.com/pytorch/torchtitan/blob/main/torchtitan/models/common/linear.py#L419
cc @pianpwk
There was a problem hiding this comment.
kda works on H100, too -- can we test using cheaper machine?
| if spmd.is_type_checking(): | ||
| spmd.mutate_type( | ||
| num_local_tokens_per_expert_E, | ||
| src=spmd.P, | ||
| dst={"dp": spmd.V, "cp": spmd.V, "tp": spmd.V}, | ||
| ) |
There was a problem hiding this comment.
I think it makes sense
cumsumshould be able to consume P and return P https://github.com/pytorch/torchtitan/blob/main/torchtitan/models/common/moe.py#L126- it'd be a local spmd region regardless of enable_ep or not
- I guess it's because grouped mm requires operand to be spmd.V instead of mixed V (matmul a, b) and P (offsets) https://github.com/pytorch/torchtitan/blob/main/torchtitan/models/common/linear.py#L419
cc @pianpwk
| type[InnerAttention], | ||
| FlexAttentionMetadata | VarlenAttentionMetadata | KDAAttentionMetadata, |
Summary
This PR replaces #4500 so the branch can participate in GitHub's native PR
stacks.
Enable context parallelism for Kimi K3's hybrid KDA/MLA decoder and
multimodal input path.
rank keeps its local sequence fragments while exchanging the short-convolution
history and composing the recurrent state from preceding fragments.
or Ulysses CP with contiguous partitions.
token IDs, allowing each rank to map replicated vision-encoder outputs to its
local placeholders.
KDA and MLA reuse the same TorchTitan CP mesh. The all-gather configuration
supports contiguous and headtail partitions across the hybrid model; the
Ulysses configuration requires contiguous partitioning.
Implementation
The integration follows Attention Gym's delta-rule context-parallel example.
The KDA path separates its local stages so the CP adapter can replace only the
distributed operations while sharing projection, normalization, gating, and
output logic with the non-CP path. Attention Gym provides:
context_parallel_conv_historyfor convolution halo exchange; andcontext_parallel_kdafor recurrent-state summary composition and the localKDA computation.
TorchTitan builds an Attention Gym routing plan that matches its contiguous or
headtail token assignment and passes the per-batch routing through every KDA
layer.
Limitations
KDA CP currently supports contiguous and headtail partitions; PTRR is not
supported.
Ulysses MLA requires contiguous partitioning; it does not support headtail.
Current TorchTitan partitioning requires equal-sized fragments, where
Tisthe token count and
Cis the CP degree:T % C == 0T % (2 * C) == 0This is a limitation of the current PyTorch/TorchTitan equal-sized sharder,
not Attention Gym; Attention Gym routing accepts arbitrary fragment ranges.
Kimi K3 sample packing is not yet supported. Routing currently models the
batch as one global sequence.
Tests
CP=1 regression check
8.0844978.0844970.000%2.5312502.5312500.000%3.5747543.5747540.000%2.5625002.5625000.000%3.0899253.0899250.000%5.1562505.1562500.000%CP=2 loss vs. the before-PR CP=1 baseline
8.0844978.0844400.001%8.0844460.001%3.5747543.5766080.052%3.5718250.082%3.0899253.0600690.966%3.0519861.228%CP=2 grad norm vs. the before-PR CP=1 baseline
2.5312502.5312500.000%2.5312500.000%2.5625002.5625000.000%2.5468750.610%5.1562505.0625001.818%5.0312502.424%