Skip to content

[Kimi K3][LoRA] Support Kimi K3 LoRA training: Export merged adapters, place adapters for every base sharding, step frozen pipeline ranks - #4576

Open
QIU023 wants to merge 5 commits into
pytorch:mainfrom
QIU023:lora_review2
Open

QIU023 wants to merge 5 commits into
pytorch:mainfrom
QIU023:lora_review2

Conversation

@QIU023

@QIU023 QIU023 commented Sep 10, 2026 •

Copy link
Copy Markdown
Contributor

Summary

With its default targets, LoRA on main fails to build the Kimi K3 debug model, cannot export a trained adapter, and fails on a pipeline rank with nothing to train; this PR fixes all three.

  • torchtitan/models/common/lora.py: trainable_state_dict, merge_lora_state_dict, and adapter shardings that follow the TP entry of the base placement.
  • torchtitan/components/optim/optimizer.py, lr_scheduler.py, torchtitan/distributed/utils.py: a rank whose model parts are all frozen gets an empty optimizer and scheduler and still joins the grad norm all-reduce.

Design

  • Export:
    • trainable_state_dict returns the trainable parameters keyed as in state_dict(); under LoRA, the adapters.
    • merge_lora_state_dict returns state_dict() with $W + \frac{\alpha}{r} B A$ in place of each adapted weight and no adapter keys.
    • The merge runs in fp32 on local shards and keeps the base's DTensor placements; only A is gathered, where FSDP shards its rank dim.
    • It works on local shards because DTensor ops cannot unflatten the _StridedShard placement of a stacked w13 under FSDP and TP.
  • Adapter placement:
    • On main, _adapter_sharding asserts that every base is dense_param_placement(tp=S(0)) or dense_param_placement(tp=S(1)); bases that TP does not shard (router gate, MLA wkv_a, forget_a) and vision linears (I on CP) fail that assert when the model is built.
    • The TP entry now decides: S(0) and S(1) keep the column and row rules, R and I give both adapters the base placement, anything else raises.
    • The replicated adapter takes the base placement with TP set to R; for a dense base this is the placement main already uses.
  • Frozen pipeline ranks:
    • A model part with nothing to train is skipped with a log line; a trainable part whose pattern matches nothing still raises.
    • A rank with nothing to train gets one empty param group, no scheduler state, and a zero grad norm on the accelerator; on main that rank's norm is a CPU tensor(0.), which the NCCL all-reduce rejects.

Results

8 x RTX 5060 Ti, kimi_k3_debugmodel (17 layers, dim 256) on the multimodal cc12m-test, 4096 tokens per step, seed 42, deterministic. LoRATransform(rank=8, alpha=16.0) adapts all 290 supported projections. Every cell loads one seed checkpoint, trains 10 steps, then compares the output of merge_lora_state_dict on every rank with $W + \frac{\alpha}{r} B A$ computed from the gathered tensors. Measured at b61c686dc; the two later commits only add a type assertion and the multi_gpu test markers. The cell configs, the merge check and the runners are in this kit, not in this PR.

Step 1 is identical to its reference in every layout without TP or CP and within 0.005% with TP or CP. On every rank of every layout, every merged weight is bitwise identical to $W + \frac{\alpha}{r} B A$ computed from the gathered tensors.

