[RFC] Vocabulary-parallel per-token ops for RL and on-policy distillation
Motivation
#8173 added vocabulary-parallel cross-entropy for AutoTP. The original motivation was sharding the OPSD teacher across TP ranks, which serves the On-Policy Distillation Trainer item on the roadmap (#8104). Cross-entropy alone does not cover RL and distillation losses. They need per-token quantities computed over the full vocabulary:
| Method | Per-token quantity needed |
|---|---|
| GRPO / PPO | log-prob of the sampled token, plus entropy |
| Policy-gradient OPD (Thinking Machines, Qwen3, verl) | sampled-token log-probs of student and teacher (k1/k3 KL estimators) |
Teacher top-k distillation (verl forward_kl_topk) |
student log-probs at the teacher's top-k ids |
| Dense KL distillation (DeepSpeedExamples OPSD, TRL GKD) | full-vocab forward or reverse KL |
| Token selection (TIP, arXiv 2604.14084) | student entropy and teacher–student KL |
With AutoTP's vocab-parallel LM head, each rank holds only [B, T, V/tp] logits. Before this work, computing these quantities required all-gathering the full [B, T, V] logits. For example, the DeepSpeedExamples OPSD trainer gathers the teacher's full logits and caches them on CPU. On long sequences with 128K–256K vocabularies, these logits dominate peak memory. Megatron users had sharded versions of these ops from verl (vocab_parallel_log_probs_from_logits, vocab_parallel_entropy, _VocabParallelKLDivergence); AutoTP had nothing equivalent.
Proposal
Add three small ops in deepspeed.sequence.vocab_parallel_ops that work directly on the local shard:
vocab_parallel_logprobs(logits, index, tp_group, vocab_start_index, vocab_end_index, ignore_index=-100) # index: [...] or [..., k]
vocab_parallel_entropy(logits, tp_group)
vocab_parallel_kl_div(student_logits, teacher_logits, tp_group, reverse=False) # KL(t||s), or KL(s||t) if reverse
- Each op returns an fp32 per-token tensor, replicated across the TP group. Masking, reduction, and temperature are left to the caller, which is where existing trainers already handle them.
- The ops compose into the losses above. For example, teacher top-k forward KL is two lines on top of
vocab_parallel_logprobs. - Communication: one MAX and two SUM all-reduces of
[N]-sized per-token statistics. The KL op packs student and teacher statistics into the same collectives. The logits are never gathered. - Backward follows the Megatron convention: every rank backprops the same loss, so gradients are closed-form, local, and need no communication.
- Memory: each op saves only its inputs and per-token statistics, and processes rows in bounded chunks.
Measured on 1× Intel Arc Pro B70, T=8192, V_local=16032 (128K vocab / TP8), bf16. Peak is fwd+bwd, excluding inputs:
| Op | Naive PyTorch | Proposed |
|---|---|---|
| logprobs | 1506 MiB | 443 MiB |
| entropy | 3012 MiB | 586 MiB |
| reverse KL | 3012 MiB | 698 MiB |
| forward KL | 2510 MiB | 634 MiB |
Plan
| # | Item | Status | Notes |
|---|---|---|---|
| PR-1 | The three ops, with tests against a full-vocab oracle and docs | ✅ #8791 | Perf follow-up #8838 (merged): fused Triton kernels (eager fallback), ~20× faster fwd+bwd, no extra fp32 copies, no API change. Includes 0z5a's single-pass forward for entropy/KL (jinyouzhi/DeepSpeed#5). |
| PR-2 | Wire the ops into the OPSD example, so the sharded teacher caches V/tp logits instead of gathering full [B, T, V] logits |
🔄 deepspeedai/DeepSpeedExamples#1019 (@0z5a) | Covers forward and reverse KL. With #8838 and response-free chunk skipping, the vocab-parallel route is 1.22× / 1.17× the throughput of the gathered route (B2/ISL1024, B4/ISL2048) and uses 3.9 GiB/rank less peak memory. Eager greedy rollout gathers only the last position's logits (gathered_rollout_logits, Examples-only). |
| 3 | Masked streamed vocab-parallel logprobs / entropy from hidden states | 🎯 Our next priority (proposal; not implemented) | See the scope below, informed by TRL streamed scoring and the requirements in #8942. Fused-linear vocab-parallel CE and its Hugging Face forward integration are already merged (#8792, #8945). Streamed dense KL/JSD remains a separate, deferred extension: with #8838 the KL kernels take ~1.3% of GPU time in the PR-2 profile, so further fusion needs a demonstrated memory bottleneck rather than an assumed speedup. |
Rollout token selection with a sharded head
With vocab_parallel_lm_head, each rank holds [B, V/tp] last-position logits. On master, HybridEngineRollout applies argmax to that shard, which gives local indices and can pick different tokens on different TP ranks.
| # | Item | Status | Notes |
|---|---|---|---|
| R-1 | Core: full-vocabulary logits for token selection | 🔄 #9162 (anyadontfly; fixes #9158, split out of #9037) | Covered by anyadontfly. Done at the head instead of through a _token_selector hook. full_vocabulary_logits() sets gather_output=True on AutoTP's VocabParallelLinear heads only while generate() runs, so training still gets rank-local logits for vocab_parallel_logprobs. This also covers the paths that decode with HF generate() and bypass _token_selector (static batching, continuous-batching prefill for models without _supports_cache_class), plus repetition penalty and recorded log-probs, and the gather is captured in the decode graph. With logits_to_keep=1 it gathers [B, V] per step, the same as a hook. Ranks share the TP group's RNG state once per generate() call, and AutoTP's input check accepts DeepSpeedStaticCache. Measured cost (#9162): Qwen3-4B-Instruct-2507, bf16, TP2 on A100, 0.5–0.8% lower tok/s than vocab_parallel_lm_head: false on the graph paths, with 0.36 GiB less peak memory per GPU. |
| R-2 | Vocab-parallel token selection ops | ⏸️ low priority after #9162's measurement | Distributed argmax (one [B] all-reduce), Gumbel-max for temperature sampling, and a two-stage top-k (local top-k + all-gather of [B, tp×k] candidates) for top-k/top-p. Cuts per-step traffic from B×V to B or B×tp×k and avoids a full-vocabulary sort. Plugs into #9162 by leaving gather_output off. Only worth it if a workload shows the gather in decode time (e.g. PCIe-connected GPUs, large GRPO batches, 256K vocabularies, TP > 2). Repetition penalty and recorded log-probs would also need sharded versions. |
| R-3 | Capture token selection in the decode graph | ⏸️ after R-2 | With #9162 the gather is already inside the graph; this item is only about the selection step. Gumbel + argmax is graph-safe. |
Possible next steps (not yet owned)
| Item | Why |
|---|---|
| Teacher top-k cache | The other caching option in the original plan. It needs a vocab-parallel top-k, which R-2 provides. The student side already works through vocab_parallel_logprobs(index=[..., k]), and the cache does not depend on the teacher's TP degree. |
| Generalized JSD (0 < β < 1) | Core logits-based vocab_parallel_jsd is merged in #8958. It still materializes local logits; #1019 rejects JSD and neither OPSD nor TRL integration is provided by #8958. |
| Streamed vocab-parallel logprobs / entropy | Our next priority under item 3: TRL-style tiled LM-head scoring with TP-global normalization and a trainer-provided position mask to skip unscored projections. Return per-token quantities; keep loss reduction in the trainer. Coordinate a minimal training-side integration with deepspeedai/DeepSpeedExamples#1023 without duplicating its rollout or loss. |
| LM head on response positions only (Core) | ResponseTokenBatch.select_causal_logits still materializes logits for prompt positions. Selecting response hidden states before the head would bring #1019's chunk skipping into Core for both student and teacher. |
vocab_parallel_lm_head for init_inference |
Lets an inference-initialized teacher produce sharded logits. |
Proposal for item 3: streamed scoring for GRPO
Our next priority is an engine-level masked streamed scoring primitive, informed by TRL's streamed logprob approach (tracking issue, GRPO integration) and the requirements in #8942. Unlike the existing logits-based ops, it takes hidden states, local LM-head weights, target token IDs and a trainer-provided position mask, and returns FP32 per-token logprobs and optional entropy. Select scored positions before projection, tile over tokens and local vocabulary, combine normalization statistics across TP ranks, and recompute tiles in backward without materializing the full local logits shard. Support TP=1 too. The trainer owns mask selection and loss reduction; the primitive uses the mask to skip unscored LM-head projections, while prompt and tool-output tokens remain in the backbone context.
The first candidate consumer is the multi-turn GRPO example in deepspeedai/DeepSpeedExamples#1023. Its current checkpointed sequence chunks still project the whole vocabulary per chunk; local-vocabulary streaming and vocabTP can complement that token chunking, with coordinated backward recomputation. Coordinate a minimal training-side integration with its author as the agentic system evolves, rather than duplicate its rollout or loss. Actual TRL integration, streamed dense KL/JSD and rollout token selection in #9162 and R-2 are separate work.
Rollout/training logprob consistency is a semantic and validation requirement: explicitly distinguish policy probabilities from the transformed sampling distribution, including temperature and any enabled top-k/top-p or repetition penalty. Rollout already has logits for selection and need not repeat hidden-to-logprob projection. Sharing an op alone does not remove incremental-decode versus training-forward numerical differences; validate the contract before claiming that recorded logprobs eliminate an old-logprob forward.
Before implementation, feedback is welcome on the scope and interface. Proposed validation:
- Compare against dense full-vocabulary and existing vocab-parallel scoring for outputs, masked GRPO loss, nonuniform upstream gradients, hidden/head gradients and an optimizer update at TP=1 and TP=2, including uneven and empty vocabulary shards and targets on different ranks. Verify that hidden gradients are reduced exactly once.
- Check causal shifts, interleaved tool-output masks, all-masked batches and consistency between rollout and training distributions, including any enabled sampling transformations. Define masked output semantics and ensure zero scoring gradient at masked positions; TP peers must agree on scored positions and collective order.
- Measure full-step peak memory, token capacity and throughput against #1023's existing sequence-chunked path and a sequence-chunked vocab-parallel baseline; include projection and backward, not just the scoring kernel. Establish a memory bottleneck before claiming a benefit from vocabulary tiling.
- Start with resident head parameters and explicitly supported head layouts. Qualify ZeRO-3 parameter gather/release and backward recomputation separately before claiming support; TP correctness alone does not establish ZeRO-3 compatibility.
Open questions
- JSD / generalized JSD integration (TRL GKD or OPSD): the logits-based primitive is available in #8958; is there demand to integrate it into a trainer?
- Temperature and T² scaling: leave both to the caller, or add a
temperatureargument? - Reduction and mask: should the ops stay per-token, or also offer a masked-mean option?
- Student-support top-k with a tail bucket (TRL SDPO): this needs a vocab-parallel top-k. Is it worth adding?
- Teacher and student with different TP degrees or sharding: out of scope for now.
- Module placement:
deepspeed.sequencesits next to the existing vocab-parallel CE, or should this go under a futuredeepspeed.runtime.rlhf?
cc @delock @PKUWZP
I’d like to take PR-2 (OPSD integration) and coordinate with PR-1 to avoid overlap.
2. I’d like to take PR-2 (OPSD integration) and coordinate with PR-1 to avoid overlap.
Thanks for offering to help! I agree that you should lead PR-2. Maybe let’s wait half a day to see if any maintainers have additional feedback before you get started. Thanks again! @0z5a
Hi @0z5a #8791 has merged, and it's eager ops which maybe make E2E performance number not good. I have submitted another triton version ops #8838 to improve it. Please check and re-run when you available, thanks. And I also updated some optional next steps into plan, please feel free to comment or correct!
@jinyouzhi thanks — I re-ran the PR-2 OPSD benchmark (deepspeedai/DeepSpeedExamples#1019) with #8838. Your kernels close most of the gap. The rest came from #1019 itself, which I have fixed.
Setup. Same workload as the #1019 matrix:
- Qwen2.5-0.5B-Instruct student and Qwen2.5-1.5B-Instruct teacher, 2× H100, TP2/DP1, BF16, student ZeRO-0, GAS2, math SDPA.
- Replay of the same recorded rollouts, 5 warm-up and 30 measured updates, 3 runs per arm.
- Every arm was run on the same node in the same session.
- B gathers full logits and applies dense KL.
- C is the vocab-parallel route. Each C run checks which kernels actually ran.
Response tokens/s, mean of 3 runs, with the ratio to B in parentheses:
| B gathered | C, #8791 eager | C, #8838 | C, #8838 + #1019 update | |
|---|---|---|---|---|
| B2 / ISL 1024 | 32.45 | (0.93) | 32.26 (0.99) | 41.54 (1.28) |
| B4 / ISL 2048 | 344.5 | (0.84) | 307.2 (0.89) | 415.4 (1.21) |
| B4 / ISL 2048 peak allocated, GiB/rank | 29.83 | 30.00 | 30.00 | 25.94 |
The eager column comes from an earlier run on the same hardware type; only its ratio to B in that run is shown.
- #8838. It removes the eager cost: on B2 the vocab-parallel route catches up with B. In the profile, its kernels take 1.3% of GPU time.
- Remaining gap on long prompts: #1019. Its vocab-parallel route did not skip sequence chunks without response tokens. The intent was to keep the op's collectives matched across TP ranks. As a result, with a 2048-token prompt it fetched and computed all 9 chunks, where 1–2 are needed.
- The #1019 update (comment with details). It now skips them. The TP group first agrees on which chunks have response tokens, through one MAX all-reduce of a per-chunk flag. It also passes the shards to the op in bf16 instead of making fp32 copies.
- Numerics. Per-update losses, the post-training fixed-response loss and the FP32 optimizer masters are bitwise identical with and without the skipping. Passing bf16 instead of fp32 copies is not bitwise neutral with the current #8838 kernels: per-update losses drift by up to about 1e-2 over 35 updates. With the single-pass kernels suggested on #8838 it was bitwise neutral where I compared it: a 2-update run, and the op alone.
I also suggested a single-pass forward for entropy/KL on #8838 (PR against your branch). It makes the op about 1.3× faster in isolation, but at this model size the end-to-end effect is within noise, because the op is now about 0.1% of GPU time.
On the possible next steps:
- Item 3, fused-linear KL. With these numbers, speed alone does not justify it at this scale. Whether it pays off for memory I have not measured; that would need a breakdown of live activations, which I don't have yet.
- Teacher top-k cache. This looks like the most useful next step for OPSD. After the update, the largest single entry in the GPU profile is the pageable host-to-device copy that feeds the teacher cache to the loss. A top-k cache would shrink that copy and would not depend on the teacher's TP degree.
- Pinned copies. My guess is that the copy takes the pageable path because the cache's sequence chunks are non-contiguous slices of the pinned buffer. I have not verified that yet; I will look at it in PR-2.
These are finite small-model runs; they say nothing about convergence or 14B/32B / TP8 behaviour.
Hi @jinyouzhi, R-1 came up in #9037, so I fixed it there, though not with the _token_selector hook from the plan. The rollout sets gather_output=True on AutoTP's VocabParallelLinear heads only while generate() runs, so every decode path sees the full vocabulary, and training keeps the rank-local logits that vocab_parallel_logprobs expects.
I didn't use a hook because the static path and the continuous-batching prefill (for models without _supports_cache_class) decode with HF generate(), which bypasses _token_selector. Also, the repetition penalty and the recorded log-probs need the full vocabulary too, and a gather inside the head gets captured in the CUDA graph. With logits_to_keep=1, it gathers [B, V] per step, the same as a hook would. R-2 still fits: a vocab-parallel selector would just leave gather_output off.
The fix provide correct output, and throughput in bf16 is within ±1.1% of vocab_parallel_lm_head: false.
Does this approach work for you, or would you prefer the hook?
@anyadontfly Thanks for your reminder, I am happy to see your approach, it looks great.