feat(sample-support): report the policy entropy over the recorded support - #2086
feat(sample-support): report the policy entropy over the recorded support#2086dyurk-lila wants to merge 23 commits into
Conversation
Extract the single-request HTTP generation path out of RemoteInferenceClient into a standalone RemoteGenerateClient plus a RemoteGenerateResult dataclass, so routed-expert results can be obtained without constructing the full inference/control-plane client. RemoteInferenceClient now owns an internal RemoteGenerateClient and delegates session management, _post, and _generate_single to it. Endpoint routing, retry/backoff, cache_salt handling, serialization, and lifecycle behavior are unchanged.
For multi-turn rollouts, build routed-expert (R3) trace data incrementally as the conversation grows instead of re-gathering the whole conversation's routes on every turn. - Add `routed_experts_prompt_starts` to `InferenceEngineInput` and thread a per-request `routed_experts_prompt_start` through `RemoteInferenceClient` and `RemoteInferenceGenerator.generate()`, forwarded as a sampling param so the engine only returns routes for the newly generated suffix. - Introduce `TokenMetadataTrace` (token-aligned array accumulator) and `RoutedExpertTrace`, which records each generation's routes and finalizes a full per-token routed-expert array with loss-mask-aware terminal padding. - Track a `RoutedExpertTrace` on `AgentLoopState` and record routes per turn, replacing the previous whole-conversation re-gather in `SkyRLGymGenerator.agent_loop`. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
There was a problem hiding this comment.
Code Review
This pull request introduces sample support replay to renormalize policy logprobs over the sampler's recorded bounded support, adding a new PackedTensor utility to manage ragged token-aligned batch fields efficiently. It integrates this capability across both Megatron and FSDP training pipelines, optimizes CPU thread pool sizing using cgroup quotas, and implements zero-copy serialization for side-channel arrays. Feedback on the changes highlights a potential AttributeError in the vLLM server actor if logprobs are not returned during sample-support capture, suggesting a guard to handle None values gracefully.
| content, support_ids = _sample_support_from_flat_logprobs( | ||
| resp.logprobs, | ||
| sampling_params_dict["top_k"], | ||
| ) |
There was a problem hiding this comment.
If resp.logprobs is None (which can happen in some edge cases or error states in vLLM), calling _sample_support_from_flat_logprobs will raise an AttributeError when trying to access logprobs.token_ids. Consider adding a guard to check if resp.logprobs is None and raise a descriptive error or handle it gracefully.
if resp.logprobs is None:
raise HTTPException(
status_code=500,
detail="vLLM failed to return logprobs for sample-support capture."
)
content, support_ids = _sample_support_from_flat_logprobs(
resp.logprobs,
sampling_params_dict["top_k"],
)
Problem
Support replay makes policy log-probabilities conditional on the recorded sampler support, but policy entropy still uses the full vocabulary. Besides reporting a different distribution, the full-vocabulary entropy path retains most of the computation and memory that bounded replay avoids—especially when the fused LM-head path otherwise projects only selected candidates.
This PR computes entropy from the same support scores used for replay on both Megatron and FSDP.
Entropy computation
For support logits
l_i, shifted by their row maximum, the scorer uses:The exponentials and denominator
Zalready exist for support-conditioned log-probabilities. Under tensor parallelism, the entropy numerator is added as a third row to the existing combined SUM reduction, so entropy requires no additional collective.A singleton support has exactly zero entropy and zero entropy gradient. Trailing
-1members do not contribute.Metric and loss modes
Entropy calculation and gradient tracking are separate controls:
The fused LM-head scorer reuses the selected candidate projections from replay. It therefore supports differentiable entropy without materializing full-vocabulary logits.
Masking and layout
SampleSupportScores.valid_maskidentifies positions backed by a recorded support row. Megatron and FSDP carry that mask back to canonical batch coordinates alongside the entropy values, including packed Megatron layouts and Ulysses gather/unpadding.The final entropy reduction intersects this mask with the response loss mask. A synthetic EOS still receives its full-vocabulary log-probability fallback, but it is excluded from support-conditioned entropy because no rollout support exists for that token.
When sample-support replay is disabled, both backends retain their existing full-vocabulary entropy paths.
Testing
Note
High Risk
Changes how training logprobs and entropy (including entropy-loss gradients) are computed, plus inference capture and packed per-token batch transport. Incorrect support alignment would silently bias RL updates.
Overview
When
enable_sample_support_replayis on, policy entropy now matches the support-conditioned logprobs instead of the full vocabulary. Metric-only entropy detaches the support distribution; entropy-loss keeps gradients through it. Tensor-parallel entropy piggybacks on the existing SUM reduction. Synthetic EOS still uses a full-vocab logprob fallback but is excluded from support entropy viavalid_mask.Megatron and FSDP both reduce entropy with that mask intersected with the response loss mask. The fused LM-head path can now take a differentiable entropy term because it reuses selected-candidate projections rather than materializing vocab logits. Full-vocab entropy is unchanged when replay is off.
The same diff also lands the rest of the sample-support stack: vLLM capture of bounded top-k IDs, packed HTTP/trainer transport (
PackedTensor), R3 route packing, and support-conditioned scoring. R3 remains refused with step-wise / misaligned generators.Reviewed by Cursor Bugbot for commit 3308bd1. Bugbot is set up for automated code reviews on this repo. Configure here.