Skip to content

Native TP: opt-in vocab-parallel lm_head and cross entropy - #18625

Merged
danielhanchen merged 5 commits into
mainfrom
nwe-vocab-parallel-head
Nov 21, 2026
Merged

danielhanchen merged 5 commits into
mainfrom
nwe-vocab-parallel-head

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Summary

Native tensor parallel (apply_tensor_parallel) keeps lm_head replicated, so every tp rank holds the whole output head and runs the whole-vocabulary loss. For a Qwen-size vocabulary (151,936 x 4,096 in 16-bit = 1.16 GiB) that is 0.58 GiB per rank of duplicated parameters at tp = 2 and 0.87 GiB at tp = 4, plus a head matmul that does not shrink with tp.

This adds an opt-in vocab-parallel output head:

  • TPConfig(vocab_parallel_head = True) or UNSLOTH_TP_VOCAB_PARALLEL=1 shards an untied lm_head by vocab rows (a LoRA lora_B on it shards with it; lora_A stays replicated with its gradient summed over tp). Off by default.
  • lm_head(x) all-gathers the logits, so every caller (generate, eval, UNSLOTH_RETURN_LOGITS, plain transformers forwards) still sees the whole logits.
  • The Unsloth causal LM loss path (CausalLM_fast_forward) calls the new vocab_parallel_cross_entropy: per-rank logits for chunks of tokens, global max and log-sum-exp through all-reduces, the target logit from the owning rank, each chunk recomputed in backward. Logit softcapping, logit scaling, num_items_in_batch and shift_labels follow the fused loss.
  • Refused before anything changes, with the reason: tied input / output embeddings, a modules_to_save / quantized / QAT / biased head, a vocab size not divisible by tp, pipeline parallel, and model forwards that read lm_head.weight directly (compiled fused losses would see one shard). shard_model over a tp model with a vocab-parallel head (dp x tp) is refused as well.

Tests

tests/test_tp_vocab_parallel_gloo.py (gloo, CPU, fp32, tiny Qwen3 with its 151,936 vocab):

  • tp = 2 and tp = 4, head frozen, LoRA on lm_head, and fully trainable lm_head: logits, every gradient, two optimizer steps of losses, and vocab_parallel_cross_entropy (chunked, softcap + scale, n_items) loss and gradients match one process.
  • Engagement counters: two gathering head forwards and one vocab-parallel cross entropy per case.
  • Per-rank head bytes are exactly 1 / tp of the replicated head (plus the replicated lora_A).
  • generate and save_tp_adapter with LoRA on lm_head match one process.
  • Tied embeddings and modules_to_save heads are refused and leave the model untouched; a forward reading lm_head.weight directly is refused.

Passes on transformers 4.57.6 / torch 2.14.1, transformers 5.17.0 / torch 2.10.0 and transformers 5.23.0 / torch 2.15.0. The existing tensor parallel suites (test_tp_native_oracle.py, test_tp_native_gloo.py, test_tp_eval_gloo.py, test_tp_env_gloo.py) are unchanged: 125 passed, with test_stablelm_4x_is_refused failing on main as well.

Not covered yet

  • GPU numbers (per-rank peak memory and step time against the replicated head on two GPUs) are pending.
  • dp x tp, pipeline parallel and tied embeddings stay on the replicated head.
  • GRPO's hidden-state path reads lm_head.weight in the trainer and is not routed through the vocab-parallel loss.

TPConfig(vocab_parallel_head = True) or UNSLOTH_TP_VOCAB_PARALLEL=1 shards an untied
lm_head (and a LoRA lora_B on it) by vocab rows over the tp ranks. lm_head(x) all-gathers
the logits so every caller stays correct; the Unsloth causal LM loss path calls
vocab_parallel_cross_entropy, which takes the global max / log-sum-exp and the target
logit through all-reduces over chunked, recomputed per-rank logits and never builds the
whole-vocabulary logits. Tied embeddings, modules_to_save / quantized / QAT heads,
pipeline parallel, dp x tp and forwards reading lm_head.weight directly are refused
before anything changes. Off by default.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 20, 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-20T14:35:03.333716Z 0b3b159 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: fa3f22ae50

ℹ️ 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 thread unsloth/models/llama.py Resolved
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 0b3b159140

ℹ️ 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 added a commit to Imagineer99/unsloth that referenced this pull request Nov 21, 2026
@danielhanchen
danielhanchen merged commit 77f37de into main Nov 21, 2026
@danielhanchen
danielhanchen deleted the nwe-vocab-parallel-head branch November 21, 2026 06:56
danielhanchen added a commit that referenced this pull request Nov 21, 2026
## Problem

`Repo tests (CPU, rest-2)` fails on `main` since #18625 and on every PR
based on it (for example #17742, #18032, #18610, #18740):

```
test_source_read_encoding.py::test_checked_in_file_reads_name_an_encoding[3]
AssertionError: 1 file reads in the test trees touch a checked-in file with the platform default encoding,
so they break on Windows as soon as that file gains a non-ASCII byte. Pass encoding = "utf-8" ...
  'tests/test_tp_vocab_parallel_gloo.py:307: open()'
```

## Cause

#18625 added a source check to `tests/test_tp_vocab_parallel_gloo.py`
that reads `unsloth/models/llama.py` with a bare `open(...)`. On Windows
that uses the locale code page, so it would raise `UnicodeDecodeError`
once `llama.py` carries a non-ASCII byte. The guard is right; the new
read is missing its encoding.

## Fix

Pass `encoding = "utf-8"` to that `open()`. One line, test-only.

## Verification

- On `main`: `tests/test_source_read_encoding.py -k
checked_in_file_reads` fails (`[3]`, naming this line).
- With this change: 16 passed, and
`tests/test_tp_vocab_parallel_gloo.py` passes (11 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