feat(megatron): add bounded sampler-support replay#1913
Open
dyurk-lila wants to merge 7 commits into
Open
Conversation
Fix routed-expert replay (R3) correctness for RL training and introduce a shared token-metadata layout that later routed-expert and sampler-support work builds on. - Scope global RouterReplay state to one Megatron pipeline schedule so a forward-only logprob pass can no longer leak backward replay state into the next training schedule (clear before the schedule and in `finally`). - Keep `rollout_expert_indices` ragged and treat its length as the captured-prefix length. Derive a `router_padding_mask` after left padding that marks alignment padding and the uncaptured trajectory suffix, and carry it through the training data, replay experiences, microbatch padding, and the Megatron model call. - Build one `TokenMetadataLayout` per microbatch and apply it to both routes and the padding mask. Generic construction, alignment, next-token shifting, and packed-output restoration live in `skyrl/utils/token_metadata.py`. - Pass Megatron's `padding_mask` through the model and apply a narrow compatibility shim so `[tokens]` masks broadcast over experts in expert-bias accounting. - Slice every per-trajectory generator field generically during dynamic-sampling replacement and filtering so route metadata stays attached to its trajectory. Synthetic padding rows use distinct dummy experts `[0, ..., topk - 1]`; the mask excludes them from expert-bias accounting while preserving Megatron's dropless `tokens * topk` dispatcher invariant.
Store routed-expert (R3) generation data as compact NumPy arrays instead of large nested Python lists, and send it over the network base64-encoded alongside its shape and dtype. Expert IDs are compacted to the smallest safe uint8/int16/int32 dtype, vLLM responses and client responses use orjson, and preprocessing accepts the decoded NumPy route arrays directly. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Under pipeline parallelism each rank replays only its local router layers, but the Megatron worker eagerly expanded the full global-layer routed-expert tensor to int32 before replay setup, allocating a large device temporary for unused layers. Keep routed-expert IDs in their compact dtype through whole-batch device movement, index_select the current PP stage's router layers before metadata alignment, and perform the single int32 conversion inside _split_replay_indices so only the bounded PP-local slice is materialized as int32. Also validate the 4D replay-indices shape up front. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Extract the single-request HTTP generation path out of RemoteInferenceClient into a standalone RemoteInferenceGenerator and a RemoteGenerateResult dataclass. RemoteInferenceClient now owns an internal generator and delegates session management, _post, and _generate_single to it. This is a pure refactor with no functionality change: endpoint routing, retry/backoff, cache_salt handling, serialization, and lifecycle behavior are all preserved. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
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>
Add the core of bounded sampler-support replay across data plumbing, inference capture, and the Megatron dense-path trainer. - Inference: /skyrl/v1/generate gains a return_sample_support flag that requests flat_logprobs from vLLM; the fixed-width rows are decoded into per-token support IDs and surfaced through RemoteInferenceGenerator, RemoteGenerateResult, and InferenceEngineOutput.rollout_sample_support. - Data plumbing: support rows ride the shared TokenMetadataTrace through multi-turn accumulation, dynamic filtering, truncation, replay buffering, and microbatch padding; preprocessing validates support width, trailing -1 padding, int32 vocab IDs, and presence of every loss-bearing token. - Config: reject sampler settings whose rollout distribution cannot be replayed exactly (temperature > 0, top_k > 1, repetition penalty 1.0, no arbitrary additional_kwargs). - Megatron: renormalize sampled-token scores over recorded support with fixed-shape gathers; fused LM-head path projects only selected candidate pairs and chunks by logprobs_chunk_size; controller-packed rows reuse TokenMetadataLayout. New utils/sample_support_replay.py holds the core. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This was referenced Jul 16, 2026
Contributor
|
Warning Gemini encountered an error creating the review. You can try again by commenting |
…om its top-k support (NovaSky-AI#66) * fix(sample-support): repair rows where the sampled token is absent from its top-k support vLLM's approximate top-k/top-p pivot can let a sampled survivor rank just beyond top_k, so it is missing from the captured support row and the downstream sample-support invariant hard-crashes the run. When the sampled id is absent, overwrite the weakest support member with it, preserving width==top_k, single-occurrence, and trailing padding. Emit one aggregated warning per call. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * style(sample-support): apply black formatting to regression test --------- Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
This adds the core of bounded sampler-support replay: the data plumbing, inference capture contract, and Megatron dense-path trainer support. It builds on the shared incremental token-metadata trace.
Problem
With bounded sampling, rollout probabilities are normalized over the candidates retained by vLLM's processed sampler rather than the full vocabulary. Megatron currently recomputes full-vocabulary log-probabilities, so the trainer cannot reproduce the rollout distribution for importance ratios or KL terms.
vLLM capture contract
When capture is enabled, the request asks vLLM for
flat_logprobswithlogprobs=top_k. Each token contributes one fixed row:The first column supplies the existing sampled-token logprob. The remaining columns become replay support IDs in one NumPy reshape; candidates whose processed logprob is
-infare stored as-1. This supports top-k, top-p, and min-p filtering without per-token searches, deduplication, or a second dict-format path.Configuration rejects combinations whose rollout distribution cannot be replayed exactly: capture must be enabled,
temperature > 0,top_k > 1, repetition penalty must remain1.0, and arbitrary sampleradditional_kwargsare unsupported. Replay is Megatron-only in this change; a follow-up adds the FSDP path.Generator and incremental metadata contract
The
RemoteInferenceGeneratorowns the single-request HTTP boundary. This extends that typed interface:RemoteInferenceGenerator.generate(return_sample_support=True)selects/skyrl/v1/generateand adds the boolean capture field;RemoteGenerateResult.sample_supportcarries the decoded support rows alongside routed experts and token logprobs;RemoteInferenceClientbatches those results intoInferenceEngineOutput.rollout_sample_support.Multi-turn accumulation follows the shared
TokenMetadataTrace, the same backbone used by incremental routed-expert capture. Each generation contributes one contiguous int32 NumPy chunk. Synthetic EOS and observation positions contribute fixed-width-1rows. The trace is finalized once per trajectory and converted to the list response only at the generator-output boundary, keeping routed-expert and sample-support alignment on the same lifecycle.Metadata ownership
Support rows follow response tokens through stepwise merging, dynamic replacement/filtering, truncation, replay buffering, and microbatch padding. Preprocessing validates one fixed support width, trailing
-1padding, int32 vocab IDs, and presence of every loss-bearing sampled token.An EOS may be appended after vLLM returns, so vLLM cannot have captured support for that token. An empty loss-bearing row is accepted only for that synthetic EOS; every other missing loss-bearing support row is rejected. At most one such EOS is allowed per trajectory, matching the generator contract.
Megatron replay
Megatron renormalizes sampled-token scores over the recorded support with fixed-shape gathers. TP uses one MAX reduction and one combined SUM reduction for the denominator and sampled score. The fused LM-head path projects only selected candidate pairs and chunks by
logprobs_chunk_size, bounding the temporary[candidate pairs, hidden]allocation.Synthetic-EOS full-vocabulary fallback also uses fixed capacity: one device-side candidate slot per trajectory, including packed CP-local segments. Unused slots are masked after computation, avoiding host synchronization, boolean compaction, ragged TP shapes, and per-microbatch CPU-to-GPU length transfer.
For ordinary unpacked RL, logits and targets use direct next-token slicing. For controller-packed RL microbatches, sample support and routed-expert replay share the
TokenMetadataLayout, built once from the attention mask, applying the same per-segment padding, next-token shift, CP front/back sharding, and final scatter into canonical batch positions. Controller-packed multi-subsequence/SFT metadata is rejected rather than adding a second packing model.Results
Bounded sampler-support replay lets top-$p$ / top-$k$ sampling be used during rollouts without breaking trainer/inference alignment. These curves come from an RL run training GLM-4.7-Flash (an MoE model) on the easy split of NVIDIA's open Nemotron-Terminal-Synthetic-Tasks dataset — a sandboxed terminal/coding agent environment. We compare routed-expert replay alone against routed-expert replay plus support-set replay with top-$k$=20, top-$p$=0.95 sampling. Training reward tracks closely between the two arms, while the top-$p$ arm retains substantially more policy entropy instead of collapsing. Curves are lightly EMA-smoothed over the raw per-step values; both arms are clipped to the step range they share (11–151).
Reward is nearly indistinguishable between the arms, but by the end of training the top-$p$ arm holds entropy around ~0.14 while the R3-only arm collapses to ~0.05.
That retained entropy shows up as sampling diversity at evaluation. The two arms are essentially tied on Pass@1, but the higher-entropy top-$p$ arm produces more diverse completions and pulls ahead at higher$k$ :
So preserving support during rollouts trades a negligible Pass@1 difference for a consistent Pass@4 / Pass@8 gain — the extra entropy widens coverage exactly where multi-sample metrics benefit.
Testing
pytest tests/backends/skyrl_train/utils/test_sample_support_replay.py tests/backends/skyrl_train/inference_servers/test_vllm_sample_support.py tests/backends/skyrl_train/inference_servers/test_build_vllm_cli_args.py tests/backends/skyrl_train/inference_servers/test_remote_inference_client.py tests/backends/skyrl_train/test_token_based_batching_utils.py tests/backends/skyrl_train/test_train_batch.py tests/train/dataset/test_sample_support_preprocess.py tests/train/generators/test_generator_output_utils.py tests/train/generators/test_skyrl_gym_generator.py tests/train/test_config.py tests/train/test_trainer.py— all passing (synthetic-EOS value/gradient parity, no-EOS rows, packed CP segments, fused chunk bounds, and preprocessing invariants).