Skip to content

MoE LoRA: keep native per-expert Linears for an explicit target_modules list on transformers 4.x - #13851

Merged
danielhanchen merged 11 commits into
mainfrom
fix/moe-explicit-targets-native-experts
Oct 15, 2026
Merged

danielhanchen merged 11 commits into
mainfrom
fix/moe-explicit-targets-native-experts

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Problem

On transformers 4.x, MoE models with per-expert nn.Linear experts (Qwen3-MoE, and other models whose mlp.experts.<i> are ModuleLists of Linears) silently get no LoRA on their experts when FastLanguageModel.get_peft_model is given an explicit target_modules list such as ["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj"]. Only attention trains, and no warning is printed.

Repro on transformers 4.57.6 with trl-internal-testing/tiny-Qwen3MoeForCausalLM and that target list:

LoRA tensors under .experts. trainable parameters
main 0 25,088 (attention only)
this PR 12 (stacked per-expert gate / up / down) 174,080

Cause

  • For Qwen3-MoE, FastLanguageModel.get_peft_model hands over to FastBaseModel.get_peft_model with finetune_vision_layers = False (unsloth/models/llama.py).
  • Because a finetune_* flag is False, the explicit list is rewritten into a regex by Zoo's get_peft_regex (unsloth/models/vision.py, the scoping branch added in f372da4, MLX Training updates #5656). That regex deliberately skips native experts.<i> blocks.
  • widen_target_regex_to_expert_submodules only re-adds expert submodules for remote-code models, so the explicit request for gate_proj / up_proj / down_proj no longer reaches the experts that plain PEFT suffix matching would have matched.
  • The "no experts trained" warning checks the original leaf names and concludes PEFT will reach the experts, so it stays silent.

Bisected: the parent of f372da4 gives 48 expert LoRA parameters and 174,080 trainable; f372da4 gives 0 and 25,088 (both with the Zoo of the same date).

