verl icon indicating copy to clipboard operation
verl copied to clipboard

[RFC] Selected-token log-probabilities from the actor engine, including fused kernels

Open eteluna opened this issue 3 months ago • 5 comments

*Updated 2026-10-03: scope narrowed. The objective composer, plugin loading and reduction schema below are withdrawn; verl-genrank composes its objective through TrainingWorker.set_loss_fn. The remaining request is one default-off engine output, model_output["selected_token_logprobs"], including the fused-kernel path, computed without a kernel change. Proposal and H200 measurements: comment. Happy to open it as a draft PR here if the direction is acceptable.

Updated 2026-09-09: f894f21e fixes an uninitialized selected_rmpad in the existing fused/remove-padding path when the selected-token projection is disabled. Four CPU regression cases were added; the two affected cases fail on the parent commit, and the related suite now passes all 66 tests. The interface and enabled-projection fused-kernel restriction are unchanged.

Edited 2026-09-03: (1) the open process_logits plugin callback was replaced by an engine-owned, configuration-declared projection, details in the comment below; (2) motivation moved first with the generative-ranking use case, and the projection's cost stated explicitly.

Motivation

A custom reward only changes the advantages of the sampled tokens. The policy gradient differentiates through the log-probabilities of what was sampled, but a detached reward cannot directly optimize a function of the current full output distribution, such as the probability mass the policy puts on a set of label tokens. Calibration of that mass, a supervised term on part of the batch, an auxiliary-prediction loss all need a gradient through those outputs. Entropy and KL already follow the pattern (derive a term from actor outputs, normalize it, weight it, add it, log it), but they are hard-coded; on-policy distillation is a third instance implemented as a dedicated wrapper.

The use case this comes from is generative ranking: a decoder LM scores each candidate by emitting a small graded score alphabet (digits, yes/no), and the ranking score served downstream is the distribution over those tokens, not the argmax. RL with a ranking reward optimizes the order within a query, but nothing pins the absolute probabilities that serving reads, and they drift across queries. A calibration term on the current-policy mass of the score tokens fixes that; we run such a model in production and train it today through install-time patches on ppo_loss and the FSDP engine. The same mechanism covers any objective that needs a gradient through the current policy's outputs rather than a reward: calibration of label tokens, a supervised term on part of the batch, an auxiliary prediction head's loss. We think enough users will hit this that it belongs in verl as an extension point rather than in each user's patches.

A public instance of the same need: any task whose answer is a small fixed token set, such as multiple-choice letters, yes/no, class labels or graded scores, where the reward is computed from the distribution over those tokens rather than from the sampled token alone. Public models already work this way: Qwen3-Reranker scores a query-document pair as log_softmax(logits[-1][[no, yes]])[1].exp(), the probability of yes over no at the last position. RL fine-tuning of such a model needs that probability to stay calibrated, and a reward on the sampled token cannot enforce it. GRPO's group-relative advantages only constrain the ordering within a prompt; the absolute probability the policy assigns to a label token stays unconstrained across prompts and drifts, so downstream consumers that read that probability as a score lose calibration. A BCE term on the current-policy mass of the label tokens fixes that.

Summary

verl accepts one actor loss callable and lets you select a policy-gradient formulation through the policy-loss registry. It has no way to add an independent differentiable term to that loss without patching ppo_loss and the engine. This RFC proposes an opt-in, config-driven composition layer:

L_total = L_policy (pg + entropy + KL, unchanged) + sum_i weight_i * L_i

Objectives are small user classes loaded from a file, like custom_reward_function. They only read model_output; anything that has to come from the full logits is produced by the engine from configuration. verl owns loading, execution order, global mini-batch normalization, coefficient application, metric namespacing and validation. An empty list (the default) leaves everything exactly as it is today.

actor_rollout_ref:
  actor:
    selected_token_logprobs:
      token_ids: [15, 16, 17, 18, 19]   # engine emits model_output["selected_token_logprobs"]
    auxiliary_objectives:
      - name: label_calibration
        path: /workspace/objectives.py
        factory: build_objective
        weight: 0.05
        kwargs: {positive_token_ids: [17, 18, 19], normalize_over: token_set}

