Skip to content

FSDP2 QLoRA: give the all-gathered 4-bit weight back its Params4bit class and 3D shape - #14204

Merged
danielhanchen merged 2 commits into
mainfrom
dh/fu-fsdp2-moe-4bit
Oct 19, 2026
Merged

danielhanchen merged 2 commits into
mainfrom
dh/fu-fsdp2-moe-4bit

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 19, 2026 •

Copy link
Copy Markdown
Member

Summary

4-bit MoE models crashed under FSDP2. FSDP2 rebuilds the all-gathered weight as a plain nn.Parameter, and fsdp2_qlora only carried the bitsandbytes quant attributes over. The unsloth-zoo 4-bit MoE paths choose their kernel with isinstance(w, Params4bit) and read a 3D expert stack's logical shape from _original_shape, so under FSDP2 they treated the packed bytes as a dense weight (RuntimeError: size mismatch / contraction dimension errors).

fsdp2_qlora now:

  • records the original parameter class and Params4bit.module when FSDP2 shards the weight;
  • gives the all-gathered parameter that class back. It is the same object and storage; only __class__ changes, and only from exactly nn.Parameter to a Parameter subclass, so DTensor (HSDP / TP) parameters are left alone;
  • carries _original_shape with the other quant attributes;
  • marks the gathered weight _unsloth_fsdp2_gathered, so the zoo MoE caches re-key their NF4 pointer tables per call (the storage moves around every forward and backward).

Companion zoo PR unslothai/unsloth-zoo#1872 (stale __dict__ swap and gpt-oss backward pointer table). Without FSDP2 nothing here runs.

Tests

tests/test_fsdp2_qlora_moe_gloo.py (new, 2 gloo ranks, real bitsandbytes 4-bit 3D stacks and ModuleList Linear4bit experts): gathered class, _original_shape, module, the marker, torch.chunk, bit-exact forward and input gradients, and the reshard back to DTensor. 3 failed on main, 3 passed here. The existing FSDP2 CPU suite (42 tests) passes.

2-rank NCCL, with the zoo companion:

Case main this PR
ModuleList 4-bit experts, grouped MoE RuntimeError fwd 0.0, dX 0.0 vs unsharded
transformers v5 3D 4-bit experts, every MoE backend RuntimeError: size mismatch fwd 0.0, dX 0.0
gpt-oss 4-bit experts grouped path never used grouped path used, exact

End to end (tiny Qwen3-MoE, load_in_4bit = True, LoRA, UNSLOTH_FSDP2=1, 2 ranks vs 1 GPU with GA x2):

step 1 GPU loss / grad_norm FSDP2 loss / grad_norm
1 11.930937 / 0.02644 11.930938 / 0.02688
2 11.928570 / 0.01856 11.928556 / 0.01904
3 11.927559 / 0.01245 11.927561 / 0.01258
4 11.927320 / 0.01094 11.927359 / 0.01177

The grad-norm gap is the same as 16-bit LoRA on that model under FSDP2 (about 1.5%). Main crashes on step 1.

Not covered here

  • The 2-rank component check also passes on Kaggle T4 x2 in fp16 with torch 2.10 and 2.14 (fwd 0.0, dX 0.0 in every case). The end-to-end training table is torch 2.13 only.
  • No real Hub checkpoint; tiny models only.

…lass and 3D shape

FSDP2 rebuilds the gathered weight as a plain nn.Parameter and the FSDPParam wrapper only carried
the bitsandbytes quant attributes, so the unsloth-zoo 4-bit MoE paths, which pick their kernel with
isinstance(w, Params4bit) and read a 3D expert stack's logical shape from _original_shape, fed the
packed bytes to a dense matmul (ModuleList experts: contraction dimension of mat_a and mat_b must
match; transformers v5 3D experts: size mismatch). gpt-oss bnb-4bit experts silently fell back to
the per-expert loop.

The wrapper now restores the class the weight was sharded from on the gathered parameter (same
object and storage), carries _original_shape and Params4bit.module, and marks the gathered weight
_unsloth_fsdp2_gathered so unsloth-zoo re-keys its address-keyed NF4 pointer tables per call.
@danielhanchen danielhanchen self-assigned this Oct 19, 2026
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 19, 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 ✅ Completed 2026-10-19T06:31:09.825795Z 0eba8a3 Manual request
🔒 Security Review ⚠️ Failed 2026-10-19T06:25:58.310546Z 0eba8a3 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

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Another round soon, please!

Reviewed commit: 0eba8a3573

ℹ️ 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 39efb78 into main Oct 19, 2026
@danielhanchen
danielhanchen deleted the dh/fu-fsdp2-moe-4bit branch October 19, 2026 13:08
danielhanchen added a commit that referenced this pull request Oct 19, 2026
## Summary

Main is over the startup bundle budget again, so `Frontend build +
bundle sanity` fails on every PR based on it:

```
over the startup budget: transfer 2012.0 KB > 2011.9 KB, raw 6681.8 KB > 6680.6 KB      (main at 26e246d)
```

#14247 (Developer mode opt-in for experimental CPU video generation)
added 1,777 B raw / 654 B transfer to the startup chunks. It merged
without raising the limits.

## Cause

