Repository navigation
[lora] Derive adapter sharding from the base weight - #5884
Conversation
|
@claude review this pr |
There was a problem hiding this comment.
Verdict: Approve -- please address the items below before merging. The new rule gives the same adapter placements for every base that main supports, and it fixes the build-time assert for vision, router, and other TP-R or TP-I bases. A maintainer still needs to review, since this touches models/common/.
What this PR does. _LoRALinearMixin._adapter_sharding no longer compares the base weight against two hardcoded dense_param_placement values. It now copies the base weight's SpmdType and changes only the TP axis:
- Column-wise base: A is TP-replicated and B is sharded like the base.
- Row-wise base: A is sharded on the input dim and B is TP-replicated.
- R or I base: both adapters copy the base.
The stacked (num_linears > 1) branch is folded into the same rule, with the output dim shifted to 1.
Example.
fc1: vision_colwise weight {dp: R, cp: I, tp: S(0)}
main: AssertionError (!= dense_param_placement(tp=S(0)) because cp=I)
PR: lora_a {dp: R, cp: I, tp: R}, lora_b {dp: R, cp: I, tp: S(0)}
router gate / qwen3_5 sigmoid gate: weight dense_param_placement(tp=R)
main: AssertionError (falls through to `assert == tp=S(1)`)
PR: lora_a = lora_b = dense_param_placement(tp=R)
w13 stacked_colwise: weight dense(tp=S(1)), num_linears=2
main == PR: lora_a dense(tp=R), lora_b dense(tp=S(1))
Must fix
torchtitan/models/common/lora.py:147: the fallback copies any non-Shard TP type, includingP/V, which would silently give wrong numerics. Allow onlyNone/R/Iand raise otherwise. This also replaces the separateShardbranch (see the inline comment).
Should consider
tests/unit_tests/cpu/models/common/test_lora.py:822:fc2usesbias=True, so its LoRA path runs underspmd.no_typecheck(). The row-wise vision adapters are checked only by numerics, not by SPMD typecheck as the description says.
Details
- Necessity: this is a real problem on the base branch. Any base weight other than
dense(tp=S(0))hits theassertat the oldlora.pyrow-wise branch. That covers router gates (moe/sharding.py:107), the qwen3_5 sigmoid gate, and all vision linears (cp=I). - Unchanged placements: for dense bases,
with_tp(R)equalsdense_param_placement(tp=R)because DP and CP are alreadyR. Stacked column-wise (stacked_colwise_sharding_config,S(1)) gives the same result as the deleted branch. Every in-reponum_linears=2linear base usesS(1)(stacked column-wise) orR. None hits the newValueError. - Stacked row-wise (
S(2)): this is newly handled as AS(1)and BR, which is correct. On main it would have copiedS(2)onto B[N, O, L]and sharded the rank dim. It has no in-repo consumer, but it falls out of the general rule with no extra code. - Row-wise math: A
S(1)on a TP-sharded input gives a partial rank activation. BRkeeps it partial, so it adds to the partial base output before the base'sP -> I/P -> Sreduction. Column-wise: ARon the gathered input, then BS(0)gives the same output sharding as the base. - Grouped LoRA:
_grouped_lora_adapter_shardingstill uses exact-equality checks. That is fine for this PR's scope.
Not verified: the GPU/FSDP paths. The TP-R adapter grads rely on FSDP to reduce the TP-partial grad, as on main.
| state_shardings={"weight": dense_param_placement(tp=spmd.S(1))}, | ||
| ) | ||
| return lora_a_sharding, replicated_weight | ||
| return original_sharding, original_sharding |
There was a problem hiding this comment.
This fallback copies any non-Shard TP type to both adapters, but copying is only correct for R and I (and for a missing TP axis). A P or V base weight would give (sum_i A_i)(sum_j B_j) or per-rank adapters, and that numerics bug would be silent. No in-repo base uses these today, but the docstring says "any other base TP type" and principle 8 says to raise on unsupported placements. A smaller rule: allow None, R, and I, and raise ValueError for everything else. That also replaces the separate isinstance(base_tp, spmd.Shard) branch:
| return original_sharding, original_sharding | |
| if base_tp not in (None, spmd.R, spmd.I): | |
| raise ValueError( | |
| f"LoRA does not support base weight TP type {base_tp} with " | |
| f"num_linears={num_linears}." | |
| ) | |
| return original_sharding, original_sharding |
(If you take this, delete the isinstance(base_tp, spmd.Shard) block above it.)
| fc2=InvariantRowParallelLinear.Config( | ||
| in_features=32, | ||
| out_features=16, | ||
| bias=True, |
There was a problem hiding this comment.
With bias=True, InvariantRowParallelLinear.forward runs self._linear (including the LoRA path) under spmd.no_typecheck() (torchtitan/models/common/vision_encoder.py:81). So typecheck(local=False) never checks the row-wise vision adapters. Only the TP2-vs-TP1 numerics comparison covers them. That comparison catches wrong placements, so the test still guards the regression. But the description says it runs "with SPMD type checking", which doesn't hold for this projection. You can either set bias=False here so the adapter types get checked too, or change the description.
tianyu-l
left a comment
There was a problem hiding this comment.
sounds good, didn't check details
## Summary (human-written)
The current LoRA adapter assumes the sharding of the base weights to be `{DP: R, CP: R, TP: S(0)}` or ` {DP: R, CP: R, TP: S(1)}`. This is not always true. For example, if we apply LoRA to the vision encoder, the sharding is not the same.
This PR fixes the issue by deriving adapter sharding from the base weight
## Why
On main, LoRA adapter sharding accepts only a base weight equal to dense_param_placement(tp=S(0)) or dense_param_placement(tp=S(1)). Any other base placement fails at model build. This blocks LoRA on vision linears (CP-invariant, cp=I), TP-invariant vision adapters and projections (tp=I), and TP-replicated router gates (tp=R).
**Example.**
```
LoRATransform(target_modules=["vision_encoder.block.mlp.fc1"]) # Muse Spark, base weight {dp: R, cp: I, tp: S(0)}
before: AssertionError at build (placement is not dense_param_placement(tp=S(0)))
after: lora_a {dp: R, cp: I, tp: R}, lora_b {dp: R, cp: I, tp: S(0)}
```
## What changed
- Adapters copy the base weight placement and change only the TP axis. Other axes, such as cp=I on vision weights, are kept.
- Column-wise base: A is TP-replicated, B is sharded like the base.
- Row-wise base: A is sharded like the base, B is TP-replicated.
- Any other TP type (R, I): both adapters copy the base.
- Any other Shard raises ValueError.
- Stacked projections ([num_linears, O, I]) use the same rule, with the output dim at 1. The separate stacked code path is removed.
## Numerics
Unchanged for the bases main supports: the adapter placements for dense column-wise and row-wise bases, and for stacked column-wise bases, are the same as on main. No loss comparison was run.
## Testing
- 2-rank CPU test with SPMD type checking: LoRA output and adapter grads of a Spark-style vision MLP and vision adapter at TP2 match TP1 (fp32, atol=rtol=1e-4). It catches wrong adapter placements on non-dense bases.
- CPU tests at this commit: tests/unit_tests/cpu/models/common/test_lora.py, 32 passed.
stack-info: PR: pytorch#5884, branch: fegin/stack/13
## Summary (human-written)
The current LoRA adapter assumes the sharding of the base weights to be `{DP: R, CP: R, TP: S(0)}` or ` {DP: R, CP: R, TP: S(1)}`. This is not always true. For example, if we apply LoRA to the vision encoder, the sharding is not the same.
This PR fixes the issue by deriving adapter sharding from the base weight
## Why
On main, LoRA adapter sharding accepts only a base weight equal to dense_param_placement(tp=S(0)) or dense_param_placement(tp=S(1)). Any other base placement fails at model build. This blocks LoRA on vision linears (CP-invariant, cp=I), TP-invariant vision adapters and projections (tp=I), and TP-replicated router gates (tp=R).
**Example.**
```
LoRATransform(target_modules=["vision_encoder.block.mlp.fc1"]) # Muse Spark, base weight {dp: R, cp: I, tp: S(0)}
before: AssertionError at build (placement is not dense_param_placement(tp=S(0)))
after: lora_a {dp: R, cp: I, tp: R}, lora_b {dp: R, cp: I, tp: S(0)}
```
## What changed
- Adapters copy the base weight placement and change only the TP axis. Other axes, such as cp=I on vision weights, are kept.
- Column-wise base: A is TP-replicated, B is sharded like the base.
- Row-wise base: A is sharded like the base, B is TP-replicated.
- TP-replicated or TP-invariant base (R, I), or no TP axis: both adapters copy the base.
- Any other TP type (another Shard, P, V) raises ValueError.
- Stacked projections ([num_linears, O, I]) use the same rule, with the output dim at 1. The separate stacked code path is removed.
## Numerics
Unchanged for the bases main supports: the adapter placements for dense column-wise and row-wise bases, and for stacked column-wise bases, are the same as on main. No loss comparison was run.
## Testing
- 2-rank CPU test with SPMD type checking: LoRA output and adapter grads of a Spark-style vision MLP and vision adapter at TP2 match TP1 (fp32, atol=rtol=1e-4). It catches wrong adapter placements on non-dense bases.
- CPU tests at this commit: tests/unit_tests/cpu/models/common/test_lora.py, 32 passed.
stack-info: PR: #5884, branch: fegin/stack/13
## Summary (human-written)
<!-- Write this yourself, not with an AI tool. 2-5 sentences: the
problem, why
this approach, and what you checked yourself. -->
Add another LORA supporting method for MOE layer: shared-outer adapter
layout for routed experts.
Comparing with per-expert lora, this shared lora way.:
* Smaller adapters and syncs
* Cheaper to serve
* Every routed token trains the shared factor
## Why
Grouped LoRA gives every expert its own `A` and `B` (`A [E, L, I]`, `B
[E, O, L]`). Serving engines and other trainers lay expert adapters out
the other way, "shared-outer": the factor on the model-dimension side of
each routed projection is shared across the experts (`A` of W13, which
reads the hidden stream; `B` of W2, which writes it) and only the other
factor is per expert. A token's low-rank path then reads and writes the
hidden stream through one matrix, and the adapter volume no longer
scales with the model dimension per expert. SGLang serves both layouts,
but its tuned MoE LoRA plans target shared-outer, Megatron-Bridge and
miles train it, and it is the one an RL trainer wants to sync every
step. The layout is fixed in `_build_grouped_lora_adapters`, so a
trainer that needs it has no way to ask for it.
Before: `LoRATransform(rank=8)` on a W13 `[E, 2, F, D]` gives `lora_a
[E, 8, D]`, `lora_b [E, 2, F, 8]`; no other shape is reachable.
After: `LoRATransform(rank=8, expert_adapter_layout="shared_outer")`
gives `lora_a [8, D]` (shared), `lora_b [E, 2, F, 8]`; for W2, `lora_a
[E, 8, F]`, `lora_b [D, 8]` (shared). The default stays `per_expert`.
## What changed
- `LoRATransform.expert_adapter_layout: Literal["per_expert",
"shared_outer"] = "per_expert"`. Under `shared_outer`, the `w13` of a
`RoutedExperts.Config` or `DistMoeRoutedExperts.Config` gets
`shared_factor="lora_a"` and its `w2` gets `"lora_b"`; a grouped
projection under any other parent, or with any other name, is refused
with `ValueError`. The grouped LoRA config's `shared_factor` is
`Literal["lora_a", "lora_b"] | None` with no default, and both adapter
factors are typed `Linear | GroupedLinear`.
- `torchtitan_recipes/tests/models/qwen3_5.py`:
`qwen35_debugmodel_moe_lora_shared_outer`, the per-expert debug recipe
with the option, registered in `tests/integration_tests/h100.py` next to
`qwen3_5_moe_lora`.
- `torchtitan/models/common/lora.py`: the grouped LoRA config carries
`shared_factor`; the shared factor is built as a plain `Linear` without
the expert axis, with the sparse family's replicated placement where the
base weight is split by expert (the placement a parameter shared across
experts already uses, kept in step under EP by
`test_fsdp_moe_sharding`), and the base placement otherwise.
`_adapter_matmul` uses `_grouped_mm` for both layouts; a shared factor
is cast to bf16 once and broadcast through a stride-0 expanded expert
axis, so rows past `offsets_E[-1]` cannot contaminate its gradient and
no `E × L × D` contiguous weight copy is needed. Dist-MoE materializes
`W + scale * B @ A` with the same single `baddbmm` as before;
`_adapter_operands` hands it a shared factor as a stride-0 expanded
view, so no extra full-size temporary.
- Mechanical: `_create_lora_class` is split into the two `get_lora_*`
builders so only the grouped config carries the new field.
## Numerics / performance
Per-expert layout is unchanged: same adapters, same grouped matmuls,
same `baddbmm` materialization. The shared-outer layout is new behavior
with no golden losses.
## Testing
- `test_shared_outer_matches_per_expert_with_grouped_bias`: fused W13
(`num_linears=2`) and GPT-OSS grouped bias match the equivalent
per-expert layout in forward and backward on CPU; the same equivalence
check also passed on CUDA.
- `test_shared_adapter_gradients_ignore_uninitialized_tail_rows`: for
W13 `lora_a` and W2 `lora_b`, NaN-poisoned rows after `offsets_E[-1]`
cannot affect valid-row outputs or shared-weight gradients. Both cases
fail before the grouped-matmul fix and pass on CPU and CUDA after it.
- `test_shared_outer_adapters_share_the_model_side_factor`: shapes and
state-dict keys of both projections, forward equal to a per-expert loop
with the shared factor broadcast (bf16 rows, as the grouped matmul
casts), gradients reach all four adapters and no base weight. Catches a
wrong shared side or a wrong operand order.
- `test_shared_outer_adapters_follow_expert_sharding`: shared factors
get the replicated sparse placement, per-expert ones keep the expert
placement.
- `test_shared_outer_rejects_a_grouped_projection_outside_the_experts`.
-
`test_shared_outer_lora_dist_moe_weight_operands_broadcast_the_shared_factor`
(Dist-MoE): effective W13/W2 equal the base plus the broadcast update.
-
`TestSharedOuterLoRAExpertParallel.test_shared_factor_stays_replicated_across_ep`
(GPU, 4 ranks, EP=2 with FSDP on the Qwen3 MoE test config): the shared
factors sit on the sparse mesh, receive gradients with their own
placements, and hold one value on every EP rank after an optimizer step;
the per-expert factors stay expert-sharded. Catches a shared factor
whose EP replicas drift. Passed on 4xH200.
- Cross-check against another trainer's shared-outer grouped adapters
(Megatron, via miles' native LoRA modules): with one adapter set copied
into both, W13 and W2 outputs are bit-identical on CPU and CUDA, and so
are the gradients of every factor (the shared W13 `A` within one bf16
ulp, since that trainer keeps a separate `A` per gate/up branch and
torchtitan shares one).
- `qwen3_5_moe_lora_shared_outer` integration entry (8 GPUs, real
process group): the end-to-end guard for the new layout, next to the
per-expert one.
- Loss curves on the Qwen3.5 MoE debug model for both layouts, 20 steps,
seed 42, deterministic: on one GPU and under FSDP2 x EP2 (tables in the
comments). Both decrease; shared-outer a little slower at the same rank,
as expected from its smaller adapter.
- Latest validation on `01638cc12`, rebased onto main at `bb34c7591` now
that #5884 is merged. On a CPU-only setup with torch nightly
`2.16.0.dev20261110`: all of `tests/unit_tests/cpu` passes (2032 passed,
19 skipped, 3 xfailed); with the optional `dist_moe` package,
`test_lora.py`, `test_dist_moe.py` and `test_transforms.py` give 124
passed, 2 failed, and the same two Dist-MoE cases
(`test_engine_builds_dist_moe_runtime_with_eager_pp_schedule`,
`test_dist_moe_671b_recipe_topology[deepseek_v3_671b_dist_moe_mxfp8-64-240]`)
fail on `main` there. Pre-commit hooks pass on the changed files, and
Pyrefly reports nothing in them.
- Not executed after this rebase: the four-rank GPU EP test and the two
8-GPU Qwen3.5 LoRA integration entries. They last passed on `219984fa1`
(8xH200, and `qwen3_5_moe_lora_shared_outer` in CI's H100 job); the code
since then differs by the rebase and one deleted comment. Real HybridEP
dispatch was not run because the available images do not expose
`deep_ep.HybridEPBuffer`; the padded-tail contract was tested directly
on CUDA instead.
- The H100 job's failure on this PR is
`test_deepep_activation_checkpoint.py` (2 tests), which fails the same
way on `main`'s nightly H100 runs since 2026-11-07.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Mythos 5.1 <[email protected]>
Stacked PRs:
[lora] Derive adapter sharding from the base weight
Summary (human-written)
The current LoRA adapter assumes the sharding of the base weights to be
{DP: R, CP: R, TP: S(0)}or{DP: R, CP: R, TP: S(1)}. This is not always true. For example, if we apply LoRA to the vision encoder, the sharding is not the same.This PR fixes the issue by deriving adapter sharding from the base weight
Why
On main, LoRA adapter sharding accepts only a base weight equal to dense_param_placement(tp=S(0)) or dense_param_placement(tp=S(1)). Any other base placement fails at model build. This blocks LoRA on vision linears (CP-invariant, cp=I), TP-invariant vision adapters and projections (tp=I), and TP-replicated router gates (tp=R).
Example.
What changed
Numerics
Unchanged for the bases main supports: the adapter placements for dense column-wise and row-wise bases, and for stacked column-wise bases, are the same as on main. No loss comparison was run.
Testing