Skip to content

feat(fsdp): add bounded sampler-support replay - #1914

Open
dyurk-lila wants to merge 9 commits into
NovaSky-AI:mainfrom
dyurk-lila:upstream/sample-support-fsdp
Open

feat(fsdp): add bounded sampler-support replay#1914
dyurk-lila wants to merge 9 commits into
NovaSky-AI:mainfrom
dyurk-lila:upstream/sample-support-fsdp

Conversation

@dyurk-lila

Copy link
Copy Markdown
Contributor

Note on the diff: This PR is part of a routed-expert-replay / sampler-support series and builds on the PRs below. GitHub can't show the intermediate branches here, so the diff is cumulative on top of main — the changes new to this PR sit on top of:

Reviewing in PR order (lowest number first) shows each incremental change cleanly.

Problem

The bounded sampler-support replay feature records vLLM's sampler support and replays it during training. The Megatron backend already applies this support-conditioned normalization; the FSDP policy and reference forwards must do the same, or their recomputed logprobs will represent a different distribution.

Implementation

  • Enable replay for trainer.strategy=fsdp while retaining the sampler-support constraints.
  • Pass support IDs and the response loss mask through policy training, policy recomputation, and reference forwards only when replay is enabled.
  • Right-align the response loss mask into the full token layout, then keep sampled IDs, support IDs, and the mask aligned through padding removal, next-token shifting, and Ulysses sequence-parallel slicing.
  • Reuse padding-removal indices rather than scanning the attention mask again.
  • Generalize Ulysses input partitioning to [batch, seq, ...] metadata and allow support padding to use -1, avoiding a second full validity-mask partition.
  • Share the backend-neutral aligned replay helper with Megatron for support normalization and synthetic-EOS handling.
  • Preserve feature-disabled behavior, including the existing FSDP reference-temperature path.

A loss-bearing EOS may be appended after vLLM returns, so that token intentionally has an empty support row. FSDP computes its ordinary full-vocabulary logprob explicitly; other loss-bearing rows must have recorded support. Loss-masked empty rows remain neutral.

The trainer representation stays the dense [batch, seq, support_width] contract.

Testing

  • pytest tests/backends/skyrl_train/distributed/test_ulysses_token_metadata.py tests/backends/skyrl_train/utils/test_torch_utils.py tests/backends/skyrl_train/workers/test_fsdp_dense_sample_support.py tests/train/test_config.py
  • Coverage includes FSDP value/gradient parity, optimizer updates, synthetic-EOS fallback, packed variable-length microbatch > 1, SP2 partition/gather parity, Ulysses padding, and strict metadata requirements.
  • Ruff, Black, and git diff --check pass.

@gemini-code-assist

Copy link
Copy Markdown
Contributor

Warning

Gemini encountered an error creating the review. You can try again by commenting /gemini review.

@dyurk-lila
dyurk-lila force-pushed the upstream/sample-support-fsdp branch from 20d9a75 to fa43c6e Compare July 17, 2026 23:14
dyurk-lila and others added 9 commits July 20, 2026 20:07
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>
…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>
Extend bounded sampler-support replay to the FSDP backend so policy and
reference forwards apply the same support-conditioned normalization as
Megatron, keeping recomputed logprobs on the same distribution.

- Enable replay for trainer.strategy=fsdp with the existing sampler-support
  constraints; thread support IDs and the response loss mask through policy
  training, policy recomputation, and reference forwards only when enabled.
- Right-align the response loss mask into the full token layout and keep
  sampled IDs, support IDs, and the mask aligned through padding removal,
  next-token shifting, and Ulysses SP slicing; reuse padding-removal indices.
- Generalize Ulysses input partitioning to [batch, seq, ...] metadata with a
  configurable padding value, avoiding a second validity-mask partition.
- Share the backend-neutral aligned replay helper for support normalization
  and synthetic-EOS handling; preserve feature-disabled behavior.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
@dyurk-lila
dyurk-lila force-pushed the upstream/sample-support-fsdp branch from fa43c6e to eefcccc Compare July 20, 2026 20:25
@erictang000 erictang000 self-assigned this Jul 20, 2026
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.

2 participants