Skip to content

Tensor parallel: serve a large frozen input embedding from CPU memory (Qwen3.8-27B 4-bit on 2x T4) - #18068

Merged
danielhanchen merged 3 commits into
mainfrom
tp-27b-fit
Nov 17, 2026
Merged

danielhanchen merged 3 commits into
mainfrom
tp-27b-fit

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Nov 17, 2026 •

Copy link
Copy Markdown
Member

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 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.
  • 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.

… (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.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 17, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-17T04:37:28.709979Z 21d1b25 Manual request
ℹ️ 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.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment on lines +2355 to +2357
if host_embed is not None:
# Before sharding, whose slices need the room.
_serve_embedding_from_host(model, host_embed, rank)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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]
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Bravo.

Reviewed commit: 21d1b25707

ℹ️ 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 8c99caf into main Nov 17, 2026
@danielhanchen
danielhanchen deleted the tp-27b-fit branch November 17, 2026 05:18
danielhanchen added a commit that referenced this pull request Nov 17, 2026
…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.
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