Repository navigation
[lora] shared-outer adapter layout for routed experts - #5738
Conversation
|
|
|
The following ciflow label(s) have been added but CI has not been triggered yet because the workflows are awaiting approval:
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. |
6c6a926 to
e95a230
Compare
|
@claude review |
There was a problem hiding this comment.
Verdict: Request changes -- this adds a new user-facing LoRA layout knob with no in-repo consumer and no named downstream user, and nothing in the repo can export the adapters it produces today.
What this PR does. It adds LoRATransform.expert_adapter_layout ("per_expert", the default, or "shared_outer"). With "shared_outer", the routed-expert w13 gets a single lora_a shared by all experts, and w2 gets a single lora_b. Each shared factor is built as a plain Linear with the sparse replicated placement. The GroupedLinear forward applies it as a dense matmul. Dist-MoE broadcasts it into the existing baddbmm through a stride-0 expand. The default path is unchanged: same adapters, same grouped matmuls, same baddbmm operands (the W2 flatten(1, -2) on [E, O, L] is a no-op).
Example.
W13 [E=4, 2, F, D], W2 [E=4, D, F], rank=8
per_expert : w13.lora_a [4, 8, D] w13.lora_b [4, 2, F, 8]
w2.lora_a [4, 8, F] w2.lora_b [4, D, 8]
shared_outer : w13.lora_a [8, D] w13.lora_b [4, 2, F, 8]
w2.lora_a [4, 8, F] w2.lora_b [D, 8]
EP=2: the shared factors use {dp_replicate: R, edp_shard: R, ep: R}, and their
gradients are reduced over EP, so the replicas stay equal.
Must fix
- Description: "Summary (human-written)" is empty. A maintainer-facing summary written by the author is required (
CONTRIBUTING.md, AI-assisted contributions). - Consumer / value (gate): no recipe, test config, or exporter in the repo uses
shared_outer. The stated goal is that "an adapter trained here can be served there." Buttorchtitan/models/common/lora.py:43-45says native DCP and HF state-dict adapters do not carrylora_a/lora_bat all, so neither layout can leave torchtitan today. Please name the concrete consumer: which serving engine expects this layout, and which trainer or recipe (miles/Megatron?) will use the option. Either land it together with that consumer (recipe, export path), or explain why the knob should land first. The docstring claim attorchtitan/config/transform/lora.py:223("as serving engines expect of expert adapters") needs that same reference, or should be removed. torchtitan/models/common/lora.py:426--shared_factoruses a"none"sentinel plus an unneeded default. UseLiteral["lora_a", "lora_b"] | Nonewith no default (inline).
Should consider
torchtitan/config/transform/lora.py:136-- the shared side is inferred from the field name alone. Also gate it on the parent beingRoutedExperts.Config/DistMoeRoutedExperts.Config(inline).tests/unit_tests/gpu/distributed/test_fsdp_moe_sharding.py:429-- the comment misdescribes which factors are perturbed (inline).- Numerics: this is a new training mode with no loss curve. A short Qwen3-MoE debug run,
shared_outervsper_expert, showing the loss decreases (and, under EP=2, that it matches EP=1) would back up the PR more than the unit-level checks do.
Questions
- Under
shared_outer, W13 shares oneAacross gate and up, while the description says Megatron/miles keeps a separateAper branch. That means an adapter trained there can't be loaded here without being merged lossily. Is a one-way export (duplicatingA) enough for the target workflow?
Details
- Padding/tail rows: the W13 path ends in a grouped
lora_b, and the W2 path applies the denseBto the groupedlora_aoutput. So rows pastoffsets_E[-1]match the base grouped matmul in both projections (relevant to theGptOssGroupedLineartail-bias handling). - Sharding:
_grouped_lora_adapter_shardingstill runs first, so unsupported base placements still raise before_shared_lora_adapter_shardingfalls back to the base placement. The EP gradient reduction forreplicated_param_placement_sparseuses the same mechanism as muse_spark'spost_expert_norm. - The
_create_lora_classsplit is mechanical and adds about 8 lines. It is acceptable, since only the grouped config carries the new field. - No overlapping open PR found.
Not verified: the GPU EP test (needs 4 GPUs), and whether baddbmm with a stride-0 batch operand avoids a copy on CUDA. Any such copy would be adapter-sized, not weight-sized. A maintainer still needs to review, since this touches models/common/.
| shared_factor: Literal["none", "lora_a", "lora_b"] = "none" | ||
| """Adapter factor every expert shares; ``"none"`` keeps both per expert.""" |
There was a problem hiding this comment.
"none" is a disabled sentinel, which rules/config.md asks us to avoid. The field also has a default even though its only constructor, _make_grouped_linear_lora_config, always passes it. Make it required and optional-by-None:
| shared_factor: Literal["none", "lora_a", "lora_b"] = "none" | |
| """Adapter factor every expert shares; ``"none"`` keeps both per expert.""" | |
| shared_factor: Literal["lora_a", "lora_b"] | None | |
| """Adapter factor every expert shares; ``None`` keeps both per expert.""" |
Then update _shared_factor / _make_grouped_linear_lora_config (transform) and _build_grouped_lora_adapters to use Literal["lora_a", "lora_b"] | None, returning None for per_expert.
There was a problem hiding this comment.
Done: Literal["lora_a", "lora_b"] | None, no default.
| shared = _SHARED_OUTER_FACTOR.get(cast(str, attr)) | ||
| if shared is None: | ||
| raise ValueError( | ||
| "expert_adapter_layout='shared_outer' knows the routed-expert " | ||
| f"projections w13 and w2 only, got grouped projection {fqn!r}." | ||
| ) | ||
| return cast(Literal["lora_a", "lora_b"], shared) |
There was a problem hiding this comment.
The model-side role is inferred from the bare field name (attr == "w13" / "w2"). The thing that actually defines those roles is the parent config: RoutedExperts.Config validates w13.num_linears == 2 and w13.in_features == w2.out_features, and DistMoeRoutedExperts.Config has the same fields. Today the inference happens to be correct. But a GroupedLinear.Config field named w2 under any other parent would silently get the shared-B layout, and an error that says "w13 and w2 only" makes the restriction look like a naming rule.
Suggest also checking isinstance(parent, (RoutedExperts.Config, DistMoeRoutedExperts.Config)) (the transform already has parent in the loop), so the shared side follows the routed-expert contract and not just a field name.
There was a problem hiding this comment.
Done: the shared side is chosen only under a RoutedExperts or DistMoeRoutedExperts parent.
| # perturb the per-expert factor so the shared one receives a gradient | ||
| with torch.no_grad(): | ||
| experts.w13.lora_b.weight.normal_() | ||
| experts.w2.lora_b.weight.normal_() |
There was a problem hiding this comment.
This comment doesn't match the code. w13.lora_b is per expert, but w2.lora_b is the shared factor. Only the first normal_() is needed for a shared factor (w13.lora_a) to get a nonzero gradient; w2.lora_b gets one either way. The second perturbation actually serves to give the per-expert w2.lora_a a gradient. Please reword so the next reader doesn't think both lines perturb per-expert factors, e.g. "perturb the zero-initialized B factors so every adapter receives a nonzero gradient".
|
@HJSang thanks a lot!
Could you share some code pointers / references for us to learn more? My main question would be that if "shared-outer" mode should be the only mode. cc @fegin |
|
@tianyu-l thanks for looking. Pointers: Serving (SGLang). The layout was introduced in sgl-project/sglang#21466 and is the only expert-LoRA layout its MoE LoRA path implements: Training (Megatron-Bridge). What the layout means. For W13 (reads the hidden stream, Consumer. The RL trainer in radixark/miles uses torchtitan as a training backend and serves adapters through SGLang after every step; today its torchtitan path can only adapt attention on MoE models for this reason, while its Megatron path trains shared-outer expert adapters. The export of these adapters under the HF/SGLang names lives in miles (the same code path it uses for fused q/k/v, which also share one Only mode? I kept |
|
Correction to my pointers above: SGLang serves per-expert expert adapters too (numbered |
tianyu-l
left a comment
There was a problem hiding this comment.
re claude comments of no consumer, please add an entry similar to https://github.com/pytorch/torchtitan/blob/main/torchtitan_recipes/tests/models/qwen3_5.py#L180
and guard it in integration tests
| shared = _SHARED_OUTER_FACTOR.get(cast(str, attr)) | ||
| if shared is None: | ||
| raise ValueError( | ||
| "expert_adapter_layout='shared_outer' knows the routed-expert " | ||
| f"projections w13 and w2 only, got grouped projection {fqn!r}." | ||
| ) | ||
| return cast(Literal["lora_a", "lora_b"], shared) |
| lora_a: Module | ||
| lora_b: Module |
There was a problem hiding this comment.
they should be either GroupedLinear or Linear?
There was a problem hiding this comment.
Yes, both are typed Linear | GroupedLinear now; that is also what the pyrefly failure was about.
| shared_factor: Literal["none", "lora_a", "lora_b"] = "none" | ||
| """Adapter factor every expert shares; ``"none"`` keeps both per expert.""" |
fegin
left a comment
There was a problem hiding this comment.
- Please fill in the motivation to the summary, human written. Looks like the motivation is mostly compatibility to SGLang.
- If I understand correctly per-expert -> shared-out is lossless while shared-out -> per-expert is lossy. So we should still keep per-expert as the default. And per claude, vllm uses per-expert, so we should keep both, cc. @tianyu-l
1c153d8 to
0bf865a
Compare
|
Rebased on main and addressed the review: shared_factor is Literal["lora_a", "lora_b"] | None with no default, the adapter factors are typed Linear | GroupedLinear (fixes the lint job), the shared side is gated on a RoutedExperts / DistMoeRoutedExperts parent, and the test comment is reworded. In-repo consumer: qwen35_debugmodel_moe_lora_shared_outer in torchtitan_recipes/tests/models/qwen3_5.py with an h100 integration entry next to the per-expert one. Per-expert stays the default and both layouts stay, per @fegin. The rl-b200 failure is the runner missing numactl. Loss curves for both layouts on the debug model follow. |
|
Loss curves,
Both layouts train; shared_outer descends a little slower at the same rank, as expected from its smaller adapter. |
Thanks for the comments |
|
@claude review — the requested changes are addressed on the rebased branch: shared_factor is Literal["lora_a", "lora_b"] | None with no default, the shared side is gated on a RoutedExperts / DistMoeRoutedExperts parent, the test comment is reworded, and the in-repo consumer is qwen35_debugmodel_moe_lora_shared_outer with an h100 integration entry. Please re-review and lift the request for changes. |
The torchtitan backend adapted Linear projections only; a target that reached a MoE's routed experts was refused, so MoE models trained attention adapters alone. torchtitan's grouped LoRA (with the shared-outer layout, pytorch/torchtitan#5738) adapts the experts; this is the miles side of it. The conversion walks GroupedLinear projections too, naming them through the state-dict adapter like the base weights and collapsing the expert index (experts.3.gate_proj -> experts.gate_proj, a gate/up pair folded into the packed gate_up_proj the engine's expert buffers use), so the HF target table's packed selectors match them. A target that reaches an expert projection requires --experts-shared-outer-loras, the layout the engine serves, and the transform is built with expert_adapter_layout="shared_outer"; w13 then shares lora_A across the experts and w2 shares lora_B. The export sends the per-expert factor through the adapter, which names and splits it per expert, restacks the parts into one tensor per packed module (experts.gate_up_proj.lora_B [E, 2F, r]), and ships the shared factor once with an expert axis of 1: the format miles' Megatron native path emits and sglang detects. Under EP the per-expert factor is gathered to the full tensor first. Qwen3-30B-A3B e2e: 4 trainer GPUs (TP2, EP2) and two engines, rank-32 adapters on attention and experts; the engine reports the shared-outer layout and loads down_proj, gate_up_proj, o_proj and qkv_proj adapters on every sync. Co-Authored-By: Claude Mythos 5.1 <[email protected]>
|
@claude review again |
There was a problem hiding this comment.
Verdict: Approve -- please address the item below before merging. Every must-fix from the previous review is resolved at 0bf865a, and the new commits introduce no correctness problems.
What changed since the last review. shared_factor is now a required Literal["lora_a", "lora_b"] | None. The shared side is chosen only when the parent is RoutedExperts.Config or DistMoeRoutedExperts.Config. Both adapter factors are typed Linear | GroupedLinear. A recipe (qwen35_debugmodel_moe_lora_shared_outer) and an h100 integration entry now consume the option.
Example.
LoRATransform(rank=8, target_modules=["w13", "w2"], expert_adapter_layout="shared_outer")
routed_experts.w13 (parent RoutedExperts.Config) -> lora_a [8, D] shared, lora_b [E, 2, F, 8]
routed_experts.w2 (parent RoutedExperts.Config) -> lora_a [E, 8, F], lora_b [D, 8] shared
a GroupedLinear named w2 under any other parent -> ValueError (previously: silently shared-B)
Earlier items
- Human-written summary: resolved. It states the motivation (smaller adapters and syncs, cheaper serving, the shared factor trained on every routed token).
- No in-repo consumer: resolved. The miles RL trainer is named as the downstream user, and
torchtitan_recipes/tests/models/qwen3_5.py:790plustests/integration_tests/h100.py:225exercise the option under FSDP2 + PP2 + EP4 + TP2, per @tianyu-l's request. "none"sentinel with a default: resolved (torchtitan/models/common/lora.py:773).- Shared side inferred from the field name alone: resolved (
torchtitan/config/transform/lora.py:420). The transform walks leaves first, soparentis still the original routed-experts config when the child is converted. - GPU test comment: resolved.
- Loss curve: resolved. The author posted runs on 1 GPU and on FSDP2 x EP2 for both layouts; both decrease. EP invariance is asserted by
TestSharedOuterLoRAExpertParallel. - gate/up
Aasymmetry: answered. Export to SGLang is a lossless duplication, and per @feginper_expertstays as the default.
Must fix
- Description: "What changed" still says the shared side is picked by field name ("a grouped target named
w13gets ..."). It also doesn't list the new recipe or the h100 integration entry under Testing. Please update it to match the parent-gated rule and the added consumer.
Details
- Sharding: under the integration config (EP4, ETP 1), the base expert weights use
expert_param_placement_sparse(), so the shared factors getreplicated_param_placement_sparse(). Without EP, the base weight isdense_param_placement(tp=R)and the shared factor reuses it. Any unsupported base placement still raises first in_grouped_lora_adapter_sharding. - Dtype:
_adapter_matmulcasts the shared weight to bf16, matchingGroupedLinear._grouped_mm(torchtitan/models/common/linear/linear.py:455). The per-expert and shared paths therefore use the same operand dtype. - The Dist-MoE parent detection (
cfg.w13._owner is get_lora_grouped_linear(GroupedLinear)) still matches, becauseshared_factoris a config field rather than a separate class. - Integration cost: the new entry is a second 8-GPU run. It could instead be a second element of
configs=[...]on the existingqwen3_5_moe_loraentry. That keeps one test definition, but the GPU time is the same, so either is fine.
Not verified: the h100 integration run and the 4-GPU EP test, since CI is still awaiting workflow approval. This touches models/common/, so a maintainer still needs to review.
| matched_targets.add(target) | ||
| is_target = True | ||
|
|
||
| if isinstance(cfg, DistMoeRoutedExperts.Config): |
There was a problem hiding this comment.
could you make it work for DistMoeRoutedExperts as well? It is currently the most performant MoE backend we have in torchtitan
There was a problem hiding this comment.
Supported. The routed-parent gate includes DistMoeRoutedExperts.Config, and test_shared_outer_lora_dist_moe_weight_operands_broadcast_the_shared_factor verifies the materialized W13/W2 updates for the shared layout. This coverage is included in the final 38 passed, 2 skipped LoRA/Dist-MoE run on 219984fa1.
|
@claude please confirm correctness on:
|
There was a problem hiding this comment.
Verdict: Needs discussion -- the sharding is correct, and so is the compute on every reachable path. One open item: the shared factor's weight gradient may read padded tail rows. I could not verify that (inline at lora.py:270).
Answers
1. Sharding from _build_grouped_lora_adapters.
- per_expert: unchanged. Both adapters still take their placement from
_grouped_lora_adapter_sharding, and both are still built as the sameGroupedLinear.Configs.shared_shardingis computed but not used. Unsupported base placements still raise. - shared_outer: correct under every parallelism below.
| Base weight placement | Shared factor placement | Result |
|---|---|---|
EP on: expert_param_placement_sparse() |
replicated_param_placement_sparse() (R on EP) |
Same mechanism as muse_spark post_expert_norm. FSDP shards over edp_shard and replicates over dp_replicate/ep. Grad division is disabled (fsdp.py:189), so the grad sums contributions from every EP rank. TP/CP are folded into edp_shard. |
EP off: dense_param_placement(tp=R) |
Same placement as the base | Behaves like a dense replicated parameter. |
| No sharding | None |
-- |
PP is unaffected. The GPU test checks that EP replicas stay identical after a step.
2. Compute.
- W13 (
num_linears=2): the shared A[L,D]produces a hidden[R,L]. The per-expert B[E,2,F,L]is flattened to[E,2F,L]byflatten(1,-2). The output is reshaped like the base output. - W2: per-expert A
[E,L,F]and shared B[D,L]. - Dist-MoE operands:
_adapter_operandsreturns[E,O,L]/[E,L,I], which matchesbaddbmmfor both projections. - Shared
lora_bwithnum_linears>1: unreachable, becauseRoutedExpertsand Dist-MoE both validatew2.num_linears == 1. Theflatten(0,-2)would still handle it. - Bias: only
GptOssGroupedLinearhas one. It is frozen by_LoRAMixinand added afterGroupedLinear.forward, i.e. after base + LoRA, which matches the per_expert layout. gpt_oss builds aRoutedExperts.Configparent, so_shared_factoraccepts it.
Must fix
torchtitan/models/common/lora.py:270-- (unverified) the denseF.linearweight gradient contracts over rows pastoffsets_E[-1], which grouped mm never reads. Under HybridEP non-blocking dispatch those rows can be uninitialized. Fix: use a grouped mm with the shared weight expanded across experts (details inline).
Details
- Where tail rows come from: under HybridEP non-blocking dispatch, the output buffer is sized by capacity (
hybridep.py:63-92). DeepEP expand mode also leaves a tail, but that is inference-only. - Where there is no tail: the all-to-all
_permute(R == sum(counts)) and TorchAOpermute_and_pad, whose pad rows sit inside groups and are zero. - The forward is fine: tail outputs are discarded downstream. Only the shared factor's wgrad sees the tail.
- @tianyu-l's comment on
transform/lora.py:305(DistMoeRoutedExperts) is handled at HEAD:_shared_factoraccepts aDistMoeRoutedExperts.Configparent, and_adapter_operandsexpands the shared factor forbaddbmm.
Not verified: what torch._grouped_mm and the HybridEP kernels write to rows past offsets_E[-1]; I did not re-run the EP GPU test.
| offsets_E=offsets_E, | ||
| ) | ||
| # Same operand dtype as the grouped matmul, which casts its weight to bf16. | ||
| return F.linear(input_RI, adapter.weight.flatten(0, -2).bfloat16()) |
There was a problem hiding this comment.
(unverified) The shared factor applies a dense F.linear to all R routed rows. Its weight gradient therefore contracts over rows past offsets_E[-1] as well:
- W13
lora_a:dA = dH^T @ X - W2
lora_b:dB = dOut^T @ H
The per-expert path goes through torch._grouped_mm, which never reads those rows. The codebase treats them as padding that kernels may skip (activation.py:49-51, gpt_oss/moe.py:47).
Such tail rows exist in training under HybridEP non-blocking dispatch: the output buffer is sized by _num_permuted_tokens_for_non_blocking, not by the real token count. In that case H (the per-expert lora_a grouped-mm output) and dH (the per-expert lora_b grouped-mm input grad) can be uninitialized in the tail. The shared-factor grad would then pick up garbage or NaN, which is a silent numerics break. The per_expert layout and the Dist-MoE path (which materializes W + s*B@A) are not affected.
Smallest fix: run the shared factor through the same grouped matmul with a stride-0 expanded weight, so tail rows are skipped exactly as for per_expert. Autograd sums the expand back into the [L, I] / [O, L] grad. Something like:
return torch._grouped_mm(
input_RI,
adapter.weight.flatten(0, -2).bfloat16().unsqueeze(0)
.expand(offsets_E.shape[0], -1, -1).transpose(-2, -1),
offs=offsets_E,
)_grouped_mm may need .contiguous() here, which costs a transient E*L*D copy. Another option is to zero the tail with torch.where(row_idx < offsets_E[-1], ...) on both the input and the output. If neither is wanted, raise at config time for shared_outer + HybridEP non-blocking.
There was a problem hiding this comment.
Fixed in 219984fa1. The shared weight is cast to bf16 once, expanded across experts with stride 0, and passed to torch._grouped_mm(..., offs=offsets_E), so no E × L × D contiguous weight copy is needed.
test_shared_adapter_gradients_ignore_uninitialized_tail_rows now covers both W13 lora_a and W2 lora_b: it poisons rows after offsets_E[-1] with NaN and checks valid-row outputs and shared-weight gradients against a valid-rows-only grouped-matmul reference. Both cases fail before the fix and pass on CPU and CUDA after it.
Both layouts also complete the 10-step Qwen3.5 integration on 8xH200. I could not run real HybridEP dispatch because the available images do not expose deep_ep.HybridEPBuffer; the padded-tail kernel contract was tested directly on CUDA instead.
|
need to rebase onto #5884 |
0bf865a to
219984f
Compare
|
@tianyu-l Rebased onto #5884 at For your correctness checklist:
Final affected-suite result: |
|
@tianyu-l I do not have permission to add labels in this repo. When approving the pending workflows, could you also add |
Grouped LoRA gives every expert its own A and B. Serving engines and
other trainers lay expert adapters out the other way: the factor on the
model-dimension side of each routed projection is shared across the
experts (A of W13 reads the hidden stream, B of W2 writes it) and only
the other factor is per expert, so a token's low-rank path goes through
one shared matrix and the adapter volume does not scale with the model
dimension per expert. A model trained here with the per-expert layout
cannot be served as expert adapters there.
LoRATransform gains expert_adapter_layout ("per_expert", the default,
or "shared_outer"). Under shared_outer the grouped LoRA config carries
shared_factor, the shared factor is a plain Linear without the expert
axis, the grouped matmul applies it as one dense matmul over the routed
rows, and Dist-MoE materializes effective weights by broadcasting it
over the experts. The shared factor takes the sparse family's
replicated placement where the base weight is split by expert, which is
what keeps a parameter shared across experts in step under EP. A grouped
projection that is not w13 or w2 is refused under shared_outer.
Co-Authored-By: Claude Mythos 5.1 <[email protected]>
Co-Authored-By: Claude Mythos 5.1 <[email protected]>
…erving gap Co-Authored-By: Claude Mythos 5.1 <[email protected]>
…e and integration entries shared_factor is Literal["lora_a", "lora_b"] | None with no default, the adapter factors are typed Linear | GroupedLinear (also what pyrefly needed), and the shared side is chosen only under a RoutedExperts or DistMoeRoutedExperts parent. qwen35_debugmodel_moe_lora_shared_outer is the in-repo consumer, with an h100 integration entry next to the per-expert one. Co-Authored-By: Claude Mythos 5.1 <[email protected]>
The roles of w13 and w2 are stated once above _SHARED_OUTER_FACTOR; the parent check and its error message say the rest. Co-Authored-By: Claude Fable 5.2 <[email protected]>
219984f to
01638cc
Compare
|
@claude review |
There was a problem hiding this comment.
Verdict: Approve -- at 01638cc the open item from the last automated review is fixed: padded tail rows can no longer leak into the shared factor's gradient. Every maintainer comment is addressed, and I found no new correctness problems.
What this PR does. It adds LoRATransform.expert_adapter_layout, with the values "per_expert" (the default, behavior unchanged) or "shared_outer". With shared_outer, routed-expert w13 gets one lora_a shared by all experts, and w2 gets one shared lora_b. Each shared factor is a plain Linear with no expert axis, placed with replicated_param_placement_sparse() when the base weight is expert-sharded. On the GroupedLinear path, the shared factor is broadcast into torch._grouped_mm through a stride-0 expand. On the Dist-MoE path, it is broadcast into the existing baddbmm.
Example.
W13 [E, 2, F, D], W2 [E, D, F], rank L, R routed rows, offsets_E[-1] <= R
shared_outer: w13.lora_a [L, D] -> _grouped_mm(x_RD, A.bf16().expand(E, L, D).mT, offs)
w2.lora_b [D, L] -> _grouped_mm(h_RL, B.bf16().expand(E, D, L).mT, offs)
Before (last review): F.linear over all R rows, so dA/dB included the tail rows
After: grouped mm skips the tail rows; expand's backward sums the E partial grads
Earlier items
- Tail rows leaking into the shared-factor wgrad (
lora.py:270in the last review): resolved attorchtitan/models/common/lora.py:744-748, and guarded bytest_shared_adapter_gradients_ignore_uninitialized_tail_rows. The test calls_adapter_matmuldirectly. That is needed: through the public W2 forward, the NaN-poisoned tail would not reachlora_b's input. - @tianyu-l's Dist-MoE request (
transform/lora.py:303): resolved._shared_factoraccepts aDistMoeRoutedExperts.Configparent, and_adapter_operandsbroadcasts the shared factor forbaddbmm(test_dist_moe.py:458). - Description: resolved. It describes the parent-gated rule, the recipe, the h100 entry, and the grouped-mm fix.
Should consider
tests/unit_tests/cpu/models/common/test_lora.py:342-- this test mostly duplicates the equivalence test at :390. Fold its few unique asserts into that test and delete about 90 lines (inline).
Details
- Shared path vs. per-expert path.
_adapter_matmulreproducesGroupedLinear._grouped_mm(linear/linear.py:474-478): the same bf16 cast, transpose, andoffs. The only difference is that it casts beforeexpand. That order is required:.bfloat16()on a stride-0 view would materialize a contiguousE x L x Dcopy. Its backward computes a transient bf16[E, L, D]grad and then sums it over E. That is the same size as the per-expert layout's persistent grad, so there is no memory regression versusper_expert. - Precision. The shared gradient is the sum of E per-expert bf16 partials, while a single dense wgrad would round once. That is why the equivalence test uses
atol=rtol=1e-2. This is expected, and it is not a regression of an existing path. - Sharding (no change since the last review). The integration recipe (
qwen35_debugmodel_moe: FSDP2, PP2, EP4, TP2) puts the experts onexpert_param_placement_sparse(), so the shared factors getreplicated_param_placement_sparse(). TP-sharded expert bases still raise in_grouped_lora_adapter_shardingbefore the shared placement is chosen. - Other consumers. No code outside
models/common/lora.pyandconfig/transform/lora.pyreadslora_a/lora_b. The sharedLinearis built in__init__, not in the config tree, so the quantization converters never see it. - No D2H syncs.
offsets_E.shape[0]is static.
Not verified: torch._grouped_mm with a stride-0 batch operand on sm100 and ROCm (the author tested H200 and CPU); the 4-GPU EP test and both 8-GPU integration entries at this HEAD. This PR touches models/common/, so a maintainer still needs to review it.
| return torch.cat(parts) | ||
|
|
||
|
|
||
| def test_shared_outer_adapters_share_the_model_side_factor(): |
There was a problem hiding this comment.
This test and its _shared_outer_reference helper (about 90 lines) mostly duplicate test_shared_outer_matches_per_expert_with_grouped_bias below. Both build fused W13 (num_linears=2) and W2, and both compare forward output to an independent per-expert computation with the shared factor broadcast. The equivalence test also covers the backward pass, and its expand(2, ...) copies would fail if a shared factor had the wrong shape. The only checks unique to this test are the shared-factor shapes, the state-dict keys, and weight.grad is None. Base freezing is already covered by the existing grouped LoRA tests.
Suggestion: move the shape and state-dict asserts into the equivalence test, then delete this test and _shared_outer_reference (tests.md: don't duplicate coverage).
There was a problem hiding this comment.
Is this legit? If so, could you address.
| return lora_a.build(), lora_b.build() | ||
|
|
||
|
|
||
| def _adapter_matmul( |
There was a problem hiding this comment.
IIUC, to deal with offsets, now we are always using grouped_mm even when lora_a / lora_b is Linear (not GroupedLinear) under shared layout.
If so, do you think we could rename
| def _adapter_matmul( | |
| def _adapter_grouped_mm( |
for better readability.
| return torch.cat(parts) | ||
|
|
||
|
|
||
| def test_shared_outer_adapters_share_the_model_side_factor(): |
There was a problem hiding this comment.
Is this legit? If so, could you address.
Resolve conflicts with pytorch#5893 (expert LoRA merge without a full-weight copy) and pytorch#6043 (vision encoders non sp): feed _adapter_operands into _MergeExpertLoRA, and drop the removed InvariantRowParallelLinear import. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Summary (human-written)
Add another LORA supporting method for MOE layer: shared-outer adapter layout for routed experts.
Comparing with per-expert lora, this shared lora way.:
Why
Grouped LoRA gives every expert its own
AandB(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 (Aof W13, which reads the hidden stream;Bof 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]giveslora_a [E, 8, D],lora_b [E, 2, F, 8]; no other shape is reachable.After:
LoRATransform(rank=8, expert_adapter_layout="shared_outer")giveslora_a [8, D](shared),lora_b [E, 2, F, 8]; for W2,lora_a [E, 8, F],lora_b [D, 8](shared). The default staysper_expert.What changed
LoRATransform.expert_adapter_layout: Literal["per_expert", "shared_outer"] = "per_expert". Undershared_outer, thew13of aRoutedExperts.ConfigorDistMoeRoutedExperts.Configgetsshared_factor="lora_a"and itsw2gets"lora_b"; a grouped projection under any other parent, or with any other name, is refused withValueError. The grouped LoRA config'sshared_factorisLiteral["lora_a", "lora_b"] | Nonewith no default, and both adapter factors are typedLinear | GroupedLinear.torchtitan_recipes/tests/models/qwen3_5.py:qwen35_debugmodel_moe_lora_shared_outer, the per-expert debug recipe with the option, registered intests/integration_tests/h100.pynext toqwen3_5_moe_lora.torchtitan/models/common/lora.py: the grouped LoRA config carriesshared_factor; the shared factor is built as a plainLinearwithout 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 bytest_fsdp_moe_sharding), and the base placement otherwise._adapter_matmuluses_grouped_mmfor both layouts; a shared factor is cast to bf16 once and broadcast through a stride-0 expanded expert axis, so rows pastoffsets_E[-1]cannot contaminate its gradient and noE × L × Dcontiguous weight copy is needed. Dist-MoE materializesW + scale * B @ Awith the same singlebaddbmmas before;_adapter_operandshands it a shared factor as a stride-0 expanded view, so no extra full-size temporary._create_lora_classis split into the twoget_lora_*builders so only the grouped config carries the new field.Numerics / performance
Per-expert layout is unchanged: same adapters, same grouped matmuls, same
baddbmmmaterialization. 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 W13lora_aand W2lora_b, NaN-poisoned rows afteroffsets_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.Awithin one bf16 ulp, since that trainer keeps a separateAper gate/up branch and torchtitan shares one).qwen3_5_moe_lora_shared_outerintegration entry (8 GPUs, real process group): the end-to-end guard for the new layout, next to the per-expert one.01638cc12, rebased onto main atbb34c7591now that [lora] Derive adapter sharding from the base weight #5884 is merged. On a CPU-only setup with torch nightly2.16.0.dev20261110: all oftests/unit_tests/cpupasses (2032 passed, 19 skipped, 3 xfailed); with the optionaldist_moepackage,test_lora.py,test_dist_moe.pyandtest_transforms.pygive 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 onmainthere. Pre-commit hooks pass on the changed files, and Pyrefly reports nothing in them.219984fa1(8xH200, andqwen3_5_moe_lora_shared_outerin 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 exposedeep_ep.HybridEPBuffer; the padded-tail contract was tested directly on CUDA instead.test_deepep_activation_checkpoint.py(2 tests), which fails the same way onmain's nightly H100 runs since 2026-11-07.🤖 Generated with Claude Code