Skip to content

support CP for KimiK3 - #4500

Closed
acisseJZhong wants to merge 1 commit into
pytorch:refactor_cp_shardfrom
acisseJZhong:kda_cp
Closed

acisseJZhong wants to merge 1 commit into
pytorch:refactor_cp_shardfrom
acisseJZhong:kda_cp

Conversation

@acisseJZhong

@acisseJZhong acisseJZhong commented Sep 6, 2026 •

Copy link
Copy Markdown
Contributor

Summary

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

Tested on NVIDIA H100 GPUs with Attention Gym main at commit 7418529.

Targeted unit tests:

pytest -q tests/unit_tests/gpu/test_kda_attention.py \
  tests/unit_tests/gpu/test_kimi_k3.py
# 13 passed

pytest -q tests/unit_tests/cpu/test_integration_test_definitions.py
# 12 passed

Two-GPU integration tests (10 training steps each):

python -m tests.integration_tests.run_tests <output-dir> \
  --test_suite b200 \
  --test_name kimi_k3_mm_allgather_kv_cp \
  --ngpu 2 --no-parallel
# rc=0

python -m tests.integration_tests.run_tests <output-dir> \
  --test_suite b200 \
  --test_name kimi_k3_mm_ulysses_cp \
  --ngpu 2 --no-parallel
# rc=0

Deterministic BF16 runs used the same seed checkpoint (seed=42), 256 tokens
per step, and 100 training steps. CP=1 used one GPU; CP=2 used two GPUs with
Attention Gym CP for KDA and either headtail all-gather K/V or contiguous
Ulysses for MLA. Values below are measured at steps 1, 10, and 100. Each diff
is the absolute percentage difference from CP=1.

Step CP=1 loss All-gather loss Diff Ulysses loss Diff
1 12.624805 12.616027 0.070% 12.627501 0.021%
10 4.031361 3.878002 3.804% 4.639540 15.086%
100 2.794998 2.930616 4.852% 2.846095 1.828%
Step CP=1 grad norm All-gather grad norm Diff Ulysses grad norm Diff
1 25.625 25.625 0.000% 25.75 0.488%
10 6.84375 6.96875 1.826% 11.625 69.863%
100 5.75 5.3125 7.609% 5.8125 1.087%

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Sep 6, 2026
@acisseJZhong
acisseJZhong marked this pull request as ready for review September 7, 2026 00:13
@acisseJZhong
acisseJZhong requested a review from drisspg September 7, 2026 00:13
pillow
spmd_types==0.2.5
attn-gym[linear]==0.0.5
attn-gym[linear] @ git+https://github.com/meta-pytorch/attention-gym.git@main

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.

lets change before land; we are also on 0.0.8 ( that should be checked in if it hasnt its probs a bug; ) but the 0.8 didnt have the cp stuff finalzied we can cut a new one for this