cell GPUs loss, step 1 step 10 merged vs expected, max abs diff [3]
dp1 [1] 1 8.13623 7.09263 0
290 on 1 rank
pp2 2 8.13623
identical
7.09142 0
290 on 2 ranks
pp4 4 8.13623
identical
7.09344 0
290 on 4 ranks
pp8 8 8.13623
identical
7.09142 0
290 on 8 ranks
tp2 x ep2 2 8.13642
+0.0023%
7.09488 0
580 on 2 ranks
tp4 x ep4 4 8.13640
+0.0021%
7.09517 0
1160 on 4 ranks
cp2 2 8.13626
+0.0004%
7.09520 0
580 on 2 ranks
ep2 x tp2 x pp2 x cp2 8 8.13628
+0.0006%
7.09160 0
1160 on 8 ranks
fsdp2 [1] 2 8.18727 7.17045 0
580 on 2 ranks
ep2 x fsdp2 2 8.18727
identical
7.17250 0
580 on 2 ranks
ep4 x fsdp2 x tp2 x pp2 8 8.18761
+0.0042%
7.17034 0
1160 on 8 ranks
ep2 x fsdp2 x tp2 x pp2 8 8.18761
+0.0042%
7.17220 0
1160 on 8 ranks
fsdp2 x pp2 x cp2 8 8.18745
+0.0022%
7.17252 0
1160 on 8 ranks
ep2 x fsdp2 x pp2 x cp2 8 8.18745
+0.0022%
7.17073 0
1160 on 8 ranks
ep4 x fsdp2 x tp2 x cp2 8 8.18752
+0.0031%
7.17260 0
2320 on 8 ranks
ep2 x fsdp2 x tp2 x cp2 8 8.18752
+0.0031%
7.17260 0
2320 on 8 ranks
ep8 x fsdp8 [1] 8 8.16220 7.07305 0
2320 on 8 ranks
cp4 [1] 4 8.14816 7.34267 0
1160 on 4 ranks
pp4 x vpp2, MLA only [2] 4 8.10062 7.97847 0
25 on 4 ranks
pp8, MLA only [2] 8 8.10062
identical
7.97848 0
25 on 8 ranks
  • [1] reference row: dp1, fsdp2, ep8 x fsdp8 and cp4 (512 token sequences) each read a different sample stream; the rows under a reference read the same samples as it
  • [2] target_modules = the MLA projections, so the stages that hold only KDA layers have nothing to train: pp4 x vpp2 puts a frozen stage next to a trainable one on three ranks, and pp8 leaves three ranks with nothing to train; both layouts rely on this PR's optimizer, scheduler and grad norm changes
  • [3] after step 10, the largest |merged - expected| over every adapted weight shard on every rank, where expected is $W + \frac{\alpha}{r} B A$ computed in fp32 from the gathered tensors and cast to the weight's dtype; the count is the shards checked (580 on 2 ranks: all 290 adapted weights, sharded on both ranks; a pipeline stage holds only its own layers)
  • step 10 is shown, not compared: each GPU group compiled on its own cache, and the 32 sample set repeats within 10 steps

Test plan

pytest tests/unit_tests/cpu/models/common/test_lora.py                          # 39 passed (10 new)
pytest tests/unit_tests/cpu/components/optim/test_optimizer_param_groups.py     # 32 passed (2 new)
pytest tests/unit_tests/cpu/components/optim/test_lr_scheduler.py               # 10 passed (1 new)
pytest tests/unit_tests/gpu/models/common/test_lora.py                          # 1 passed, 4 GPUs
pytest tests/unit_tests/gpu/distributed/test_clip_grad_norm.py                  # 1 passed, 2 GPUs

The GPU merge test covers a stacked w13 under TP2 x FSDP2; the clip test raises No backend type associated with device type cpu on main. pyrefly check reports the same errors as main.

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Sep 10, 2026
@QIU023
QIU023 marked this pull request as draft September 10, 2026 09:07
trainable_state_dict returns the parameters left trainable, keyed as in state_dict(): under LoRA, the adapters, which
is what an adapter checkpoint or a trainer-to-rollout sync ships. merge_lora_state_dict returns state_dict() with each
base weight replaced by W + (alpha / rank) * B @ A and the adapter keys removed, the form a state-dict adapter can
convert like the unadapted model's.