Change

  • unsloth/models/_utils.py: _native_expert_parents finds native experts.<i> blocks inside decoder layers that the scoped regex already reaches (so a vision tower's experts stay out), and widen_target_regex_to_expert_submodules(..., explicit_leaves = True) widens to those as well.
  • unsloth/models/vision.py: marks the regex as coming from the caller's explicit list and passes explicit_leaves when MLP modules are being finetuned.

Unchanged: the default (target_modules = None) still keeps native experts off LoRA as before; fused transformers 5.x experts (target_parameters) are untouched; an attention-only list widens nothing; a down_proj-only list widens to down_proj only.

Tests

  • Two new tests in tests/test_remote_code_class_and_expert_submodules.py: an explicit list selects exactly the modules PEFT's own leaf matching would (router stays frozen), down-only and attention-only lists, the default path unchanged, and a vision expert tower kept out.
  • The 7 related MoE / PEFT test files: transformers 4.57.6 160 passed (158 on main + the 2 new), transformers 5.17 172 passed (170 + 2).
  • jobs/moe_sft.py (tiny Qwen3-MoE, transformers 4.57.6, B200): main fails its lora_on_experts check; this PR passes every check, including LoRA on experts, the adapter changing, non-zero lora_B gradients on all 6 expert tensors, and 52 torch._grouped_mm calls.
  • transformers 5.17: identical to main (the regex is not widened there).

Not covered: Mixtral and other transformers 4.x MoE families on a real checkpoint (the unit test uses a synthetic model with the same layout), and merged 16-bit saving of the stacked per-expert LoRA tensors.

… list

FastLanguageModel.get_peft_model passes finetune_vision_layers=False, which routes an
explicit leaf list through get_peft_regex. Its text-only branch skips mlp.experts.<i>,
so on transformers 4.x Qwen3-MoE / Mixtral (per-expert nn.Linear ModuleLists) the
requested gate_proj/up_proj/down_proj silently stopped reaching the experts and only
attention was trained. Widen that regex to the native expert submodules of decoder
layers it already reaches, scoped to the requested leaves. The auto regex
(target_modules=None) and transformers 5.x fused experts are unchanged.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 15, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ⚠️ Failed 2026-10-15T17:18:04.739303Z fa4a5c1 New commits
🔒 Security Review ⚠️ Failed 2026-10-15T12:57:45.882591Z 7d5ce70 PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 43832d03ba

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread unsloth/models/_utils.py Outdated
Comment on lines +9217 to +9218
if not layer or not any(r == layer or r.startswith(layer + ".") for r in reached_layers):
continue

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Widen expert-only target lists without an attention anchor

When the explicit list contains only expert MLP leaves, such as ["down_proj"] or ["gate_proj", "up_proj", "down_proj"], the scoped regex matches no non-expert module in a fully sparse Qwen3-MoE layer, so reached_layers remains empty and every expert parent is rejected here. The new widening therefore still omits all requested experts (and may leave PEFT with no targets), while the test labeled down-only includes q_proj and masks the problem; derive the decoder-layer scope independently of an unrelated matched attention leaf.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Checked this on the real Qwen3-MoE module tree (trl-internal-testing/tiny-Qwen3MoeForCausalLM, transformers 4.57.6). For an expert-only list get_peft_regex finds no non-expert leaf, so it returns its unscoped form .*?(?:...|mlp|...).*?\.(?:down_proj), which already fullmatches model.layers.<n>.mlp.experts.<i>.down_proj. The widening then exits early and the adapters land on exactly the modules plain PEFT picks: 8 of 8 for ["down_proj"] and 24 of 24 for gate/up/down. Added d4f0af4 to lock both expert-only lists against the plain-PEFT leaf match.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 15, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 15, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 15, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 15, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 15, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

danielhanchen added a commit that referenced this pull request Oct 15, 2026
`pinned-symbol matrix (vLLM, TRL, PEFT, ST, bitsandbytes, transformers)`
fails on any PR that runs it (seen on #13851, on main e1cdbf4):

```
FAILED tests/version_compat/test_peft_conversion_symbol_backfill.py::test_the_fused_snapshot_matches_upstream
AssertionError: fused MoE types missing from the snapshot: ['UnlimitedOcrTextModel']
```

That test is the canary against transformers main's
`conversion_mapping._MODEL_TO_CONVERSION_PATTERN`, which now carries
`"UnlimitedOcrTextModel": "qwen2_moe"` (the unlimited_ocr text model, a
fused qwen2_moe-family MoE). The canary is right; this is the same kind
of upkeep as #12018 (longcat_flash_lsa).

Two changes in `unsloth/import_fixes.py`:

1. The entry goes into `_PEFT_MOE_CONVERSION_PATTERNS`.
2. Unlike every existing entry it is keyed by class name, not by a
lowercase model type, and `_UnavailableConversionPatternMap._is_moe`
lowercased the key before the snapshot lookup. So the snapshot entry
alone would not have helped: with the map gone,
`get("UnlimitedOcrTextModel")` would still lowercase to
`unlimitedocrtextmodel`, miss the snapshot, find no `moe`/`mixtral` hint
in the name, and return a silent `None`, which is the mis-conversion the
stand-in exists to refuse. `_is_moe` now checks the key as given as well
as lowercased.

New test `test_a_fused_class_name_alias_is_refused_in_its_own_case` pins
both halves.

Verification
(`tests/version_compat/test_peft_conversion_symbol_backfill.py`,
transformers 5.18.0 installed, upstream map fetched live):
- main: the upstream canary fails as above.
- With this change: 68 passed.
- Sabotage, entry removed: the canary and the new test fail.
- Sabotage, entry kept but `_is_moe` back to the lowercase-only lookup:
the new test fails (the stand-in returns `None` for the class name).
- Formatted with `scripts/run_ruff_format.py`.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 15, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 15, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Bravo.

Reviewed commit: e0a2078ac2

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@danielhanchen
danielhanchen merged commit ddbbd9b into main Oct 15, 2026
@danielhanchen
danielhanchen deleted the fix/moe-explicit-targets-native-experts branch October 15, 2026 17:51
danielhanchen added a commit that referenced this pull request Oct 15, 2026
…3909)

With #13846 merged, main (d303bac) is still red in Backend CI and
Repo tests, from three regressions that landed in the last few hours.
Each is reproduced locally on main and fixed here.

## 1. `test_text_io_names_its_encoding[drafter.py]` (from #13806)

```
drafter.py:222: subprocess(text = True) without encoding
```

`core/training/drafter.py` runs the drafter capability probe in a child
interpreter with `text = True` and no encoding, so the parent decodes
the child's output with the locale codec (cp1252 on Windows, ASCII under
a C locale). The guard is right and the code is what changes: the call
now passes `encoding = "utf-8", errors = "replace"`, and the child gets
`PYTHONIOENCODING=utf-8` so it writes what the parent reads. That
matches how `core/training/worker.py` runs its own probes. The payload
line is `json.dumps` output, so nothing parsed changes.