`#14247` touches eager startup code. Its new strings land in
`i18n/locales/en.ts` (the English catalog ships in the startup chunks),
and the developer-mode flag is read from `__root.tsx`,
`app-sidebar.tsx`, `config/env.ts` and `config/hardware-verdict.ts`. The
settings section itself is lazy. This is small real growth with no lazy
home. The other commits since the last measurement (#14204, #14239,
#14249) change no frontend code.

## Change

- **`check-bundle-budget.ts`:** a BUDGET comment entry for #14247, and
both limits moved to the measured build plus a 160 B raw / 189 B
transfer margin:
  - `rawBytes`: 6,840,888 -> 6,842,343.
  - `transferBytes`: 2,060,219 -> 2,060,510.

## Testing

One machine and build, Node 24, exact byte totals from the budget
script. CI has matched this machine to the byte on earlier budget
changes.

| tree | raw B | transfer B |
|---|---|---|
| `88afa84b87` (before #14247) | 6,840,406 | 2,059,667 |
| main `26e246d407` | 6,842,183 | 2,060,321 |

- **Main against the old limits:** `over the startup budget: transfer
2012.0 KB > 2011.9 KB, raw 6681.8 KB > 6680.6 KB`.
- **With this change:** `within budget (0.2 KB transfer, 0.2 KB raw to
spare)`, 96 chunks.
danielhanchen added a commit to danielhanchen/unsloth-zoo-staging that referenced this pull request Oct 19, 2026
…ointer tables for all-gathered experts (unslothai#1872)

## Summary

Two zoo bugs that only show up when FSDP2 shards 4-bit MoE experts.
FSDP2 frees and re-allocates the all-gathered weight storage around
every forward and backward. Companion unsloth PR (marks those weights):
unslothai/unsloth#14204.

1. **`swap_moe_weights_for_call` left the original Parameter in the
instance `__dict__`.** It swaps dequantized expert weights in with
`object.__setattr__` and restored them the same way. That left a
`__dict__` entry shadowing `_parameters`, so every later
`_parameters[name] = ...` swap was hidden, including FSDP2 installing
its sharded / gathered parameter around each forward. The next call then
read a stale, freed all-gather buffer. This path is used by the 4-bit
MoE backends that dequantize first: pinned / `UNSLOTH_MOE_RECOMPUTE=0`,
`native_torch`, `unsloth_triton`, and every backend on GPUs without
`torch._grouped_mm` (T4). It now restores by removing the entries it
added.
2. **gpt-oss grouped QLoRA backward used a stale NF4 pointer table.**
The backward recompute reused the table captured in forward, which
points at the forward all-gather FSDP2 already freed. The result was
silently wrong input gradients. For weights marked as FSDP2-gathered
(`_unsloth_fsdp2_gathered`, set by unsloth's `fsdp2_qlora`), the table
is now re-read at recompute time, and `moe_ready_epoch.scan` gives those
subtrees no cached record, the same as accelerate-hooked subtrees. The
fp16 grouped path (`_Fp16StackProvider`) had the same stale table, and
the refresh now turns on when any gate-up or down expert weight is
FSDP2-gathered, not only the first gate-up one.

Without FSDP2 none of the new branches run: single GPU numerics are
byte-identical, and no host sync or graph break is added. The swap fix
only removes a `__dict__` shadow, so attribute lookup returns to
`nn.Module.__getattr__` as before the first call.

## Tests

| Test | main | this PR |
|---|---|---|
| `tests/test_moe_swap_weights_restores_parameters.py` | 1 failed | 2
passed |
| `tests/test_moe_fsdp2_gathered_tables.py` | 2 failed | 2 passed |
|
`tests/test_gpt_oss_grouped_qlora.py::test_fsdp2_gathered_backward_reads_current_weights`
(GPU; bf16, fp16, fp16 windows; all or only down experts marked) | new
test; 5 of 6 fail at the head before the fp16 and any-projection fixes |
6 passed |

2-rank NCCL check (real zoo code, forward and input gradients against
the same module before sharding), together with the unsloth companion:

| Case | main | this PR + companion |
|---|---|---|
| ModuleList 4-bit experts, grouped MoE | `RuntimeError` (contraction
dims) | fwd 0.0, dX 0.0 |
| transformers v5 3D 4-bit experts, every MoE backend | `RuntimeError`
(size mismatch) | fwd 0.0, dX 0.0 |
| gpt-oss 4-bit experts | grouped path never used (loop fallback) |
grouped path used, fwd 0.0, dX 0.0 |

End to end, a tiny Qwen3-MoE loaded in 4-bit with LoRA trains under
FSDP2 (2 ranks) with loss matching the 1-GPU run to about 1e-5. The
grad-norm gap (about 1.5%) is the same as for 16-bit LoRA on that model.
On main it crashes.

The zoo MoE suite (39 files touching these modules, GPU) has the same
single failure on main and here (an xformers "No operator found" in a
Llama attention test, environment related).

Kaggle T4 x2, fp16, torch 2.10 and 2.14: the same 2-rank check gives fwd
0.0 and dX 0.0 in all five cases, with the gpt-oss grouped path used 3 /
3. Before the fp16 fix the gpt-oss dX on T4 was 0.089 to 0.198.

## Not covered here

- The tiny gpt-oss checkpoint loads its experts uninitialized, so
gpt-oss is covered by the component test only.
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