The merge runs in fp32 on each rank's local shards and casts back to the base dtype. B is sharded like the base's
output rows, A is gathered only where FSDP cuts its rank dimension, and the result keeps the base's DTensor placements,
so no base weight is gathered. DTensor ops on the sharded tensors fail on a stacked w13 under FSDP and TP, whose
_StridedShard placement cannot be unflattened.
_adapter_sharding compared the base weight's placement with dense_param_placement(tp=S(0)) and asserted that every
other base was dense_param_placement(tp=S(1)). Two kinds of base failed that assert at build, so LoRATransform with its
default targets could not build deepseek_v3, deepseek_v4, gpt_oss, qwen3_5, kimi_k2_5 or kimi_k3: bases that TP does
not shard (R when tokens are TP-sharded, I otherwise), such as the MoE router gate and the MLA down projections, and the
vision encoder's column and row parallel linears, which are I rather than R on CP.

The adapters now follow the TP entry of the base placement: S(0) and S(1) keep the column and row rules, R and I give
both adapters the base placement, and any other TP placement raises. The replicated adapter copies the base placement
with TP set to R, so its DP and CP entries are the base's; for a dense base that is dense_param_placement(tp=R) as before.
Adapter training under pipeline parallelism can leave a stage with nothing trainable, for example a stage whose layers
no LoRA target matches. The optimizer container raised "matched no parameters" for such a model part; it now skips the
part with a log line, and a part that trains still raises on a pattern that matches nothing.

When every part on a rank is frozen, the container still initializes as an Optimizer with one empty parameter group,
the LR scheduler container holds no scheduler and saves and loads no state, and clip_grad_norm_ puts the rank's zero
norm on the accelerator so it joins the pipeline all-reduce; it was a CPU tensor, which NCCL rejects.
@pytorch-bot

pytorch-bot Bot commented Oct 12, 2026 •

Copy link
Copy Markdown

The following ciflow label(s) have been added but CI has not been triggered yet because the workflows are awaiting approval:

  • ciflow/rl
  • ciflow/fake-pg

Once a maintainer approves the workflows (scroll to the bottom of the PR page), the corresponding CI jobs will be triggered automatically. Please ping one of the reviewers if you do not have access to approve and run workflows.

pyrefly reads module.lora_a.weight as a Parameter, so the DTensor calls in the sharded branch of _merged_weight
failed the type check. The adapters are DTensors whenever the base is; the branch now asserts it.
@QIU023 QIU023 changed the title [DO NOT review, draft, pending reconciling with other QAT changes] [Kimi K3] Support LoRA and QLoRA (NF4 and packed MXFP4) [Kimi K3][LoRA] Export merged adapters, place adapters for every base sharding, step frozen pipeline ranks Oct 13, 2026
@QIU023 QIU023 changed the title [Kimi K3][LoRA] Export merged adapters, place adapters for every base sharding, step frozen pipeline ranks [DO NOT review][Kimi K3][LoRA] Export merged adapters, place adapters for every base sharding, step frozen pipeline ranks Oct 13, 2026
Both tests spawn a process group (2 and 4 ranks). Without the marker they land in the single-GPU lane, where the device-count guard skips them, and the multi_gpu lane does not select them.
@QIU023 QIU023 changed the title [DO NOT review][Kimi K3][LoRA] Export merged adapters, place adapters for every base sharding, step frozen pipeline ranks [Kimi K3][LoRA] Export merged adapters, place adapters for every base sharding, step frozen pipeline ranks Oct 14, 2026
@QIU023
QIU023 marked this pull request as ready for review October 14, 2026 08:47
@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Oct 14, 2026
@QIU023 QIU023 changed the title [Kimi K3][LoRA] Export merged adapters, place adapters for every base sharding, step frozen pipeline ranks [Kimi K3][LoRA] Support Kimi K3 LoRA training: Export merged adapters, place adapters for every base sharding, step frozen pipeline ranks Oct 19, 2026
@QIU023 QIU023 mentioned this pull request Oct 19, 2026
14 of 18 tasks

This branch has not been deployed

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

Labels

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.

1 participant