Repository navigation
FSDP2 QLoRA: give the all-gathered 4-bit weight back its Params4bit class and 3D shape - #14204
Merged
Merged
Conversation
…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.
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
Member
Author
|
@codex review |
|
Codex Review: Didn't find any major issues. Another round soon, please! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
4-bit MoE models crashed under FSDP2. FSDP2 rebuilds the all-gathered weight as a plain
nn.Parameter, andfsdp2_qloraonly carried the bitsandbytes quant attributes over. The unsloth-zoo 4-bit MoE paths choose their kernel withisinstance(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_qloranow:Params4bit.modulewhen FSDP2 shards the weight;__class__changes, and only from exactlynn.Parameterto a Parameter subclass, so DTensor (HSDP / TP) parameters are left alone;_original_shapewith the other quant attributes;_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 ModuleListLinear4bitexperts): 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:
RuntimeErrorRuntimeError: size mismatchEnd to end (tiny Qwen3-MoE,
load_in_4bit = True, LoRA,UNSLOTH_FSDP2=1, 2 ranks vs 1 GPU with GA x2):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