refactor(generators): assemble routed-expert traces incrementally - #1912
Open
dyurk-lila wants to merge 6 commits into
Open
refactor(generators): assemble routed-expert traces incrementally#1912dyurk-lila wants to merge 6 commits into
dyurk-lila wants to merge 6 commits into
Conversation
This was referenced Jul 16, 2026
Contributor
|
Warning Gemini encountered an error creating the review. You can try again by commenting |
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>
dyurk-lila
force-pushed
the
upstream/r3-incremental-traces
branch
from
July 20, 2026 20:25
059c69f to
b6fb2a4
Compare
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.
Summary
TokenMetadataTracefor accumulating token-aligned NumPy metadata.RoutedExpertTracefor routed-expert (R3) multi-turn alignment with masked terminal gaps.routed_experts_prompt_start(s)) through the remote inference client andInferenceEngineInput.SkyRLGymGenerator.Why
The multi-turn generator sends the cumulative prompt on every inference request. Routed-expert generation previously returned routing rows for that full prefix on every turn and kept only the latest full tensor. Passing the number of already-captured rows to the engine makes routed-expert response metadata incremental: total route transfer becomes O(N) instead of O(N^2) over a growing trajectory. Full-prompt request traffic is unchanged and continues to benefit from sticky routing and prefix caching.
RoutedExpertTracerecords each generation's routes and finalizes a full per-token routed-expert array, padding the loss-masked terminal gap so the result stays aligned to the token sequence. The genericTokenMetadataTraceunderneath is a standalone token-aligned accumulator reusable beyond R3.Testing
uv run --isolated --extra dev --extra fsdp pytest tests/backends/skyrl_train/inference_servers/test_remote_inference_client.py tests/train/generators/test_skyrl_gym_generator.py tests/utils/test_token_metadata.py— all pass (99 passed), including new coverage for incremental trace assembly, chunked/independent-schema traces, invalid-chunk rejection, and multi-turn suffix / terminal-gap padding.