Repository navigation
Tensor parallel: serve a large frozen input embedding from CPU memory (Qwen3.8-27B 4-bit on 2x T4) - #18068
Conversation
… (Qwen3.8-27B 4-bit on 2x T4) Under UNSLOTH_PARALLEL=tp=2 every rank kept a whole copy of embed_tokens. For unsloth/Qwen3.8-27B-unsloth-bnb-4bit (vocab 248320, hidden 5120, untied) that is 2.37 GiB per rank, which left about 0.5 GiB for the first forward on a T4 and it ran out of memory in the first Gated DeltaNet layer. apply_tensor_parallel now serves a frozen, untied input embedding that holds at least 15% of the GPU from host memory through Unsloth's offload_embedding hooks (as native FSDP2 does since #18028), before the projections are sharded. Only when tp spans the whole world and the model is not a pipeline stage; ranks agree over the tp group. TPConfig.host_input_embedding sets the fraction (0 = off) and UNSLOTH_TP_EMBED_ON_CPU=1/0 forces it on or 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: 83bb5eb0b6
ℹ️ 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".
| if host_embed is not None: | ||
| # Before sharding, whose slices need the room. | ||
| _serve_embedding_from_host(model, host_embed, rank) |
There was a problem hiding this comment.
Keep replica collectives on CUDA after offloading the embedding
On CUDA/NCCL TP runs where the input embedding is the first registered parameter (including Qwen3), moving it to CPU makes tp_replica._device(root) return CPU, since that helper returns the first parameter's device. Both generation and collective saving call gather_replica(), whose _plan() then passes that CPU device through _comm_device() into _room()'s dist.all_gather. NCCL cannot communicate CPU tensors, so these previously supported operations now fail, including adapter saving through tp_collective(select="adapters"). Update replica device selection to use the TP mesh or an accelerator parameter when enabling host embeddings; the CPU/gloo tests do not exercise this failure.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed on 2x T4: with the input embedding on the CPU and registered first (Qwen3-8B 4-bit, tp 2, UNSLOTH_TP_EMBED_ON_CPU=1), save_pretrained of the adapter and generate both failed with 'No backend type associated with device type cpu' from _room's all_gather. Fixed in 21d1b25: tp_native._compute_device returns the first parameter's device but skips lookup tables served from host memory, and tp_replica._device and tp_native._default_mesh use it. A new CPU test, where the host embedding is the first parameter, checks that the replica and comm devices resolve to the compute device; it fails on the previous head and passes now. On the same Kaggle setup the adapter save (504 tensors) and an 8-token generate now succeed on both ranks. The existing tp replica / save / native gloo suites are unchanged (70 passed, 9 skipped before and after).
With the input embedding served from CPU memory, it is often the first registered parameter (Qwen3: embed_tokens). tp_replica._device read the first parameter's device, so on a CUDA / NCCL run the replica gather and _room()'s all_gather got the CPU device, and generate and collective saving (save_pretrained of the adapter included) failed. tp_native._compute_device returns the first parameter's device while skipping lookup tables served from host memory (offload hooks or the plain CPU lookup); tp_replica._device and tp_native._default_mesh use it. [skip ci]
|
@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". |
…re (intermittent Broken pipe) (#18115) `tests/test_tp_host_input_embedding_gloo.py::test_tp_narrower_than_world_keeps_the_embedding` (added in #18068) fails intermittently in the `Repo tests (CPU, gloo-tp-env)` shard, seen on the staging run of #18106 (a frontend-only PR): ``` [rank1] TCPStore.cpp:106 sendBytes failed ...: Broken pipe File "tests/test_tp_host_input_embedding_gloo.py", line 107, in _case_world_wider_than_tp mesh = init_device_mesh("cpu", (world, 1), mesh_dim_names = ("dp", "tp")) torch.distributed.DistNetworkError: Broken pipe E AssertionError: rank exit codes [0, 1] ``` ## Cause In the `dp_x_tp` case each rank builds a `(world, 1)` mesh, so its `tp` group has one member and rank 0 never waits for rank 1. Rank 0 hosts the TCPStore, finishes, destroys its process group and exits. If rank 1 is still creating its mesh groups through that store, its next store write hits a closed socket. The TP code is fine; the test worker let rank 0 leave first. ## Fix The worker calls `dist.barrier()` after a case has saved its result, before `destroy_process_group()`, so no rank tears the store down while another still uses it. On a failure path nothing changes. ## Verification - Rank 1 delayed by 3 s before `init_device_mesh` (local only, not committed): - main: `rank exit codes [0, 1]` with the same `Broken pipe` as CI. - this branch: passes. - Whole file: 5 passed.
Problem
Under
UNSLOTH_PARALLEL="tp=2"every rank keeps whole copies of everything outside the attention / MLP regions. Forunsloth/Qwen3.8-27B-unsloth-bnb-4bit(vocab 248320, hidden 5120, untied,lm_headkept 16-bit) the per-rank breakdown after the sharded 4-bit load on a T4 is:in_proj_qkv)embed_tokens(replicated)lm_head(replicated)get_peft_model)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.pyapply_tensor_parallelserves 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 sameoffload_input_embeddinghooks native FSDP2 uses for this model since Native FSDP2: keep large frozen input / output embeddings out of the root unit (Qwen3.8-27B 4-bit on 2x T4) #18028. This happens before the projections are sharded, so their slices get the freed room.TPConfig.host_input_embeddingsets the fraction (0 = never).UNSLOTH_TP_EMBED_ON_CPU=1skips the size rule,0keeps the embedding on the GPU.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.pyembed_tokenson Qwen3 and others. With the table on the CPU that sent CPU tensors to NCCL.tp_native._compute_devicenow skips host-served lookup tables, andtp_replica._deviceandtp_native._default_meshuse it.lm_headstays 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=0andhost_input_embedding = 0turn it offtp 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.pyandtest_frozen_table_tp_gloo.pygive 80 passed, 25 skipped on both main and this branch.On one CUDA rank (tiny Qwen3 through
FastLanguageModel, tp 1) withUNSLOTH_TP_EMBED_ON_CPU=1against0, the embedding sits on the CPU with the offload hooks installed,lm_headstays 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
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_modelmoves 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-4bitwithUNSLOTH_TP_EMBED_ON_CPU=1(the embedding is the first parameter): without the replica device change,save_pretrainedandgenerateboth fail withRuntimeError: No backend type associated with device type cpuin_room'sall_gather. With it, one training step, the adapter save (504 tensors) and an 8-token greedy generate all succeed on both ranks.