Repository navigation
gpt-oss on multiple GPUs: FSDP2 keeps frozen untied IO tables out of the root unit, PP trains MoE models with the router aux loss off - #18165
Conversation
… at any size The root unit is wrapped with reshard_after_forward=False, so a frozen input / output embedding left in it is all-gathered at the first forward and held whole until the end of backward: each rank pays the full table plus its own shard for the whole step, and the gather allocates the output plus a same-size copy. Kept whole on every rank (input embedding served from CPU) the table costs at most its full size on the device. Replicating therefore never needs more device memory than the root gather, whatever the table's share of the device. The 0.15 device-fraction floor from #18028 missed gpt-oss-20b 4-bit on a T4 (2,316,533,760 table bytes vs a 2,345,405,645 byte threshold), whose first forward then ran out of memory in the root all-gather (2.16 GiB). FSDP2Config.replicate_io_tables now defaults to True (always, when the device size is known). A float still means a minimum device fraction, False / 0 never. CPU meshes, tied / trainable tables, explicit units, the fit and root-only layouts (where frozen weights are already replicated), CPU offload and pipeline stages are unchanged. UNSLOTH_FSDP2_REPLICATE_IO_TABLES=1 / 0 still forces either way. Tests: flip tests at gpt-oss's table share of a T4 (picked by default, missed by the old 0.15 floor), the floor boundary, and a gloo world of 2 where the default keeps both tables out of the root with loss / grads matching one process.
…the router aux loss is off Pipeline parallelism refused every mixture-of-experts family outside the carried set (Qwen3-MoE, Qwen4Exp and their multimodal wrappers), even when the model adds no router auxiliary loss. gpt-oss loads with output_router_logits = False, so its stages cut nothing that needs carrying, yet UNSLOTH_PP_SIZE=2 stopped with "GptOssForCausalLM is not proven". A mixture-of-experts CausalLM whose config has output_router_logits off, or a zero router_aux_loss_coef, is now split like the families listed as having no auxiliary loss. With the loss on it stays refused: - at the split, as before; - at Trainer init: TRL >= 1.x SFT / DPO turn output_router_logits on inside their own __init__ from args.router_aux_loss_coef (None = the architecture's, 0.9 for gpt-oss), so the default SFTConfig is refused with a pointer to router_aux_loss_coef = 0.0; - at every stage forward, if the config is switched on after the split (the last stage would otherwise add the loss over its own routers only). With a zero coefficient the stages skip the router logits. Models with no output_router_logits switch (DeepSeek-V3 style) keep the old refusal; the carried families are unchanged. Tests (gloo, world 2, CPU): PP=2 vs gradient accumulation in one process for tiny gpt-oss (full and LoRA, gpipe and 1F1B, coefficient 0 with logits on, 4 micro-batches) and Mixtral, losses / grads within 1e-5; aux on stays refused at the split; the Trainer-init and stage-forward refusals.
…er aux loss off The pipeline split now trains gpt-oss when its router auxiliary loss is off, but the composition registry still refused every gpt-oss x pp row (MoE x pp runs only with a row carrying parity / engagement / compile evidence), so UNSLOTH_PARALLEL=pp=2 on gpt-oss-20b stopped with "no supported cell covers it". Rows opened (aux off, gpipe / 1f1b, eager attention): - gpt_oss x lora and x lora+experts: tests/test_pp_moe_aux_off_gloo.py, pp2 vs gradient accumulation in one process, now also with expert LoRA (target_parameters) and HF reentrant / non-reentrant checkpointing. - gpt_oss x qlora: the same stage cut (4-bit experts stay inside the layers), measured on 2x T4 with unsloth/gpt-oss-20b-unsloth-bnb-4bit. - Checkpointing: none, HF, and Unsloth's offloading checkpoint (nothing is captured across it with the auxiliary loss off). With the loss on (TRL >= 1.x SFTConfig default for gpt-oss) the refused row now says to set router_aux_loss_coef = 0.0, and other uncarried families with the loss off say no gloo parity run covers them yet, instead of "refused at the split". Kaggle 2x T4, gpt-oss-20b bnb-4bit, router_aux_loss_coef = 0.0, seq 1024, 8 rows per step, 8 steps: pp2 (gpipe, 4 micro-batches, layers 12 / 12) 357 tok/s, peak 7.9 / 12.2 GiB, vs one process split over both GPUs 304 tok/s; losses within 0.0065 (split vs split A/A 0.0025).
|
@codex review |
Codex Review Summary: ✅ CompletedThis 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. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 331c1a436a
ℹ️ 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".
| ("gpt_oss", precision, False, "pp"): (f"{_GPT_OSS_PP}[{ids}]",) * 2 | ||
| + ("eager: no compiled region",) | ||
| for precision, ids in _GPT_OSS_PP_CASES.items() |
There was a problem hiding this comment.
Classify zero router coefficients as aux-off before gating
For a gpt-oss model with output_router_logits=True and router_aux_loss_coef=0.0, the new pipeline implementation permits training, but the Trainer capability gate still rejects it: _aux_loss_on() returns True immediately when router logits are configured, without checking the zero coefficient. Consequently, query_from() selects the unsupported aux-on row instead of this newly supported row, and _parallel_capabilities_pre() raises before the pipeline can run. Update the capability classification to recognize the zero-coefficient case, and cover the actual query-generation path rather than only manually constructed aux-off queries.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 43f6696: _aux_loss_on now uses the effective coefficient (the TRL argument when set, else the config value), so router logits on with a zero coefficient classify as aux off, and a config without a coefficient stays aux on. test_capability_query_classifies_the_effective_coefficient goes through query_from (6 cases); the capabilities and PP MoE suites pass (153 passed, 2 skipped).
… as aux loss off _aux_loss_on returned True whenever output_router_logits was configured, so a gpt-oss model with router_aux_loss_coef = 0.0 picked the unsupported aux-on row at Trainer init before the pipeline split (which already trains that case) could run. The effective coefficient (the TRL argument, else the config's) now decides; a config without a coefficient stays aux on. The new test goes through query_from.
|
@codex review |
|
Codex Review: Didn't find any major issues. What shall we delve into next? 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". |
[skip ci]
… with its output (rest-2 timeouts) (#18180) `tests/test_ddp_find_unused_default.py::test_trainable_embeddings_train_under_ddp_reentrant_checkpointing` hits pytest-timeout in the CPU `rest-2` shard on unrelated PRs (#18135, #18165, #18171 today): ``` tests/test_ddp_find_unused_default.py:285: in test_trainable_embeddings_train_under_ddp_reentrant_checkpointing proc = subprocess.run( E Failed: Timeout (>330.0s) from pytest-timeout. ``` The test takes about 11 s locally and hung only on some workers, with no child output in the log. ## Cause The test copies `os.environ` into both children: the single-process reference and the `torchrun` pair. The worker decides it is distributed from `WORLD_SIZE`. Several tests write rank variables (`RANK`, `WORLD_SIZE`, `MASTER_PORT`, ...) into the pytest process environment, so on a worker that ran one of them first, the single-process reference sees `WORLD_SIZE=2`, calls `init_process_group("gloo")` and waits for a second rank that never comes. It never returns, and the child's `timeout = 600` is longer than pytest-timeout's 330 s, so CI only showed a bare timeout. Reproduced on main by running the file with `WORLD_SIZE=2 RANK=0 MASTER_ADDR=127.0.0.1 MASTER_PORT=29555` in the environment: it hangs until killed. ## Fix - `_rank_env(tmp_path)` builds the child environment without `RANK`, `WORLD_SIZE`, `LOCAL_RANK`, `LOCAL_WORLD_SIZE`, `GROUP_RANK`, `ROLE_RANK`, `MASTER_ADDR`, `MASTER_PORT` (torchrun sets its own) and the `UNSLOTH_DDP_FIND_UNUSED_PARAMETERS_AUTO` override the test already dropped. - `_run_child` runs each child under a timeout below pytest-timeout (150 s each for the two-step test, 300 s for the single torchrun in the VLM test) and, if one still hangs, fails with the tail of its output instead of a bare timeout. - Both DDP tests in the file use them. ## Verification - `tests/test_ddp_find_unused_default.py`: 63 passed. - Same file with `WORLD_SIZE=2 RANK=0 MASTER_ADDR=127.0.0.1 MASTER_PORT=29555` exported: 63 passed (main: hangs).
…s off (gloo-pp red since #18165) (#18184) `Repo tests (CPU, gloo-pp)` fails on main since #18165 (seen on the staging run of #18168, an audio.cpp installer change, and on #18165's own run): ``` tests/test_pp_env_gloo.py: test_pp_env_layout_and_refusals E assert ('mixture-of-experts' in ((None or ''))) tests/test_pp_native_gloo.py: test_pp2_refusals E assert 'mixture-of-experts' in ((None or '')) ``` ## Cause #18165 changed what pipeline parallel accepts: a mixture-of-experts model whose router aux loss pp does not carry between stages now splits and trains with that loss off, and is refused only once the loss is turned on (in the stage forward, and at Trainer init when TRL or the config turns it on). Its new `tests/test_pp_moe_aux_off_gloo.py` covers both halves, including `test_pp2_uncarried_moe_with_aux_on_stays_refused`. The two older refusal tests still expected every such load (OLMoE in `test_pp2_refusals`, the tiny MoE in `test_pp_env_layout_and_refusals`, both with the aux loss off by default) to be refused. The behaviour change is intended; the tests predate it. ## Fix Both assertions now expect the load to go through (`None`), with a comment pointing at the aux-on refusal coverage in `test_pp_moe_aux_off_gloo.py`. The other refusals in both tests (MLA, tied trainable embeddings, unsupported trainer options, ...) are unchanged. ## Verification - main: both tests fail as above. - this branch: the two tests plus `tests/test_pp_moe_aux_off_gloo.py`: 23 passed.
…without the chunk, expandable segments on every rank) (unslothai#18287) ## Summary With native FSDP2, `Trainer.__init__` (the sharding step) was the highest GPU memory point of the whole run on Kaggle 2x T4. The model was `unsloth/Qwen3.8-27B-unsloth-bnb-4bit` (QLoRA, sharded loading). Sharding peaked at 13.22 / 13.90 GiB reserved per rank on a 14.56 GiB T4. There are two causes, fixed in two commits. 1. **The table chunk stayed on the GPU during its gather.** `shard_model` keeps the frozen, untied `lm_head` whole on every rank (unslothai#18165) and builds it by all-gathering the chunk each rank loaded. That chunk stayed on the GPU for the whole gather, next to the full table, so sharding briefly needed chunk + full table + gather slices on top of the loaded model. 2. **Ranks above 0 ran without `expandable_segments`.** `bind_local_cuda_device` calls `torch.cuda.set_device(LOCAL_RANK)` at `import unsloth` on every rank above 0. That starts CUDA and fixes the caching allocator settings before `unsloth_zoo` exports its default `PYTORCH_ALLOC_CONF=expandable_segments:True`. Rank 0 does not bind, so only rank 0 got expandable segments. - On the 27B, rank 1 ended sharding with 511 allocator segments against rank 0's 5. - Two freed 1.2 GiB table chunks stayed reserved, each pinned by a 1.5 MiB block in its tail. - Rank 1 reserved 2.2 GiB more than rank 0 after sharding and about 0.9 GiB more in training. ## Changes `unsloth/models/fsdp2_load.py`: - `gather_replicated` hands each chunk over to `_full_from_chunks` as the only reference to it. - A chunk of at least one gather slice (64 MiB) on an accelerator is copied to host memory, and its GPU block is released before the full table is allocated. The slices are then fed from the host copy. - Each slice's buffers are dropped before the next slice is allocated. - A chunk that another pending entry still names (a shared parameter) is gathered as before. - The gathered bytes are identical. `unsloth/_gpu_init.py`, `unsloth/parallel_env.py`: - The allocator variables are recorded before `import unsloth_zoo`. - If the import changed them after CUDA had already started, the new settings are applied with `torch.cuda.memory._set_allocator_settings` (torch 2.1+). - If CUDA has not started yet, torch reads the environment itself, so single-process runs and rank 0 behave as before. ## Kaggle 2x T4: Qwen3.8-27B bnb-4bit, FSDP2, sharded load Setup: LoRA r 8, 1,024-token rows, GA 2, 3 steps, `adamw_8bit`, fp16. All arms ran in one kernel on unsloth 31b5c7a with zoo main 5baf98d. Numbers are GiB per rank, as peak reserved / peak allocated. | phase | main, rank 0 | main, rank 1 | this PR, rank 0 | this PR, rank 1 | |---|---|---|---|---| | from_pretrained | 10.67 / 10.64 | 10.92 / 10.81 | 10.67 / 10.64 | 10.67 / 10.64 | | get_peft_model | 10.85 / 10.80 | 11.09 / 10.97 | 10.85 / 10.80 | 10.85 / 10.80 | | Trainer init (sharding) | **13.22 / 12.36** | **13.90 / 12.53** | **11.16 / 11.11** | **11.16 / 11.11** | | 3 training steps | 12.75-12.82 / 12.06 | **13.75 / 12.23** | 12.82 / 12.06 | **12.82 / 12.06** | - **Peak.** The run-wide peak falls from 13.90 GiB (rank 1, sharding) to 12.82 GiB (training). Sharding is no longer the highest point. - **Repeats.** Main was run 3 times (2 in an earlier kernel) and this PR twice. Sharding peaks were identical to 3 decimals within each arm. Rank 0's training peak varies between 12.75 and 12.82 on main alone. - **Losses.** Steps 1 and 2 match bit for bit in every arm (2.246492, 2.280375). Step 3 varies run to run on main itself (2.178731, 2.178771, 2.178793), and this PR's runs (2.178710, 2.178716) are within 1e-4 of those. - **Host RAM.** During sharding the host peak rises by about 1.2 GiB per rank (3.74 to 4.9 GiB private), while the chunk waits in host memory. The training host peak is unchanged (4.1 to 4.5 GiB). ## Correctness on B200 (relative memory, not a T4 measurement) - **Model.** A cut-down Qwen3.8-27B: the real config with real widths, vocab 248,320 and untied 2.37 GiB tables, but 4 text layers and 2 vision blocks. Random weights, quantized to bnb-4bit with the real checkpoint's skip list. - **Setup.** 2 ranks on one B200 with gloo carrying CUDA tensors. The T4 is emulated: `total_memory` / `mem_get_info` report 14.56 GiB, fp16 weights, fp16 AMP. `UNSLOTH_FSDP2_SHARDED_LOAD=1`, `UNSLOTH_FSDP2_LAYOUT=sharded`. - **Scope.** Both ranks use LOCAL_RANK 0 here, so this run covers the first commit only. - **Result.** Sharding peak drops from 5.375 / 4.61-4.63 to 3.34-3.42 / 3.256 GiB. Training peak is unchanged at 4.455 reserved. - **Bitwise checks.** Losses, grad norms and per-rank LoRA weight checksums are bitwise equal to main, in two runs per arm. ## Tests - `tests/test_fsdp2_sharded_gather_peak.py` (CUDA, about 2 s): - The chunk must leave the GPU before the full table is allocated. Main fails it with 288 MiB over the start against a 64 MiB limit. - A shared chunk is gathered once and bit-exact. - A gather to host frees the GPU chunk. - `tests/test_parallel_env_allocator.py`: - CPU unit tests for the late allocator settings: torch 2.10+ and older variable names, the standby case that turns expandable segments off, and the not-started case. - A CUDA test that starts CUDA before `import unsloth`, as a rank above 0 does, and checks the new segments are expandable. Main fails it: `PYTORCH_ALLOC_CONF=expandable_segments:True` is set, but the segments are not expandable. - **Flip results on B200:** main fails 2 and passes 2 of the CUDA tests; this PR passes all 4. The CPU unit tests pass: 5 passed, 1 skipped (the CUDA test). - **Existing CPU suites**, with the same results on main: - `test_fsdp2_native_io_tables_gloo`, `test_fsdp2_native_sharded_load_gloo`, `test_sharded_load_bnb4_gloo`, `test_fsdp2_native_trainer_init_any_loader_gloo` and `test_sharded_load_host_tables`: 68 passed, 2 failed. The two failures are `test_sharded_loading_matches_full_load_shard_model[qwen2_5_vl-None-lora-False]` and `[llama-overrides9-lora-remap]`, which fail on main too. - `test_parallel_env`: 138 passed. `test_bind_local_cuda_device`: passes. ## Not covered - Real multi-GPU runs other than Kaggle 2x T4 NCCL: no AMD, Windows, or more than 2 GPUs. - TP, PP and DDP on real GPUs. The second change also gives their ranks above 0 the allocator settings rank 0 already had. Their memory was not re-measured. - A fit-layout sharded load. Every frozen chunk of at least 64 MiB now takes the host round trip there, and load time was not measured for that combination.
Two multi-GPU gaps for gpt-oss-20b (and other models in the same shape) on 2x T4.
1. Native FSDP2: frozen untied input / output tables stay out of the root unit at any size
The root unit is wrapped with
reshard_after_forward=False, so a frozen table left in it is gathered at the first forward and held whole until backward ends, costing its full size plus its shard (and a second copy briefly while gathering). Kept whole on every rank, it costs at most its full size, and the input embedding is served from CPU, so keeping it whole never needs more GPU memory than the root gather. The old 15% device-fraction threshold left gpt-oss-20b's 2.16 GiB tables in the root and the first forward ran out of memory.FSDP2Config.replicate_io_tablesnow defaults toTrue; a number still works as a minimum device fraction andFalse/0turns it off. Unchanged: CPU meshes, tied or trainable tables, the fit and root-only layouts (anything under 40% of the card never reaches this code), CPU offload and PP stages.2. Pipeline parallel: MoE models whose router aux loss cannot be carried across stages train when the aux loss is off
The split refused every MoE family outside the carried set even with the aux loss off, and the capabilities registry had no gpt-oss x pp row. An uncarried MoE model is now allowed when
output_router_logitsis off or the coefficient is 0; it is refused again (with a pointer torouter_aux_loss_coef = 0.0) if the aux loss is turned on at Trainer init or seen at a stage forward. Models with nooutput_router_logitssetting at all stay refused. The registry opens gpt-oss x {lora, lora+experts, qlora} x aux off x pp for gpipe / 1F1B.Note: TRL 1.x turns gpt-oss's router aux loss on by default, so PP needs
router_aux_loss_coef = 0.0inSFTConfig; the default config now gets that message instead of a generic refusal.Kaggle 2x T4,
unsloth/gpt-oss-20b-unsloth-bnb-4bitLoRA, fp16, 8 stepsOther models, same session: Llama-3.1-8B 4-bit on the sharded layout 679 tok/s at 4.20 / 4.54 GiB with the new rule vs 676 tok/s at 8.11 / 8.43 GiB with the old one (losses identical to 1e-4); Llama-3.2-1B takes the fit layout and is unchanged. No run had a NaN loss or a skipped fp16 step.
Tests (CPU, gloo)
tests/test_fsdp2_native_io_tables_gloo.py: tables at gpt-oss's share of a T4 are kept whole by the new default (missed by the old 0.15), an exact-boundary flip for an explicit fraction, and a world-2 run where both tables stay out of the root with loss and grads matching one process. 2 of 11 fail on main, all pass here, on transformers 4.57.6 and 5.17.tests/test_pp_moe_aux_off_gloo.py(new, 15 tests): PP=2 vs gradient accumulation within 1e-5 for tiny gpt-oss and Mixtral (full, LoRA, expert LoRA, gpipe, 1F1B, coefficient 0 with logits on, 4 micro-batches, both HF checkpointing modes); aux loss on is still refused.tests/test_parallel_env.pyandtests/test_parallel_capabilities_evidence.py, 256 passed, 2 skipped.Not covered
unsloth/gpt-oss-20bon T4 still overflows to NaN: its packed experts compute in float16 and overflow at layer 23. That is a separate float16 fix; on T4 / V100 use the bnb-4bit checkpoint.