Contract

Per objective, three static declarations and two callbacks:

When Contract
required_batch_keys, required_model_output_keys, stat_names validated at start-up required_model_output_keys is checked against what the configured forward emits (log_probs, entropy if enabled, selected_token_logprobs if configured), so a missing flag fails at init with the flag named, not on the first forward.
prepare_batch(data) -> {stat: float} once per mini-batch, before micro-batch splitting returns exactly stat_names. verl packs every objective's scalars in the static (objective, stat) order and SUM-reduces once over DP, so ranks never disagree on shape or slot. Plugins never issue collectives.
compute(model_output, data, context) -> ActorObjectiveResult(loss_sum, normalizer, metrics) per micro-batch, after the base loss loss_sum is the unweighted sum over applicable elements, grad-connected; normalizer names one of stat_names.

Logits access is declarative, not a callback: actor.selected_token_logprobs.token_ids makes the engine emit model_output["selected_token_logprobs"], the full-vocabulary log-softmax (temperature- scaled like log_probs) at those ids, laid out like log_probs with a trailing dimension of M. It is a row-wise function of the same logits log_probs comes from, so it is correct under remove-padding, packed padding and Ulysses sequence parallelism, it has a fixed schema, and the full logits never leave the engine.

It is not free just because it returns M columns. The full-vocabulary normalizer is one extra pass over the [tokens, vocab] logits, the same order of work as the cross-entropy itself; and because its backward reads the logits, the fused cross-entropy can no longer run its backward in place, which keeps one extra logits-sized buffer alive through backward (about 5 GB for a 150k vocabulary and 16k packed tokens in bf16). Fused kernels never materialize logits, so configuring both fails at init today. The way to make it cheap is a Liger-style fused linear-plus-cross-entropy kernel that emits the selected columns and folds their gradient into its chunked backward; that also lifts the fused-kernel restriction (PR split, item 3). We are measuring the eager cost against a no-projection control on real training data and will post the step-time and peak-memory numbers here.

Per micro-batch verl adds weight * dp_size * loss_sum / N_global, which sums over gradient-accumulation steps and averages over ranks to the global mini-batch mean, the same trick ppo_loss uses with batch_num_tokens. This assumes objectives are additive over samples; cross-sample terms are out of scope. Zero global normalizer: active=0, a differentiable zero, no division. weight: 0 skips the objective; metrics_only: true runs it under no_grad for ablation metrics. Metrics: actor/aux/<name>/{loss, weighted_loss, normalizer, active} plus namespaced plugin metrics. Objectives run only on the gradient-enabled actor update. The composer is built after the actor process group exists and refuses to start if the resolved configuration (entries, kwargs, plugin file hash, API version) differs across ranks.

Scope

  • In: stateless, sample-additive objectives; canonical outputs (log_probs, entropy) plus the declarative selected-token projection; FSDP/FSDP2 first, other backends reject a non-empty list.
  • Out: rewards/advantages, producing new batch fields, extra forwards, new parameters, optimizer groups, checkpoint entries, rollout weight sync. Sidecar heads are a separate RFC. No plugin callback receives the logits.
  • Compatibility: the on-policy distillation wrapper keeps working; the composer delegates its logits-processor calls unchanged. An empty objective list returns the original loss callable. With the selected-token projection disabled, CPU regression tests cover existing fused output processing with remove-padding and entropy independently enabled/disabled, checking output values, jagged offsets and gradients. These tests do not execute GPU fused kernels or distributed SP.

Decision requested

  1. Is a separate composition layer (additive objectives) next to the policy-loss registry (which selects one surrogate) the right shape, or should this live inside the registry?
  2. Is an engine-owned, declarative projection the right V1 answer for logits access, with a generic logits-processing stage deferred until its sequence-parallel layout and fused-kernel interactions are specified? (The first prototype had an open process_logits callback; review feedback on SP alignment and capability detection led to replacing it.)
  3. weight: 0 skips the objective entirely and metrics_only: true is the explicit way to keep ablation metrics. Any objection to that split?

