Repository navigation
[kimi_k3_1] Add Kimi K3.1 Pro with Gated DSA - #6007
Conversation
Kimi K3.1 Pro is Kimi K3 with its 24 Gated MLA layers replaced by Gated DeepSeek Sparse Attention. The new kimi_k3_1 model adds the indexer, the sparse attention (Attention Gym gather_attn over the absorbed MLA latent), the debugmodel and Kimi-K3.1-Pro flavors built with the Kimi K3 config builder, a K3.1 block and model, and a state dict adapter that adds the indexer weights to the Kimi K3 mapping. Top-k selection and the indexer loss come from DeepSeek V4. Kimi K3 gets small builder hooks so K3.1 can reuse it.
Attention Gym main now runs the shared-KV schedule with (latent, rope) pairs on Ampere and newer. The Kimi-K3.1-Pro shape compiles in seconds this way; a single 576-wide tensor stays on the slow per-head kernel. The fused pair path needs 16 to 128 heads, so the debug model now has 16 heads.
Indexer.select, gather_attn and the indexer loss read the untyped varlen offsets, so a type-checked run failed in compressed_cu_seqlens. Run them under spmd.no_typecheck() and assert the output keeps the query's type, as DeepSeek V4's sparse attention does.
|
|
The Kimi K3.1 block was a copy of the K3 block that only also passed padding_mask and aux_loss_denominator to the attention. The K3 block now passes them to Kimi MLA attention, which K3 ignores and the K3.1 DSA subclass uses, so the K3.1 block and the block class argument of kimi_k3_config are removed. K3 configs are unchanged; K3.1 configs differ only in the block class.
301153a to
d29924d
Compare
5250af4 to
136f91e
Compare
|
@tianyu-l @shuhuayu this PR is ready for review. The K3.1 integration test has no golden yet, because KimiSparseAttention calls Attention Gym's gather_attn, and that kernel has no deterministic backward yet: meta-pytorch/attention-gym#795. |
Follow the Kimi K3 split from pytorch#6084: debugmodel and Kimi-K3.1-Pro build the text KimiK31Model, and the _mm flavors build KimiK31MultimodalModel with the vision encoder. kimi_k3_config takes the multimodal config class next to the text one.
c0c4312 to
94c27f5
Compare
mla_attention_config's config_cls takes a callable, not only a class, so call it config_factory. kimi_k3_config's full_attention becomes full_attention_config_factory, like attention_config_factory in the DeepSeek V3 builder.
…type KimiDSAAttention.Config skipped the Kimi MLA inner attention check and had none of its own. It now requires a KimiSparseAttention.Config and an indexer loss with the attention's softmax scale and head count, since a mismatch gives a wrong loss without an error. The fused (latent, rope) pair kernel only runs BF16 on Ampere or newer. Other dtypes and devices now use the reference kernel, as the indexer selection already does, instead of raising inside Attention Gym.
Kimi K3.1 was missing from the build_model_config tests, so none of its flavors were built on CPU.
c7acb22 to
fed98f1
Compare
fed98f1 to
80c6d68
Compare
There was a problem hiding this comment.
Verdict: Approve -- please address the items below before merging -- the code at HEAD addresses all five of @shuhuayu's comments. What's left is a PR description that no longer matches the code. @shuhuayu's change request is still open, so a maintainer still needs to re-review.
What this PR does. Kimi K3.1 Pro is now a flavor-only folder (kimi_k3_1/flavors.py), like qwen3_6. It builds KimiK3Model / KimiK3MultimodalModel through kimi_k3_config(..., full_attention_config_factory=_dsa_config). The DSA layer lives in kimi_k3/dsa.py. K3 itself now registers the aux-loss zero hook and maps the five indexer HF keys. A K3 checkpoint has no indexer keys and K3 has no AuxLoss, so both are no-ops for K3.
Example.
# before (first round): separate model, adapter and config classes
kimi_k3_config(..., config_cls=KimiK31Model.Config, multimodal_config_cls=KimiK31MultimodalModel.Config)
# now: same K3 classes, only the full-attention factory differs
kimi_k3_config(..., full_attention_config_factory=partial(mla_config, attn_backend="varlen")) # K3
kimi_k3_config(..., full_attention_config_factory=partial(_dsa_config, index_topk=2048, ...)) # K3.1@shuhuayu's feedback at HEAD
| Comment | Status |
|---|---|
Move the test to b200.py, use 32 heads, copy the shape of kimi_k3_debugmodel_fsdp2_tp2_ep2_pp2_vpp4 |
Addressed: b200.py:115. The debug model has num_heads=32 (16 per TP rank), and the FSDP2/TP2/EP2/PP2/VPP4 split, schedule and optimizer match the K3 cell |
| Add the aux-loss hook to the K3 model | Addressed: kimi_k3/model.py:210 |
| Fold the state dict adapter into K3 | Addressed: kimi_k3/state_dict_adapter.py:111-121. kimi_k3_1/state_dict_adapter.py is deleted |
Fold model.py into K3, keep kimi_k3_1 flavor-only |
Addressed: kimi_k3_1/ now has only __init__.py, flavors.py and README.md. config_cls / multimodal_config_cls are removed from kimi_k3_config |
| Remove the run-to-run noise paragraph from the README | Addressed: the paragraph is removed. A deterministic loss-parity check across parallelisms, which is the bar the comment sets, still has to wait for meta-pytorch/attention-gym#795. That is tracked by the TODO at b200.py:193 |
Must fix
- The PR description no longer matches the code, and reviewers verify against it:
- "What changed" still lists
kimi_k3_1/dsa.py,model.py(KimiK31Model,KimiK31MultimodalModel),state_dict_adapter.py, and the "optional text and multimodal model config classes". - "Tests" still says H100
kimi_k3_1_fsdp+ep(FSDP 2 + EP 2, SPMD type checking on). At HEAD it is B200kimi_k3_1_fsdp2_tp2_ep2_pp2_vpp4on 8 GPUs with type checking off. - The testing commands point to
tests/unit_tests/cpu/models/kimi_k3_1/andh100 ... kimi_k3_1_debugmodel_fsdp2_ep2. Neither exists anymore. - Please update these sections, and say whether the new 8-GPU B200 cell was run.
- "What changed" still lists
Should consider
tests/integration_tests/b200.py:115-- this function duplicates the K3 VPP4 cell. Factor out the shared body (see the inline comment).- Still open from the first review:
torchtitan_recipes/tests/models/kimi_k3_1.py:34-38imports_dist_muon_optimizer,_kimi_k3_multimodal_dataloaderand_KimiK3TrainerConfig, which are private to another module. The rootREADME.mdmodel table has no row for K3.1.
Questions
- Still unanswered from the first review: were the five
self_attn.indexer.*HF names checked against the released K3.1 checkpoint index? The README now says the adapter "maps the released Hugging Face checkpoint, including the indexer weights", but no test or check in the PR shows that.
Details
- Items from the first automated review: the DSV4 promotion TODO is at
kimi_k3/dsa.py:393-394and the golden TODO atb200.py:190-192. Both are resolved. The fp32 silent-fallback finding is handled by the newKimiSparseAttention.Config.impl: Literal["fused", "reference"] = "fused". With that field nothing chooses an implementation from dtype or device, andhas_cuda_capabilityis gone from the model code. Only the CPU oracle test uses"reference". - The block branch
isinstance(self.attention, KimiMLAAttention)inkimi_k3/model.py:158sendspadding_maskandaux_loss_denominatorto MLA and DSA. K3'sKimiMLAAttention.forwarddrops them withdel, so the K3 numerics don't change. The description reports a bitwise K3 comparison, which I did not re-run. kimi_k3_1/__init__.pyre-exports the K3 model classes, asqwen3_6/__init__.pyre-exportsQwen35Model.
Not verified: that gather_attn(impl="fused") raises on fp32 or non-accelerator inputs (Attention Gym is not importable here); where debug.deterministic = True raises for K3.1 (nothing in this diff checks for it, so it must come from Attention Gym); and the GPU runs.
| return config | ||
|
|
||
|
|
||
| def kimi_k3_1_debugmodel_fsdp2_tp2_ep2_pp2_vpp4() -> Trainer.Config: |
There was a problem hiding this comment.
(should consider) Apart from the recipe it starts from, this function is a line-for-line copy of kimi_k3_debugmodel_fsdp2_tp2_ep2_pp2_vpp4 above. The copy also leaves out the comments that explain why type checking is off, why the split uses 4 stages, and why it keeps AdamW (#3353). Factoring the shared body into a module-private helper that takes the base Trainer.Config removes about 25 lines and keeps those comments in one place:
def _fsdp2_tp2_ep2_pp2_vpp4(config: Trainer.Config) -> Trainer.Config:
# (body of the K3 function, starting at _set_spmd_typechecking)
...
def kimi_k3_debugmodel_fsdp2_tp2_ep2_pp2_vpp4() -> Trainer.Config:
return _fsdp2_tp2_ep2_pp2_vpp4(kimi_k3_debugmodel(parallelism=ParallelismConfig(expert_parallel_degree=2)))
def kimi_k3_1_debugmodel_fsdp2_tp2_ep2_pp2_vpp4() -> Trainer.Config:
return _fsdp2_tp2_ep2_pp2_vpp4(kimi_k3_1_debugmodel(parallelism=ParallelismConfig(expert_parallel_degree=2)))| remat.recompute_needs_tensor(q_TJ) | ||
| q_THK = local_head_split(q_TJ, self.q_head_dim, cp_shard_dim=0) | ||
|
|
||
| compressed_kv_TC = self.wkv_a(x_TD) |
|
|
||
| compressed_kv_TC = self.wkv_a(x_TD) | ||
| remat.recompute_needs_tensor(compressed_kv_TC) | ||
| kv_latent_TC, k_shared_TR = torch.split( |
There was a problem hiding this comment.
| kv_latent_TC, k_shared_TR = torch.split( | |
| kv_latent_TL, k_shared_TR = torch.split( |
|
@JavaZeroo could you check CI failures? some are unrelated, but some seem related |
pytorch#6181 changed Indexer.select and SparseIndexerLoss to take DeepSeekV4CompressedSparseAttentionMetadata instead of cu_seqlens. KimiSparseAttention now builds that metadata once per variant, with the compressed pool equal to the token pool since K3.1 selects at ratio 1.
981c09f to
470f5dd
Compare
@tianyu-l #6181 changed Indexer.select and SparseIndexerLoss to take the DSV4 sparse-attention metadata instead of cu_seqlens, which broke lint and the K3.1 CPU test. K3.1 now builds that metadata once in build_attention_metadata. |
pytorch#6216 replaced Indexer.select with the InnerIndexer module. KimiSparseAttention now holds an InnerIndexer (ratio 1, the K3.1 top-k) in place of index_topk. InnerIndexer has no parameters, so state dict keys and the HF mapping do not change.
470f5dd to
3d311af
Compare
|
@claude review again |
There was a problem hiding this comment.
Verdict: Approve -- please address the items below before merging -- the three new commits are a rename and a port to the DSV4 API that #6181 / #5722 changed. I found no new problems in them. Two lines of the PR description are now stale. @shuhuayu has approved; a maintainer still needs to sign off.
What changed since the last automated review (5351ee7..3d311af, +42/-32 in 3 files)
8f277b5:kv_latent_TC->kv_latent_TLandcompressed_kv_TC->compressed_kv_TG, with a newG = L + Rlegend entry. This resolves both of @shuhuayu's comments.51950cd+3d311af:KimiSparseAttentionnow selects through aDSV4 InnerIndexersubmodule instead of the removedIndexer.select.index_topk: intbecomesinner_indexer: InnerIndexer.Config(ratio=1, topk=...), andbuild_attention_metadatareturns aDeepSeekV4CompressedSparseAttentionMetadata.
Example.
# before
Indexer.select(q, k, w, max_seqlen=md.max_k, ratio=1, topk=self.index_topk, cu_seqlens=md.cu_seq_q, ...)
# after
self.inner_indexer(q, k, w, attention_metadata=md, return_scores=...)
# md.cu_seq_compressed = md.cu_seq_q (ratio 1: every token is its own "compressed" slot)Earlier items at HEAD
- Resolved: the TODO at
kimi_k3/dsa.py:28now names only #5863. #5722 is closed and itsInnerIndexerAPI is what the code uses. - Resolved: most of the stale description from the last review. "What changed" and "Tests" now describe
kimi_k3/dsa.py, the flavor-onlykimi_k3_1/folder, and the B200 cell.
Must fix
- PR description, "Known issues": it still says K3.1 is "the second user of the DSV4
Indexer.select" and that the move tomodels/common/waits for "#5722 and #5863". The code now usesInnerIndexer, and #5722 is closed. Please also say whether the 8-GPU B200 cellkimi_k3_1_fsdp2_tp2_ep2_pp2_vpp4was run, and whether the 2-GPU numerics rows were run again after the switch toInnerIndexer(they came before3d311af).
Should consider (still open from earlier reviews, no new inline comments)
torchtitan_recipes/tests/models/kimi_k3_1.py:33-37imports three_privatenames from the K3 recipe module.tests/integration_tests/b200.py:122copies the body of the K3 VPP4 cell.- The root
README.mdmodel table has no K3.1 row.
Questions
- Still unanswered: were the five
self_attn.indexer.*HF names checked against the released K3.1 checkpoint index?
Details
- Metadata at ratio 1:
cu_seq_compressed = cu_seq_q, socompressed_gather_indices(deepseek_v4/compressor.py:55) adds each document's token offset. That is the same packed indexinggather_attnuses withcu_seqlens_k=cu_seqlens.group_start/group_firstare empty, and onlyCompressorreads them (compressor.py:169). K3.1 has noCompressor. InnerIndexer.forwardcarries@spmd.no_typecheck()itself, so removing the explicitwith spmd.no_typecheck()around selection changes nothing. Becauseinner_indexeris now a submodule, any hook or FQN walk sees one extra parameterless module. It has no state dict entries, so HF loading is unaffected.Decodercaches metadata by inner-attention class (common/decoder.py:544), so the DSV4 metadata type built forKimiSparseAttentiondoesn't collide with the KDA layers' metadata.flops_per_tokennow readsinner_indexer.topk. The value is the same as before.InnerIndexerpicks the referencelightning_indexeron anything below SM90 or on fp32 (compressor.py:304-308), whilegather_attnfollowsimpl. That is pre-existing DSV4 behavior, not part of this PR.
Not verified: GPU runs, and whether InnerIndexer selects the same tokens bitwise as the removed Indexer.select.
yes
8-GPU B200 was run by ci, and switch to InnerIndexer is bit-wise equal |
|
looks good to me, will merge once ci tests pass, thx. |
|
the failed test is unrelated, so good to merge. |
…6363) ## Summary (human-written) <!-- Write this yourself, not with an AI tool. 2-5 sentences: the problem, why this approach, and what you checked yourself. --> ## Agent details **TLDR:** Since main 74a2c8e, `lint` fails on every PR into main that changes a Python file. pyrefly reports `Could not import quadratic_attention_flops_per_token from torchtitan.models.common.flops` at `torchtitan/models/kimi_k3/dsa.py:297`. It broke when #6007 (Kimi K3.1) merged after #6325 replaced the attention FLOPs API: each passed CI on its own. @JavaZeroo @acisseJZhong, could you please take a look? This PR ports `KimiDSAAttention.Config.flops_per_token(seq_len)` to `flops(positions)`, the method the FLOPs estimator calls now. That also restores the top-k cap and the indexer in Kimi K3.1's FLOPs count. Today, main counts its sparse attention (DSA) layers as dense attention, so Kimi K3.1 Pro's `tflops` and `mfu(%)` read 8.4% high at 32k tokens and 3.1x at 1M.  <!-- pr-image drawn at a81832f --> ```python # before: never called, and imports a removed function def flops_per_token(self, seq_len: int) -> int: ... # after def flops(self, positions: torch.Tensor) -> int: num_keys = positions + 1 attention_flops = quadratic_attention_flops(..., num_keys=num_keys.clamp(max=topk)) indexer_flops = 6 * num_index_heads * index_head_dim * int(num_keys.sum()) return attention_flops + indexer_flops ``` **Problem** 1. Commit bd64f5c ("Count causal and document-masked attention FLOPs per query position") replaced each attention config's `flops_per_token(seq_len)` with `flops(positions)`. It removed `quadratic_attention_flops_per_token`. 2. Commit 74a2c8e ("Add Kimi K3.1 Pro with Gated DSA") added `KimiDSAAttention.Config.flops_per_token` on the old API. Its lint passed on 11-23 at 23:38 UTC, before bd64f5c merged (11-24 01:55 UTC). 3. pyrefly checks the whole project whenever a PR changes a Python file. So `lint` now fails on those PRs, from their next push on. 4. The estimator calls `attention.flops(positions)` (`decoder.py:214`). DSA layers inherit it from `KimiMLAAttention`: all p + 1 keys, no top-k cap, no indexer. **Solution** 1. Port the method to `flops(positions)`, as DeepSeek-V4's sparse attention does (`deepseek_v4/attention.py:337`). 2. Attention reads at most top-k keys per query. The indexer scores all p + 1 keys. 3. At full length (every query at position seq_len - 1), it gives the same number as the old method. 4. Only Kimi K3.1's `tflops` and `mfu(%)` metrics change. Loss and gradients don't. **Results** ``` Kimi K3.1 Pro, FLOPs/token, one document (positions 0..seq_len-1) seq_len main this PR main reads 4096 6.37e11 6.36e11 +0.2% 32768 7.01e11 6.47e11 +8.4% 131072 9.18e11 6.76e11 +35.8% 1048576 2.95e12 9.46e11 3.1x debugmodel, FLOPs/token, seq_len 128, every query at position 127 (top-k = 128, so only the indexer differs) main 834,345,216 this PR 835,328,256 = the old flops_per_token formula ``` You may ask: Why count the indexer over p + 1 keys instead of seq_len? Since bd64f5c, the estimator charges each query its causal keys. At full length both give the same count. NOTE: The indexer term keeps the old method's factor of 6, a forward and backward over all p + 1 keys, as DeepSeek-V4's does. The indexer scores all keys without grad, and recomputes only the top-k with grad for the indexer loss (`deepseek_v4/compressor.py:310-333`). Counting that would cut Kimi K3.1 Pro's estimate by 0.8% at 32k and 21.7% at 1M. A TODO at the line records it. The fix belongs in both models, so it's left for a follow-up. **Test plan** ``` pytest tests/unit_tests/cpu/models/kimi_k3/test_kimi_k3_1_dsa.py -k flops main: 1 failed (7987200 != 8125440: the inherited dense formula) this PR: 1 passed pytest tests/unit_tests/cpu/models/kimi_k3/ tests/unit_tests/cpu/models/common/test_flops_estimators.py \ tests/unit_tests/cpu/models/deepseek_v4/test_deepseek_v4_flops.py: 48 passed ``` pyrefly check, whole project, on a copy of this PR: the `dsa.py` error is gone. One error remains locally, in `activation_offload.py:449`. It comes from our older torch nightly, which lacks `FSDPModule.get_all_gather_copy_in_stream`, and CI's lint doesn't report it. pre-commit run --files <changed files>, with SKIP=pyrefly-check because pyrefly ran above: all hooks pass. Co-authored-by: Felipe Mello <[email protected]>
…er override; agent self-review; rl/transport (#6407) ## Summary (human-written) <!-- Write this yourself, not with an AI tool. 2-5 sentences: the problem, why this approach, and what you checked yourself. --> ## Why Since #5667, `@claude review` has reviewed 459 PRs. Of the 380 PRs it approved, 30 then got a formal "request changes" from a maintainer, and about 20 more got substantive inline asks. In nearly all of them the bot either saw the problem and approved anyway, or never asked the questions maintainers ask most ("does the repo already do this?", "who should own this?"). The opposite failure, the bot blocking something a maintainer was fine with, is rare: in the PRs we sampled, 2 of its 81 must-fix items were wrong and about a third were minor (the empty human-written summary was the biggest source). **Example** (#6112, controller sizes the rollout worker pool): ``` before: bot approved 10 times; tianyu-l then blocked: "the controller reads rollouter.rollouts_per_worker to compute a count it hands back to the Rollouter -- violates encapsulation" after: same commit, new skill -> Request changes, must-fix #1: "controller.py:589 -- wrong owner for the worker count ..." ``` There was also no way for a code owner to overrule the bot except dismissing its review in the GitHub UI, and a later `@claude review again` would block again. ## What changed **Review skill** (`.claude/skills/pr-review/`, `review-checklist.md`): - Verdict rules: Approve only when every remaining item is an edit the bot could write itself. Anything the author still owes (a design change, an unexplained golden change, evidence the PR rests on) is Request changes; anything only a maintainer can decide is Needs discussion. A hedge like "a maintainer should decide" can't come with Approve. - Always must-fix: a violated written rule, a silent wrong result, a second definition of an existing concept, a gate finding. - Design gate: new questions for the existing counterpart, in-repo ownership, and the design behind a bug; "ban only what doesn't work on main"; read the numbers behind a claim. The overlapping-PR search is mandatory and reported. - Re-review covers every commit since the last full review, including code taken from the bot's own suggestions. A scoped question gets a `COMMENT`, not a whole-PR verdict. - The bot fact-checks its own proposed fixes, and cites a source for claims about external tools or marks them unverified (never must-fix). - An empty "Summary (human-written)" is a one-line "Before merge" note that never affects the verdict. - Checklist: config ownership direction, general shared wrappers, dead code the PR creates, model variants as flavors, a mechanical pass over every new or changed function. **Code owner override** (`SKILL.md`, `claude-code.yml`, `CONTRIBUTING.md`): a code owner comments `@claude override` (optionally `@claude override 2,3: <reason>`); the bot approves if nothing else is open and doesn't re-raise the overridden items. A code owner's GitHub approval or "LGTM" is not an override, so a teammate can approve without the bot dropping its findings. Dismissing the bot's review still unblocks the PR, but isn't an override: the bot can't tell who dismissed it. **Agent self-review** (`CLAUDE.md`, `pr-description`): an agent preparing a PR runs `pr-review` in branch mode first and records unaddressed items in an optional "Self-review" section. PRs written without an agent are unaffected; a missing section is never a finding. Where each new rule comes from (maintainer asks the bot missed): | Change | PRs | | --- | --- | | No Approve with open design/evidence items or a "maintainer should decide" hedge | #6007, #5837, #5997, #5712, #5511, #5996 | | Author waiver can't clear a must-fix | #6201, #6202, #6203 | | Existing counterpart; one source of truth | #5228, #6169, #5881, #5823, #5824, #6059, #5812 | | Responsibility owner; config ownership direction | #6112, #6332, #5802, #5803, #6325 | | Fix the design behind the bug; a TODO doesn't justify a workaround | #5572, #5689, #5657 | | Fact-check the bot's own suggested fixes | #5740, #5802, #5511, #4819, #5543 | | Re-review covers all new commits; scoped asks don't approve | #5824, #5842 | | Mandatory overlap search | #5885, #6248 | | Ban only what doesn't work on main | #5543 | | Summary placeholder no longer a must-fix | #6119, #6174, #6112, #5868 | **Rules**: `design.md` gets the one-general-wrapper rule (moved from `models.md`, whose glob skipped `torchtitan/rl`), thin adapters, and the consumer owning its values; `config.md` gets ownership direction and "a Config doesn't read runtime state"; `direction.md` calls all-to-all the MoE reference implementation, so a new vendor-specific dispatch path (e.g. #6242) needs a reason the existing backends can't serve. **Area reviewers**: `.ci/` -> huydhn, wwwjn; `torchtitan/rl/transport/` -> d4l3k. **Mechanical, skim**: `torchtitan/rl/transport/` holds data movement between RL actors. - `rl/model_state_dict_transport.py` -> `rl/transport/model_state_dict.py` - `rl/MODEL_STATE_DICT_TRANSPORT.md` -> `rl/transport/MODEL_STATE_DICT_TRANSPORT.md` - `rl/trainer/rdma_microbatch.py` -> `rl/transport/rdma_microbatch.py` - tests: `tests/rl/unit_tests/cpu/test_{model_state_dict_transport,rdma_microbatch}.py` -> `tests/rl/unit_tests/cpu/transport/test_{model_state_dict,rdma_microbatch}.py` - imports, READMEs and `scripts/install_rl_env.sh` updated; no code changes. ## User-facing changes | Before | After | | --- | --- | | Overrule the bot: dismiss its review in the UI, and it blocks again on the next run | `@claude override [items]: <reason>`; the bot approves and doesn't re-raise them | | Empty human-written summary: bot must-fix | One "Before merge" line, no effect on the verdict | | `from torchtitan.rl.model_state_dict_transport import ...` | `from torchtitan.rl.transport.model_state_dict import ...` | | `from torchtitan.rl.trainer.rdma_microbatch import ...` | `from torchtitan.rl.transport.rdma_microbatch import ...` | ## Testing Backtest: the new skill run locally (nothing posted) on each PR at the commit and thread state the bot originally saw. | PR | Bot then | New skill | What the maintainer asked | | --- | --- | --- | --- | | #6112 | Approve | Request changes | worker-count ownership (caught) | | #5837 | Approve | Request changes | apply to `dp_shard` too (caught) | | #5572 | Approve | Request changes | delete the injection design (caught) | | #6201 | Approve after author waived pins | Request changes, waiver ignored | pins broke GPU tests after merge (caught) | | #6007 | Approve | Request changes | fold K3.1 into K3 (caught) | | #5543 | Request changes: "ban it" | Request changes: keep main's path | don't break gpt-oss + DeepEP (fixed) | | #6144, #5905 (controls) | Approve | Approve | -- | | #6137 (control) | Approve | Needs discussion | -- (merge gate on an upstream API) | Code owner override, simulated on #6201: override by a code owner lifts the named item; `@claude override` from the author changes nothing; a code owner's "LGTM" approval followed by "review again" keeps Request changes. Transport move: 83 RL CPU unit tests pass locally (`transport/test_model_state_dict.py`, `test_trainer.py`, `test_engine_loop.py`). `transport/test_rdma_microbatch.py`, `test_generator.py` and `test_batcher_actor.py` fail to collect in my env on `origin/main` too (stale attention-gym / Monarch), so CI is the check for those. ## Known issues / follow-ups - Open PRs that edit the moved files rebase cleanly (git follows the renames), but new imports of the old module paths will break: #6309 (adds a delta transport that should live in `rl/transport/`), #6237, #6176, #6177, #5862, and drafts #6127, #6393, #6163, #5764. - The Actions bot can't read dependency source (e.g. SGLang); follow-up for the workflow. ## Self-review pr-review (branch mode) at ad905a5: Needs discussion. Fixed: branch mode diffs against `origin/main` and skips description findings before a description exists; the "Config doesn't read runtime state" rule no longer contradicts hardware validation; dismissal dropped as an override form (the bot can't tell who dismissed); `test_rdma_microbatch.py` added to the transport area. Not addressed: - One concern per PR -- the five changes ship together at the maintainer's request. - Open PRs touching the moved files -- listed above; the maintainer will coordinate.
Summary (human-written)
Add Kimi K3.1 Pro. It differs from K3 only in its 24 full-attention layers, which change from Gated MLA to Gated DSA. So this PR reuses the K3 backbone, adds the DSA layers with DSV4's existing top-k selection and indexer loss, and runs the sparse attention with Attention Gym's gather_attn.
I've already checked the model code, model accuracy, test cases, and the model README.md
Why
Kimi K3.1 Pro (RFC #5936) is Kimi K3 with its 24 Gated MLA layers replaced by Gated DeepSeek Sparse Attention (DSA). torchtitan cannot build, train or load it today.
What changed
torchtitan/models/kimi_k3/dsa.py: the indexer and the sparse attention. Top-k selection and the indexer loss are imported fromdeepseek_v4/compressor.py; DSV4 is not changed. Attention over the selected tokens runs Attention Gymgather_attnwith(latent, rope)pairs, underspmd.no_typecheck()as in DSV4.KimiSparseAttention.Config.implpicks thegather_attnimplementation ("fused"by default).torchtitan/models/kimi_k3_1/, flavors only likeqwen3_6:flavors.py:debugmodelandKimi-K3.1-Pro(text only), plusdebugmodel_mmandKimi-K3.1-Pro_mmwith the vision encoder, built with the K3 config builder like the K3 flavors.build_model_configraises unless each TP rank has 16 to 128 query heads, which the pair kernel needs.padding_maskandaux_loss_denominatorto Kimi MLA attention. K3 ignores them; the K3.1 DSA attention uses them.KimiK3Modelregisters the aux-loss zero hook, andKimiK3StateDictAdaptermaps the five indexer tensors. Both are no-ops for K3.kimi_k3_configtakes afull_attention_config_factory.mla_attention_configis split out ofmla_configso K3.1 reuses the MLA projections.kimi_k3_1_fsdp2_tp2_ep2_pp2_vpp4in the B200 integration suite, the same shape as the K3 cell, without a golden for now.Numerics
Testing
The H100 Kimi integration tests (
kimi_k3_mm_allgather_kv_cp,kimi_k3_mm_ulysses_cp) pass on 2x H100.Known issues / follow-ups
gather_attnhas no deterministic backward for(latent, rope)pairs yet, so K3.1 raises withdebug.deterministic = True, and the integration test has no golden: gather_attn: deterministic backward for (latent, rope) pairs meta-pytorch/attention-gym#795.InnerIndexerandSparseIndexerLoss. Move them tomodels/common/after [QSA] sparseindexerloss teacher #5863 lands.KimiDSAAttentionsubclassesKimiMLAAttentionon purpose: the MLA weights are the same, so the K3 HF mapping and Muon grouping apply as is.