Repository navigation
Native FSDP2: keep large frozen input / output embeddings out of the root unit (Qwen3.8-27B 4-bit on 2x T4) - #18028
Conversation
…root unit The root unit never reshards after forward, so on the sharded layout it held the gathered embed_tokens and lm_head for the whole step, plus a same-size all-gather buffer while gathering. Qwen3.8-27B 4-bit on a 15 GiB T4 asked for 4.83 GiB on the first forward and went out of memory. Frozen, untied input and output embeddings outside every unit that hold at least 15% of the device now stay whole on every rank (UNSLOTH_FSDP2_REPLICATE_IO_TABLES forces it on or off). On a CUDA mesh the input embedding serves its lookups from host memory through the offload_embedding hooks (UNSLOTH_FSDP2_EMBED_ON_CPU=0 keeps it on the GPU), so per-rank memory stays where it was and nothing is gathered. Sharded loading now gathers a replicated parameter slice by slice into one output, on the GPU or straight into host memory, instead of holding the padded chunk, every rank's copy and their concatenation.
…pt whole With the input / output embeddings out of the root, Qwen3.8-27B 4-bit on 2x T4 still went out of memory on the first forward, a 264 MiB block gather with 2.56 GiB reserved but unallocated. Implicit prefetch all-gathers into FSDP2's own stream. On that same memory-tight layout, unshard on the current stream (_set_unshard_async_op) and keep the overlap with explicit one-ahead prefetch. UNSLOTH_FSDP2_UNSHARD_ASYNC_OP=0 turns it off.
|
@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: cf4600bf50
ℹ️ 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".
| for m in io_tables: | ||
| tables.update(m.parameters()) |
There was a problem hiding this comment.
Preserve the output head's mixed-precision compute dtype
When the frozen output head's storage dtype differs from config.param_dtype, adding it to the replicated tables removes the mixed-precision casting previously performed by the root FSDP unit. For example, an ordinary Transformers Qwen3 model stored in float32 and sharded with param_dtype=torch.bfloat16, fit_layout=False, and I/O replication enabled now feeds bfloat16 decoder outputs into an unmanaged float32 lm_head. Without an external autocast context, its linear projection raises a dtype-mismatch error on the first forward; the previous sharded head was gathered in bfloat16. Cast the replicated head appropriately, preserve equivalent input-casting behavior, or exclude incompatible heads from this optimization.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed and fixed in 7f532b8. With a float32-stored Qwen3 sharded with param_dtype=bfloat16, fit_layout=False and UNSLOTH_FSDP2_REPLICATE_IO_TABLES=1, the replicated lm_head received bfloat16 hidden states and the forward failed with a dtype mismatch. The input / output embeddings now leave the root unit only when its gather would not cast them (param_dtype unset, or equal to the tables' storage dtype; on torch < 2.8 also not when the root would be upcast to float32 as a mixed-dtype group). Otherwise they stay in the root and keep the cast and logits dtype they had before. The Qwen3.8-27B 4-bit 2x T4 case gathers as stored and is unaffected. test_io_tables_stay_in_the_root_when_the_gather_casts_them reproduces the failure on the previous head and passes now.
…them Kept whole, a table computes in its storage dtype, while the root unit gathers it in param_dtype. A float32-stored model sharded with a bfloat16 gather then fed bfloat16 hidden states into a float32 lm_head. Tables now leave the root only when the root would not cast them: param_dtype unset (gather as stored) or equal to their dtype, and on torch < 2.8 not part of a mixed-dtype root that main upcasts to float32. The 27B 4-bit T4 case gathers as stored and is unchanged.
|
@codex review |
|
Codex Review: Didn't find any major issues. Bravo. 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". |
… (Qwen3.8-27B 4-bit on 2x T4) (unslothai#18068) ### Problem Under `UNSLOTH_PARALLEL="tp=2"` every rank keeps whole copies of everything outside the attention / MLP regions. For `unsloth/Qwen3.8-27B-unsloth-bnb-4bit` (vocab 248320, hidden 5120, untied, `lm_head` kept 16-bit) the per-rank breakdown after the sharded 4-bit load on a T4 is: | tensor group | GiB per rank | | --- | --- | | decoder projections (sharded, incl. Gated DeltaNet `in_proj_qkv`) | 8.08 | | `embed_tokens` (replicated) | 2.37 | | `lm_head` (replicated) | 2.37 | | vision tower (replicated) | 0.86 | | norms and small decoder tensors | 0.01 | | LoRA (r 8, after `get_peft_model`) | 0.15 | That is 13.83 / 14.01 GiB allocated on the two ranks at the start of training, out of 14.56 GiB. The first forward then fails in the first Gated DeltaNet layer: `Tried to allocate 256.00 MiB ... 94.75 MiB is free ... 14.05 GiB is allocated by PyTorch`. ### Change `unsloth/models/tp_native.py` - `apply_tensor_parallel` serves the input embedding from host memory instead of replicating it, when the table is frozen, untied, not shared with another module, a plain floating tensor on the GPU, and holds at least 15% of the GPU. The lookup runs on the CPU and only the looked-up rows go to the GPU, through the same `offload_input_embedding` hooks native FSDP2 uses for this model since unslothai#18028. This happens before the projections are sharded, so their slices get the freed room. - Ranks AND the decision over the tp group. It only applies when tp spans the whole world and the model is not a pipeline stage, so dp x tp and pp x tp layouts are unchanged. - `TPConfig.host_input_embedding` sets the fraction (0 = never). `UNSLOTH_TP_EMBED_ON_CPU=1` skips the size rule, `0` keeps the embedding on the GPU. - Tied tables, trainable embeddings (`modules_to_save`), and any model whose embedding is below 15% of its GPU are left as before. On an 80 GB card this model's table is 3%, so nothing changes there. `unsloth/models/tp_replica.py` - The replica gather (generate, collective saves) took its device from the model's first parameter, which is `embed_tokens` on Qwen3 and others. With the table on the CPU that sent CPU tensors to NCCL. `tp_native._compute_device` now skips host-served lookup tables, and `tp_replica._device` and `tp_native._default_mesh` use it. `lm_head` stays replicated (the fused loss reads its full weight) and the vision tower stays on the GPU: with the embedding moved, training peaks at 12.42 GiB allocated (13.84 GiB reserved) of 14.56 GiB, so neither was needed. ### Tests New `tests/test_tp_host_input_embedding_gloo.py` (CPU, gloo, world 2, tiny untied Qwen3 with LoRA): - selection rules: frozen untied table picked, tied or trainable table refused, auto mode needs a GPU table, `UNSLOTH_TP_EMBED_ON_CPU=0` and `host_input_embedding = 0` turn it off - tp 2 with the host-served embedding: the decoder is really sharded, the embedding is served from the host on both ranks, and loss and LoRA grads over 2 steps match one process within 1e-5 - fault injection: perturbing one rank's table breaks that parity - a world wider than tp (dp 2 x tp 1) keeps the embedding - the replica device resolves to the compute device, not the CPU, when the host-served embedding is the first parameter (with an NCCL backend stubbed in) On main all 5 fail; on this branch all 5 pass. The existing `test_tp_native_gloo.py`, `test_tp_env_gloo.py`, `test_tp_gdn_gloo.py` and `test_frozen_table_tp_gloo.py` give 80 passed, 25 skipped on both main and this branch. On one CUDA rank (tiny Qwen3 through `FastLanguageModel`, tp 1) with `UNSLOTH_TP_EMBED_ON_CPU=1` against `0`, the embedding sits on the CPU with the offload hooks installed, `lm_head` stays on the GPU, and the loss and all 28 LoRA grads match. ### 2x T4 (Kaggle), Qwen3.8-27B 4-bit, LoRA r 8, batch 1 x GA 4, 1,024-token rows, adamw_8bit, 20 steps | run | result | steady tok/s | end to end tok/s | peak allocated per GPU (GiB) | peak reserved per GPU (GiB) | | --- | --- | --- | --- | --- | --- | | main, tp 2 | OOM in the first forward | - | - | 14.05 at the OOM | 14.26 | | this branch, tp 2, run 1 | 20/20 steps | 102.5 | 82.8 | 12.24 / 12.42 | 12.31 / 13.84 | | this branch, tp 2, run 2 | 20/20 steps | 101.2 | 83.9 | 12.24 / 12.42 | 12.31 / 13.84 | | 1-GPU split (one process, layers over both GPUs) | 20/20 steps | 64.3 | 56.3 | 11.16 / 11.27 | 11.23 / 11.31 | Both tp runs see the same tokens per step as the split run, and their losses are within 0.0023 of it at every step (mean difference 0.0004). The two tp runs differ by at most 0.0011 from each other. Rank 0 and rank 1 log identical losses. adamw_8bit is kept (local shard stepping). The load itself is unchanged and still peaks at 13.97 / 14.26 GiB reserved before `get_peft_model` moves the embedding, so the load margin on a T4 stays small. Reading the table straight into host memory during the sharded load would remove that peak; it is not part of this change. Adapter save and generate under tp 2 on 2x T4, `unsloth/Qwen3-8B-unsloth-bnb-4bit` with `UNSLOTH_TP_EMBED_ON_CPU=1` (the embedding is the first parameter): without the replica device change, `save_pretrained` and `generate` both fail with `RuntimeError: No backend type associated with device type cpu` in `_room`'s `all_gather`. With it, one training step, the adapter save (504 tensors) and an 8-token greedy generate all succeed on both ranks.
Problem
On the sharded layout the root unit holds everything outside the decoder and vision blocks, including
embed_tokensandlm_head, and it is wrapped withreshard_after_forward=False. Its gather is therefore held for the whole step, and FSDP2 allocates the all-gather output plus a same-size unsharded copy while gathering it.For
unsloth/Qwen3.8-27B-unsloth-bnb-4bit(vocab 248320, hidden 5120, untied,lm_headkept 16-bit) the root is 4.83 GiB:embed_tokens2.37 GiB,lm_head2.37 GiB, vision patch / position embeddings and merger 0.09 GiB. On 2x T4 withUNSLOTH_PARALLEL=dp=2,fsdp=1the model loads sharded (about 10.9 GiB per rank) and the first forward fails withTried to allocate 4.83 GiB ... 3.32 GiB free. Splitting the two tables into their own units does not help: each still needs about 4.7 GiB while gathering.Change
unsloth/models/fsdp2_native.pyFrozen, untied input and output embeddings that sit outside every unit and together hold at least 15% of the device are kept whole on every rank instead of in the root unit. Ranks AND the decision over the mesh.
On a CUDA mesh the input embedding serves its lookups from host memory through the existing
offload_input_embeddinghooks, so per-rank GPU memory stays where it was (half ofembed_tokensleaves, the other half oflm_headarrives) and neither table is gathered.UNSLOTH_FSDP2_REPLICATE_IO_TABLES=1/0forces the behaviour on or off;UNSLOTH_FSDP2_EMBED_ON_CPU=0keeps the input embedding on the GPU. Tied tables, trainable tables, explicit units, root-only / replicated-frozen layouts, CPU offload,shard_frozen=Trueand pipeline stages are left as before.On that same memory-tight layout (tables kept whole, CUDA), FSDP2 unshards on the current stream (
_set_unshard_async_op(True)) with explicit one-ahead forward / backward prefetch, instead of implicit prefetch on its own all-gather stream. Without this the first forward still failed on a 264 MiB block gather with 2.56 GiB reserved but unallocated, withexpandable_segmentsalready active.UNSLOTH_FSDP2_UNSHARD_ASYNC_OP=0turns it off. Numerics are unchanged (stream placement only).unsloth/models/fsdp2_load.pylm_head. It now all-gathers 64 MiB slices into one preallocated output, on the GPU or straight into host memory for the CPU-served embedding.Tests
New
tests/test_fsdp2_native_io_tables_gloo.py(CPU, gloo, world 2):On main 5 of the 6 new tests fail (only the disabled-path control passes); on this branch all 6 pass. The existing FSDP2 and frozen-table suites have the same 10 failing test IDs before and after (Qwen2.5-VL / Qwen3-VL units, vision dummy, two sharded-load cases, two trainer clip tests), with 550 passing on this branch.
2x T4 (Kaggle), Qwen3.8-27B 4-bit, LoRA r 8, batch 1 x GA 2 per rank, 1,024-token rows, adamw_8bit, no allocator env set by the job
Tried to allocate 4.83 GiBUNSLOTH_FSDP2_UNSHARD_ASYNC_OP=0)Both runs of this branch that reached the GPU trained; without the stream change 1 of 5 runs trained. The second GPU peaks at 13.76 of 14.56 GiB reserved, so the margin on a T4 is small. On larger GPUs the change only removes the 4.83 GiB root gather.