PR split

  1. Config, protocol, loader, composer, static stats, start-up validation, the selected-token projection, FSDP integration, tests, docs (the prototype).
  2. Megatron/VeOmni/TorchTitan parity behind capability checks, with the reduction semantics provided by the backend rather than fixed as dp_size / N in the composer (Megatron's micro-batch and CP scaling differ, see #6609 and #5983).
  3. A fused linear-plus-cross-entropy kernel (Liger-style) that emits the selected columns inside its chunked pass, removing the extra logits pass and the extra buffer and lifting the fused-kernel restriction.
  4. A generic logits-processing stage once the SP token layout, fused-kernel coexistence and real distributed tests exist; possible follow-up if maintainers want one path: migrate the on-policy distillation logits processor onto it.
  5. Examples and benchmarks (disabled path under 1% is the regression-review threshold; framework overhead reported separately from objective compute).

References

  • verl/workers/utils/losses.py (ppo_loss), verl/workers/engine/fsdp/transformer_impl.py (forward_backward_batch, prepare_model_outputs), verl/trainer/distillation/losses.py (distillation_ppo_loss as logits processor), verl/workers/engine_workers.py (loss selection).
  • #1560 (engine interface), #7200 (global micro-batch normalization), #6696 (autograd graph retention), #6519 (no-grad entropy/KL at zero coefficient), #6609 / #5983 (Megatron loss scaling).

eteluna avatar Sep 03 '26 04:09 eteluna

cc @vermouth1992 @zhtmike @wuxibin89: this touches losses.py, the FSDP engine's prepare_model_outputs and the loss selection in engine_workers.py, where you have the most recent context. Happy to adjust the shape before opening a PR here.

eteluna avatar Sep 03 '26 04:09 eteluna

Revised the prototype (https://github.com/eteluna/verl/pull/1) after a review pass; the issue body above is updated to match. What changed and why:

  1. No plugin callback sees the logits. The open process_logits hook is gone. Instead actor.selected_token_logprobs.token_ids makes the engine emit model_output["selected_token_logprobs"], the full-vocab log-softmax at fixed ids, laid out like log_probs. Row-wise on the same temperature-scaled logits, so it is correct under remove-padding, packed padding and Ulysses SP; fixed schema; fused kernels reject it at init. (The callback had two real problems: a canonical-only objective was mis-detected as a logits consumer, and under SP the callback received shard-local logits next to a full micro-batch.)
  2. Static reduction schema. Objectives declare stat_names; prepare_batch must return exactly those, and the single SUM over DP packs them in configuration order, so ranks cannot disagree on shape or slot.
  3. Start-up validation of requirements. required_model_output_keys is checked against what the configured forward will emit; asking for entropy without calculate_entropy fails at init with the flag named.
  4. Reliable cross-rank handshake. The composer is built after the actor process group exists (not before, where actor-only roles skipped the check); the digest covers kwargs, the plugin file hash and an API version, and a mismatch is fatal.
  5. weight: 0 skips; metrics_only: true for ablation metrics under no_grad, so a zero coefficient no longer retains the graph or triggers the reduction.
  6. Calibration example now uses BCE-with-logits (z = lse(positive) - lse(negative), no clamp) with normalize_over: token_set | vocab, so the yes/no-reranker reading from the motivation and the raw-vocabulary-mass reading are both expressible.

Still open and deliberately not in this PR: backend-provided reduction semantics for Megatron (PR 2), a generic logits stage (PR 3).

eteluna avatar Sep 03 '26 05:09 eteluna

Numbers from the prototype on real training data, as promised in the cost paragraph.

Setup. Qwen3-0.6B, GRPO/GSPO, 16×H200 (2 nodes), remove-padding on, fused kernels off, flash-attn cross-entropy, 152k vocabulary, ~6.8k packed tokens per micro-batch (2 sequences of ~3.4k tokens). 40 steps each. Objective: BCE calibration of the mass on 2 of 5 selected digit tokens (normalize_over: vocab), weight 0.05, targets at ~40 positions per sequence. Control: same stack and data, no projection, no objective.

The objective works end to end. active=1 on every step, global normalizer ≈ 5k cells per mini-batch, BCE 0.40 → 0.14 over 40 steps, mean positive mass settling near the base rate, no NaN, old_log_prob and generation timings unchanged (the projection runs only on the update pass).

The cost, steps 2–39 mean:

control with projection + objective delta
update_actor time 5.40 s 7.28 s +35 %
end-to-end step time 15.5 s 19.1 s +23 %
actor peak memory allocated 7.5 GB 35.7 GB +28 GB per GPU
actor peak memory reserved 9.3 GB 41.1 GB +32 GB

So "a few columns" is the wrong mental model, as internal review of this RFC pointed out. With a full-vocab fp32 tensor at ~4 GB here, the eager projection materializes several of them: the logits kept alive for backward (in-place CE disabled), the out-of-place CE gradient, the logsumexp backward temporary, and the index_select backward, which scatters into a dense zeros-like of the logits.

What we will do about it, in order:

  1. Eager mitigation, now in the draft PR (commit 145354c0): when the projection is configured, one fp32 log_softmax is computed and gathered at [label, selected ids...], so log_probs and the selected columns come from the same pass; only the logits are saved and the softmax is recomputed in backward (_LogSoftmaxSparseGather). Re-run of the same arm, same data, same recipe:

    steps 2–39 mean control eager projection (before) shared log-softmax (after)
    update_actor time 5.40 s 7.28 s (+35 %) 6.30 s (+17 %)
    end-to-end step time 15.5 s 19.1 s (+23 %) 17.3 s (+12 %)
    actor peak memory allocated 7.5 GB 35.7 GB (+28 GB) 20.8 GB (+13 GB)
    actor peak memory reserved 9.3 GB 41.1 GB 22.4 GB

    The objective metrics are identical to the third decimal between the two runs (BCE 0.40 → 0.14, same normalizer, same grad norm), so this is the same objective at half the extra memory. The remaining ~13 GB is about three full-vocab tensors (bf16 logits kept for backward, the fp32 softmax recomputed in backward, the fp32 gradient), which is the floor for any eager implementation that materialises the full-vocab gradient once.

  2. The fused Liger-style kernel that emits the selected columns inside the chunked cross-entropy (PR split item 3), which removes that floor and lifts the fused-kernel restriction. Help there is very welcome.

eteluna avatar Sep 04 '26 03:09 eteluna

@eteluna Thanks for publishing the measured projection cost and inviting help with the fused kernel. I would like to contribute only that bounded kernel slice, without duplicating your objective composer, eager projection, or backend-parity work.

Before implementing, could you and the engine maintainers confirm the ownership and integration contract below?

Proposed boundary

  • One chunked/fused linear + log-softmax/gather operation that produces both the sampled/label-token log-probabilities and the configured selected-token columns. Both outputs retain the full-vocabulary normalizer and the engine's temperature semantics; this is not a softmax over the selected subset.
  • Logical inputs: hidden states [T, H], LM-head weight [V, H], labels [T], fixed selected IDs [M], and temperature. Logical outputs: ordinary log-probabilities [T] and selected-token log-probabilities [T, M]. The engine remains responsible for padding/packing/SP layout restoration and for exposing model_output["selected_token_logprobs"] in the existing layout.
  • Backward must combine arbitrary upstream gradients from both outputs and compute the corresponding hidden-state/LM-head gradients without materializing a full [T, V] gradient. FP32 accumulation/output semantics should match the shared eager reference in 145354c0; any dtype differences must be explicit and tested.
  • First integration: CUDA and the FSDP/FSDP2 path. No objective API changes, no generic logits callbacks, no new loss normalization, and no Megatron/NPU/ROCm parity in this slice. Unsupported LM-head variants would be explicitly bounded rather than silently approximated.

Questions to settle before coding

  1. Is the fused-kernel slice still available for collaboration, or is someone already implementing it outside the linked prototype? If available, may I take this slice while your PR remains the owner of the framework-level interface?
  2. Where should the reusable kernel live: an extension to the existing Liger kernel path with a small verl adapter, or initially under verl's existing fused-kernel utilities? I would like to follow the preferred ownership/dependency policy rather than introduce a parallel backend or a new mandatory dependency.
  3. Does the logical contract above match the intended interface? In particular, which existing fused backend/LM-head variants and output dtypes should be the first acceptance target, and should the integration be stacked on the prototype or wait for its upstream API to settle?

Validation plan

  • Compare both outputs and hidden-state/weight gradients with a dense PyTorch reference for FP32/BF16, temperature, repeated selected IDs, selected-ID/label overlap, and boundary vocabulary/chunk sizes; test unsupported inputs explicitly.
  • Check gradient accumulation and the engine's padded/remove-padding layouts; add two-rank SP coverage before claiming SP compatibility.
  • Measure peak allocated/reserved memory and update time against the shared eager implementation under matched shapes and settings, then run a short controlled FSDP training comparison. Report kernel measurements separately from end-to-end training evidence.

This is a scope-confirmation proposal, not a claim that maintainers have accepted the interface or assigned the work.

WenzheWang avatar Sep 06 '26 13:09 WenzheWang

Update: narrowing this RFC to one engine output

GenRank now lives in the verl-genrank sub-project. It composes its label objective through the existing TrainingWorker.set_loss_fn and a registered engine subclass, so the objective composer, plugin loading and reduction schema proposed here are no longer needed in verl. I'm withdrawing those parts.

A sub-project cannot read selected-token log-probabilities when use_fused_kernels=True: the fused forward never materializes logits, and the LM-head weight is only used inside the patched model forward. That is the remaining request.

Proposal. One optional output, off by default:

  • actor.selected_token_logprobs.token_ids: [...] makes the engine return model_output["selected_token_logprobs"]: full-vocabulary log-probabilities at those ids for every position, in the same layout as log_probs (dense, remove-padding, Ulysses SP), with the engine's temperature. Consumers that need probabilities over the selected set can renormalize them; the shared normalizer cancels.
  • Fused path, no kernel change: every backend already returns log p(label). With z = h·W[ids]ᵀ / temperature (one [T, H] × [H, M] matmul), log p(id) = log p(label) + z_id − z_label, because the log-sum-exp cancels. Autograd handles the backward and nothing of size [T, V] is materialized. z has to be rounded the way each backend rounds its logits, and positions with an ignored label are masked.
  • Non-fused path: gather the M columns from the logits the engine already holds and apply the same identity, so the in-place cross-entropy backward stays enabled.
  • First model patch: dense_common. Other patches raise a clear error when the option is set.

Measured on H200 (op-level forward+backward of log-probs plus the selected output; bf16, H=1024, V=151,936, M=5). Baseline is the eager reference from the prototype (fp32 log-softmax + gather, 145354c0).

Extra peak memory (GB):

tokens eager reference torch + identity triton + identity Liger + identity
6.8k 9.62 2.35 (−7.28) 0.84 (−8.78) 0.90 (−8.73)
16k 23.19 2.38 (−20.80) 1.22 (−21.97) 0.93 (−22.25)

Forward+backward time (ms):

tokens eager reference torch + identity triton + identity Liger + identity
6.8k 28.0 59.0 (+31.0) 33.7 (+5.7) 21.1 (−6.9)
16k 67.5 139.7 (+72.2) 82.2 (+14.7) 46.3 (−21.3)

The selected output adds about 0.3 GB and 1 ms to the same backend's label-only path (triton 0.54 → 0.84 GB, 32.6 → 33.7 ms; Liger 0.59 → 0.90 GB, 20.1 → 21.1 ms). Max abs error of the selected log-probabilities against float64 at 6.8k tokens: 3.9e-3 for the eager reference and the torch backend (bf16 logits), 4.0e-4 for Liger, 3.0e-6 for triton. For scale, the eager prototype added 28 GB peak per GPU end to end (numbers above in this thread).

Tests. CPU: values and gradients of each layout against a float64 full log-softmax reference, masking and temperature. GPU: the same comparison on H200 for the triton and Liger backends.

@wuxibin89 @vermouth1992 does this shape work for the engine? If so I'll open a PR against main.

eteluna avatar Oct 03 '26 06:10 eteluna