## 2. `test_backfill_splits_a_quant_suffix_the_way_the_backend_does`
(from #13899)

```
AssertionError: MXFP
```

#13899 widened the GGUF known-quant pattern from `MXFP...` to
`(?:MX|NV)FP...` so NVFP4 files get their own variant key. That change
is right, and it was made consistently in all three places that must
agree: `core/inference/llama_cpp.py` (`_GGUF_KNOWN_QUANT_RE`),
`hub/utils/gguf.py` (`_GGUF_QUANT_RE`) and the frontend's
`model-identity.ts` (`QUANT_TOKEN_SOURCE`). The test was checking that
the literal substring `MXFP` appears in `llama_cpp.py`, which it no
longer does.

The test now checks the property it was standing in for: it reads the
pattern string out of both Python modules with `ast` (adjacent literals
joined as Python joins them) and the TypeScript constant, asserts all
three are identical, and asserts the shared pattern still fully matches
`MXFP4`, `NVFP4`, `IQ4_XS`, `TQ1_0`, `Q4_K_M`, `Q8_0`, `BF16`, `F16` and
`F32`. That is stricter than before, since a pattern edited on one side
only now fails, and it no longer breaks on a correct rewording.

## 3. `test_every_tracked_python_file_is_already_formatted`

Formatter drift (pinned ruff 0.6.9 via `scripts/run_ruff_format.py`),
output only, no logic change:

| file | from |
| --- | --- |
| `studio/backend/core/inference/llama_cpp.py`, `offload_layout.py`,
`tests/test_nemotron35_bolt_super.py`,
`tests/test_nemotron35_planner.py` | #13899 |
| `studio/backend/tests/test_muse_spark.py` | #13903 |
| `tests/test_norm_fast_launch.py`, `unsloth/kernels/layernorm.py` |
#13889 |
| `tests/test_remote_code_class_and_expert_submodules.py`,
`unsloth/models/_utils.py` | #13851 |
| `tests/test_triton_fp_fusion.py` | #13846 |

## Verification

- `tests/test_formatter_fixed_point.py` (ruff 0.6.9): fails on main, 16
passed here.
- `tests/studio/test_model_picker_contracts.py` and
`tests/test_runtime_text_encoding.py`: 210 passed.
- `studio/backend/tests/test_text_io_encoding.py`,
`test_nemotron35_bolt_super.py`, `test_drafter_training.py`: all pass
except `test_capability_child_process_runs_for_real`, which fails
identically on main without this change on this host (it runs the probe
in a real child interpreter) and is not failing in CI.
- Sabotage on the rewritten picker guard: dropping `NV` from the pattern
in `hub/utils/gguf.py` only, or in `model-identity.ts` only, fails it;
restored, it passes.
- Sabotage for (1) is main itself: without the encoding, the guard fails
as quoted above.
danielhanchen added a commit to Etherll/unsloth that referenced this pull request Oct 18, 2026
…test fixes across torch 2.10 - 2.14 (unslothai#14122)

Follow-up fixes from a re-verification of the recent kernel PRs (unslothai#13828, unslothai#13829, unslothai#13830, unslothai#13831, unslothai#13840, unslothai#13851, unslothai#13889, unslothai#13893, unslothai#13967, unslothai#14026, unslothai#14027) across T4, L4, A100, H100, RTX PRO 6000, B200 and gfx1151, on torch 2.10 to 2.14. Main itself showed no regression for default training or inference. These are the real gaps the re-verification turned up.

## Changes

**NVFP4 fused GEMM row gate scales with the weight shape** (`unsloth/kernels/nvfp4.py`)
- The old gate was one row limit per GPU (A100 64, L4 256, RTX PRO 6000 128). It picked the fused kernel in cells where fused is slower than dense: up to 2.4x on A100, 2.5x on L4 and 5.9x on RTX PRO 6000. For example, at 64 rows with N = K = 4096 it was +12% on RTX PRO 6000 and +4.5% on A100.
- The limit is now `clamp(max(N * K // div, k_rows), floor, max_rows)`, with separate forward and dX entries per capability. Weights with N or K not a multiple of 128 run the masked edge tiles, so they only get the floor.
- The constants were fitted to a bf16 sweep: rows 1 to 256, ten (N, K) shapes, timed with CUDA graphs, interleaved arms and an A/A spread.
- `UNSLOTH_NVFP4_FUSED=0` / `1` and `UNSLOTH_NVFP4_FUSED_MAX_ROWS` keep their meaning. Unmeasured GPUs (H100, T4, others) stay dense as before.

Confirmation pass, 90 cells per GPU:

| GPU | old gate: fused picked but slower than dense | new gate | new slower than old by more than max(noise, 10%) |
|---|---|---|---|
| A100 | 11 | 0 | 1 (dX, 32 rows, 2048x2048, +16%) |
| L4 | 23 | 0 | 2 (fwd, 256 rows, 5120x5120, +43%; fwd, 128 rows, 3072x768, +10%) |
| RTX PRO 6000 | 21 | 0 | 0 |

Fixing those three cells would push a neighbouring shape that loses onto fused, so they are left as they are.

**MoE fallback grouped GEMM configs fit the GEMM** (`unsloth/kernels/moe/autotune_cache.py`)
- These are the configs used with `UNSLOTH_MOE_DISABLE_AUTOTUNE=1`, or when autotuning fails (for example OOM on a 16 GB card). They used fixed tiles, and the kernels assert `N % BLOCK_SIZE_N == 0` and `K % BLOCK_SIZE_K == 0`. So intermediate sizes such as 1408 (DeepSeek-V2-Lite, Qwen1.5-MoE), 352 and 2880 crashed.
- The tiles now shrink to the largest power of two (at least 16) that divides each GEMM's N and K. Configs that already worked (Qwen3-30B-A3B, Qwen3-235B, Mixtral, OLMoE) are byte-identical.
- The heuristic 64x64x256, 4-stage dX config needs 122,880 B of shared memory, more than L4 and RTX PRO 6000 have (101,376 B). It raised OutOfResources there for every shape. On sm_80+ with that limit it now drops to 3 stages (81,920 B), reading the limit of the current device. T4, A100, H100 and B200 configs are unchanged.

**Tests**
- `test_norm_fast_launch`: run the narrow-row self-check before measuring the compiled call. On torch 2.10 to 2.12, Dynamo reaches that one-time check with `is_compiling()` False, and the test counted its eager launches. The compiled graph never used the fast launcher.
- `test_cross_entropy_eviction_hints`: skip an arch the active ptxas cannot target. Once Inductor sets `TRITON_PTXAS_PATH`, the CUDA 13 ptxas has no sm_52 to sm_72.
- `test_layernorm_compiled_matches_eager_bytes`: also run in fp16, and skip bf16 on GPUs without native bf16. Inductor skips bf16 graphs there, so `fullgraph=True` fails in plain torch too.

## Validation

- **CPU tests:** new tests `test_nvfp4_fused_gate_shape.py` (27) and `test_moe_fallback_tile_dims.py` (60) pass on torch 2.10 and 2.14.
- **GPU, base (main) vs this branch:**
  - Colab L4 (torch 2.11, 2.14), RTX PRO 6000 (2.14), T4 (2.10, 2.14): no test fails on the branch that passes on main.
  - Norm self-check test: fails on main on torch 2.10 and 2.11, passes here.
- **MoE fallback, one MoE block driven exactly as unsloth-zoo calls it:**
  - T4: main crashes on 1408 / 352 / 2880. This branch trains them, with forward and all gradients within about 6e-4 of an fp32 reference.
  - L4 and RTX PRO 6000: the heuristic path crashes on main for every shape and trains here.
  - Unchanged shapes are bit-identical to main. 768 timing is unchanged on T4, L4 and RTX PRO 6000.
- **NVFP4 GPU tests:** 105 passed on A100, L4 and RTX PRO 6000. The fused vs dense outputs match.

Not covered: NVFP4 timing on H100 (no allocation) and in fp16; the MoE heuristic smem change on T4 is covered by CPU tests and earlier T4 runs of the same configs.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant