Skip to content

[CP] Support Kimi K3 KDA CP - #4639

Merged
acisseJZhong merged 4 commits into
mainfrom
kda_cp
Oct 6, 2026
Merged

acisseJZhong merged 4 commits into
mainfrom
kda_cp

Conversation

@acisseJZhong

@acisseJZhong acisseJZhong commented Sep 13, 2026 •

Copy link
Copy Markdown
Contributor

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.

  • KDA layers use Attention Gym's native context-parallel implementation. Each
    rank keeps its local sequence fragments while exchanging the short-convolution
    history and composing the recurrent state from preceding fragments.
  • MLA layers can use all-gather K/V CP with contiguous or headtail partitions,
    or Ulysses CP with contiguous partitions.
  • Multimodal preprocessing shards token-aligned vision-bank indices with the
    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_history for convolution halo exchange; and
  • context_parallel_kda for recurrent-state summary composition and the local
    KDA 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 T is
    the token count and C is the CP degree:

    • contiguous: T % C == 0
    • headtail: T % (2 * C) == 0

    This 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

Step Before PR loss (CP=1) This PR loss (CP=1) Diff Before PR grad norm (CP=1) This PR grad norm (CP=1) Diff
1 8.084497 8.084497 0.000% 2.531250 2.531250 0.000%
10 3.574754 3.574754 0.000% 2.562500 2.562500 0.000%
100 3.089925 3.089925 0.000% 5.156250 5.156250 0.000%

CP=2 loss vs. the before-PR CP=1 baseline

Step Before PR (CP=1) This PR all-gather (CP=2) Diff This PR Ulysses (CP=2) Diff
1 8.084497 8.084440 0.001% 8.084446 0.001%
10 3.574754 3.576608 0.052% 3.571825 0.082%
100 3.089925 3.060069 0.966% 3.051986 1.228%

CP=2 grad norm vs. the before-PR CP=1 baseline

Step Before PR (CP=1) This PR all-gather (CP=2) Diff This PR Ulysses (CP=2) Diff
1 2.531250 2.531250 0.000% 2.531250 0.000%
10 2.562500 2.562500 0.000% 2.546875 0.610%
100 5.156250 5.062500 1.818% 5.031250 2.424%

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Sep 13, 2026
@acisseJZhong

Copy link
Copy Markdown
Contributor Author

This PR replaces #4500; the earlier review history remains available there.

@acisseJZhong
acisseJZhong marked this pull request as draft September 13, 2026 05:22
@acisseJZhong
acisseJZhong marked this pull request as ready for review September 13, 2026 05:34


@dataclass(kw_only=True, slots=True)
class KDAContextParallelTransform(ModelConfigTransform):

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.

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?

Comment thread torchtitan/models/kimi_k3/cp_kda.py Outdated
# 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,

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 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?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 call config.cp_shard_metadata
  • no longer need to pass backend_config.

Comment thread torchtitan/models/kimi_k3/model.py Outdated
block_residual_TND: torch.Tensor,
attention_masks: KimiK3AttentionMaskDict | None = None,
positions: torch.Tensor | None = None,
kda_cp_routing: ContextParallelRouting | None = None,

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.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

created KimiK3AttentionMetadata for this

Comment thread torchtitan/models/kimi_k3/kda.py Outdated
dt_bias_HK: torch.Tensor,
*,
cu_seqlens: torch.Tensor | None,
routing: ContextParallelRouting | None,

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.

add docstring at least for public methods

@acisseJZhong
acisseJZhong force-pushed the kda_cp branch 2 times, most recently from ca91264 to 8505d24 Compare September 25, 2026 23:57
@acisseJZhong
acisseJZhong removed this pull request from stack #4640 September 26, 2026 01:55
@acisseJZhong
acisseJZhong changed the base branch from refactor_cp_shard to attn_metadata September 26, 2026 01:56


@dataclass(frozen=True, slots=True)
class KDAAttentionMetadata:

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.

remove

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.

remove

also KDA should be put in attention/kda.py?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

turns out we still need num_conv_history_tokens to build the context routing object

conv_history=attention_metadata.num_conv_history_tokens,

Comment thread torchtitan/models/kimi_k2_7/sharding.py Outdated
ve_cfg,
*,
projector_norm: Literal["pre_norm", "post_norm"] = "pre_norm",
include_cp_axis: bool = False,

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.

remove

Comment on lines +75 to +85
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)

@tianyu-l tianyu-l Oct 6, 2026 •

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.

seems a bit fragile
cc @jinsooihm in case you'd like to address later



@dataclass(frozen=True, slots=True)
class KDAAttentionMetadata:

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.

remove

also KDA should be put in attention/kda.py?

Comment thread torchtitan/models/common/decoder.py Outdated
Comment on lines +401 to +402
type[InnerAttention],
FlexAttentionMetadata | VarlenAttentionMetadata | KDAAttentionMetadata,

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.

we should use AttentionMetadata as alias for this long thing

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we already had AttentionMetadata as the mapping, which is returned from _get_attention_metadata.

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.

then why don't you use it here?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

attention_metadata: AttentionMetadata | None = None,
should also change to map. I feel this makes things complicated than necessary.

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.

please fix this

Comment on lines +118 to +123
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},
)

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.

why introducing in this PR?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

With CP enabled and EP=1, router produces local per-expert counts as Partial. i believe this was missing before.

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.

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".

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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?

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.

I think it makes sense

cc @pianpwk

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.

kda works on H100, too -- can we test using cheaper machine?

Comment on lines +118 to +123
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},
)

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.

I think it makes sense

cc @pianpwk

Comment thread torchtitan/models/common/decoder.py Outdated
Comment on lines +401 to +402
type[InnerAttention],
FlexAttentionMetadata | VarlenAttentionMetadata | KDAAttentionMetadata,

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.

please fix this

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/b200 Trigger B200 CI 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.

4 participants