Comment thread torchtitan/models/kimi_k3/model.py Outdated
tokens = batch.get("input")
if not isinstance(tokens, torch.Tensor):
raise ValueError("Kimi K3 context parallelism requires token input.")
batch["kda_cp_routing"] = build_kda_context_parallel_routing(

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.

Code looks a bit hard to follow. E.g. are you making kda_cp_routing field sharded in this function, and would the cp_shard in the function below shard it again? https://github.com/pytorch/torchtitan/blob/main/torchtitan/distributed/context_parallel/api.py#L109

Following my comment #4450 (comment), I think we should abstract the CP sharding method to associate it with each Attention / CP backend, and here in model.preprocess_inputs we should only call succinct API interface.

@acisseJZhong acisseJZhong Sep 8, 2026 •

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.

no cp_shard will only shard tensor inputs. So this routing object will not be sharded again.

named: dict[str, torch.Tensor] = {

Yes maybe we can customize cp_shard for different backends, and put build_kda_context_parallel_routing into cp_shard for kda cp. cc @fegin

the rest of this function is pretty standard, following muse glimmer's preprocess input.

not torch.cuda.is_available()
or torch.cuda.get_device_capability() not in {(10, 0), (10, 3)},
"Attention Gym KDA requires CUDA capability 10.0 or 10.3.",
or torch.cuda.get_device_capability() not in {(9, 0), (10, 0), (10, 3)},

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 do support ampere+ CP might need hopper + though

Comment thread torchtitan/models/kimi_k3/model.py Outdated
Decoder.Config.update_from_config(self, config=config, **kwargs)
parallelism = config.parallelism
if parallelism.context_parallel_degree > 1 and (
parallelism.context_parallel_load_balancer not in (None, "headtail")

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.

Is there a nice way to register some other form of balancer? Or at least a plan to open this up

@fegin fegin Sep 9, 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.

Do you mean that users can add their own load balancer? The corresponding CP kernel needs to know the load-balancing algorithm. So they need to swap together, the interface is not clean yet. After the stack of #4459, it may be a step closer, but I haven't fully thought about that.

What's the load balancing in your mind? cc., @jinsooihm

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.

Maybe each kernel can define their load balancing function, which can be passed in prepare_context_parallel_input? But there could be some problems if a model uses two different kernels and their load balancers are not compatible.

@drisspg drisspg Sep 9, 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.

so at least at the kda level we just need the dataloader/batcher to describe the fragment allocation per rank there are alot of nouns and verbs I have a detailed walkthrough (quite long) https://github.com/meta-pytorch/attention-gym/blob/81c186d900658c9da2597acaa1042f1b8721ffe8/attn_gym/linear/context_parallel.py#L7

my original claim is that depending on your actual distribution of packed documents you might want to do different load balancing. This is not really applicable today with just the Dense path supported so its moot until then but food for thought

num_tokens: int,
world_size: int,
load_balancer: str | None,
) -> list[list[tuple[int, int]]]:

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.

Yeah, I do think we should think about how we want people to extend this. Could be a follow-up

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.

added a todo

@fegin
fegin force-pushed the gh/fegin/166/orig branch from 2192c50 to 06dc84a Compare September 9, 2026 08:07
@QIU023 QIU023 mentioned this pull request Sep 9, 2026
14 of 18 tasks

@fegin fegin 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.

As discussed offline, the Ulysses introduced in #4450 is not the best one for MLA attention. You may want to subclass the UlyssesCPFlexInnerAttention to provide a new one.

@acisseJZhong
acisseJZhong marked this pull request as draft September 11, 2026 23:19
@acisseJZhong
acisseJZhong changed the base branch from main to refactor_cp_shard September 12, 2026 00:10
@acisseJZhong
acisseJZhong force-pushed the refactor_cp_shard branch 6 times, most recently from 3219338 to 84080c5 Compare September 13, 2026 05:08
@acisseJZhong

Copy link
Copy Markdown
Contributor Author

Replacement upstream-branch PR: #4639. This preserves the same stack base while allowing GitHub native PR stacks.

QIU023 added a commit to QIU023/torchtitan that referenced this pull request Sep 13, 2026
tianyu-l pushed a commit that referenced this pull request Sep 16, 2026
### Summary

Tensor parallelism, with and without sequence parallel, for Kimi K3 on
spmd_types: KDA and MLA become head-parallel, the latent MoE takes
core's expert sharding, and the MoonViT tower reuses Kimi K2.5's plan.
At tp=1 nothing changes: loss and grad norm match main on all 100 steps.

- Before: `parallelize_kimi_k3` refuses tensor parallel, and MLA / KDA
reshape to the global head count (`view(num_tokens, n_heads, ...)`).
After: `local_head_split` splits the rank-local heads; `wq_b`, `wkv_b`,
`gate` and KDA's `q_proj`, `k_proj`, `v_proj`, `forget_b`, `beta`,
`output_gate` are colwise; `wo` and `output_proj` are rowwise,
reduce-scattering under SP.
- Two Kimi K2.5 commits sit under it. `kimi_k2_7/vision_encoder.py`: the
packed position tables retype only the dp axis under type checking;
retyping tp as well is refused at tp > 1, where the tables are already
invariant on tp. `kimi_k2_7/sharding.py`: K2.5's MoonViT plan is public
as `set_moonvit_sharding_config`, with the projector norm named by the
caller (`pre_norm` in K2.5, `post_norm` in K3). The first can go as its
own PR.
- No core file changes.

### Design

- `kimi_k3/sharding.py`: `set_kimi_k3_sharding_config(config, *,
enable_sp, enable_ep)` fills every sub-config unconditionally, as
DeepSeek V3 does; `Module.parallelize` drops the disabled axes.
- MLA: DeepSeek V3's plan without RoPE; `wq_a`, `wkv_a` and their norms
replicated; inner attention through core's
`set_gqa_inner_attention_local_spmd`; the headless rope key is broadcast
to the local heads under `spmd.local()`.
- KDA: Qwen3.5 GatedDeltaNet's head-sharded plan; `forget_a` and
`output_norm` replicated; the conv weights, `A_log` and `dt_bias` shard
with the heads; the kernel is one `local_spmd` region on the local
heads.
- Latent MoE: core's `set_moe_sharding_config`, plus core's padding-mask
sharding on the MoE layers. Under EP the routed path follows the router:
`routed_down` takes the rank's token shard (without SP it drops the
other TP ranks' tokens on entry), the experts' output stays
token-sharded, and `routed_norm` and `routed_up` run on those tokens
with Replicate weights, so their gradients reduce over TP; without SP,
`routed_up` re-enters Partial and the MoE exit reduces once with the
shared experts. Without EP the experts are TP-sharded: `routed_down` is
replicated, and without SP the experts' Partial output is reduced at
`routed_norm`.
- Multimodal: `tok_embeddings` stays TP-replicated for the vision
scatter; layer 0's input boundary puts the stream and the block-residual
stack back in the decoder's layout (sequence shard under SP, invariant
otherwise).
- `kimi_k3/model.py`: `update_from_config` runs core's first, then
checks that tp divides the tower's head count (as K2.5 does), then
declares; the batch uses core's `multimodal_input_sharding()`.
- Not covered: TP x CP (#4500's); tp above 2 on the debug model, whose
tower has 6 heads (the released tower has 12).

### Results

```bash
torchrun --nproc_per_node=2 -m torchtitan.train --module kimi_k3 --config kimi_k3_debugmodel \
  --debug.seed 42 --debug.deterministic --training.steps 100 \
  --training.num-tokens-per-train-step 256 --training.num-tokens-per-microbatch-per-dp-rank 256 \
  --parallelism.tensor_parallel_degree 2   # --parallelism.no-enable-sequence-parallel for SP off
```

dp1, 256 tokens per step, against tp=1 on main; the last column counts
the steps, of 100, whose logged loss and grad norm equal main's.

| cell | loss, step 1 | step 10 | step 20 | grad norm, step 1 | step 10
| step 20 | steps equal to main |
| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: |
| tp=1, main | `12.44473` | `4.12222` | `3.31114` | `27.2500` | `6.0625`
| `6.1875` | reference |
| tp=1, this PR | `12.44473` | `4.12222` | `3.31114` | `27.2500` |
`6.0625` | `6.1875` | 100 / 100 |
| tp=1, this PR, fresh inductor cache | `12.44473` | `4.12222` |
`3.31114` | `27.2500` | `6.0625` | `6.1875` | 100 / 100 |
| tp=2, SP on | `12.45268` (+0.064%) | `4.44351` (+7.79%) | `3.20842`
(-3.1%) | `27.8750` (+2.29%) | `6.9062` (+13.9%) | `6.2188` (+0.51%) | 0
/ 100 |
| tp=2, SP off | `12.44544` (+0.0057%) | `4.24770` (+3.04%) | `3.38211`
(+2.14%) | `27.5000` (+0.92%) | `8.8125` (+45.4%) | `6.6875` (+8.08%) |
0 / 100 |

dp2, **512 tokens per step** (256 per rank; a multimodal row does not
fit in 128), against dp2 on this PR.

| cell | loss, step 1 | step 10 | step 20 | grad norm, step 1 | step 10
| step 20 |
| --- | ---: | ---: | ---: | ---: | ---: | ---: |
| dp2 | `12.45935` | `4.07423` | `3.38009` | `24.5000` | `6.0625` |
`4.4375` |
| dp2 x ep2 (no TP) | `12.45935` (0%) | `3.72571` (-8.55%) | `3.40608`
(+0.77%) | `24.5000` (0%) | `4.7188` (-22.2%) | `4.2500` (-4.23%) |
| dp2 x tp2 | `12.50688` (+0.38%) | `3.88132` (-4.73%) | `3.41127`
(+0.92%) | `24.7500` (+1.02%) | `5.0625` (-16.5%) | `4.7500` (+7.04%) |
| dp2 x ep2 x tp2 | `12.52374` (+0.52%) | `4.07369` (-0.013%) |
`3.45136` (+2.11%) | `24.3750` (-0.51%) | `4.5938` (-24.2%) | `4.6250`
(+4.23%) |
| dp2 x ep2 x tp2, SP off | `12.48901` (+0.24%) | `4.02450` (-1.22%) |
`3.42512` (+1.33%) | `24.1250` (-1.53%) | `8.4375` (+39.2%) | `5.3438`
(+20.4%) |

Kimi K2.5, dp2, tp=1, 4096 tokens per step (its debug config), this PR
against main; K2.5 refuses tp > 1 on main (DistMuon, #3353).

| cell | loss, step 1 | step 10 | step 20 | grad norm, step 1 | step 10
| step 20 | steps equal to main |
| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: |
| main | `8.01201` | `4.60605` | `3.24834` | `8.8055` | `4.5538` |
`2.9925` | reference |
| this PR | `8.01201` | `4.60605` | `3.24834` | `8.8055` | `4.5538` |
`2.9925` | 100 / 100 |

Type checking, 3 steps with `--debug.spmd_typechecking` and activation
checkpointing off (as the b200 recipe sets it): the b200 cell
`kimi_k3_debugmodel_mm` (fsdp 2 x tp 2 x ep 2) with SP on and off on 4
GPUs, and dp1 x tp2 on 2 GPUs, pass.

4 x H100 80GB HBM3 (SXM), main `d34a13fdf`, torch
`2.15.0.dev20260906+cu130`, `attn-gym` 0.0.8 (main's pin), spmd_types
0.2.5; KDA's capability guard widened locally to admit SM 9.0, not part
of this PR. For scale, #4500's CP=2 rows on H100: +3.8% and +15.1% loss
at step 10.

### CI/CD Coverage

`kimi_k3_mm` in the b200 suite: `kimi_k3_debugmodel_mm`, fsdp 2 x tp 2 x
ep 2 with SP and type checking, 4 GPUs; it replaces `kimi_k3_mm_fsdp`.
`test_integration_test_definitions.py` and `test_no_new_cli_options.py`
pass on this head.
acisseJZhong added a commit that referenced this pull request Oct 6, 2026
## 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](https://github.com/meta-pytorch/attention-gym/blob/main/examples/linear/delta_rule_context_parallel.py).

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%` |
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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