Skip to content

perf(token-capture): stage routed experts without codec round trips - #4345

Merged
ZhiyuLi-Nvidia merged 15 commits into
NVIDIA-NeMo:mainfrom
zyzhou5:router-capture-no-codec
Nov 4, 2026
Merged

ZhiyuLi-Nvidia merged 15 commits into
NVIDIA-NeMo:mainfrom
zyzhou5:router-capture-no-codec

Conversation

@zyzhou5

@zyzhou5 zyzhou5 commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor

What does this PR do?

Removes router-index codec round trips from token capture: the vLLM generation worker actor keeps routes as tensors, slices each captured token delta, and passes it through Gym's existing attachment API to TQTokenSink in the same actor. Route verification in the finalizer or policy worker checks tensor metadata and its checksum without re-encoding routes. Captured routes stay out of HTTP responses; the non-capture path keeps its existing codec behavior.

#4517 is merged into main and supplies the Gym update. This PR has no Gym pin or dependency lockfile changes.

Validation

Paired OCI-AGA SWE training with Nano-30B BF16: 24 GPUs per run, five updates, token capture and R3 enabled, routes deferred to policy workers, TransferQueue SimpleStorage, and NCCL Socket.

No regression of perf and correctness is observed.

The linked E2E runs predate the latest main merge (26d52d998). The conflict resolution preserves main's cancellation handling, captured-logprob bypass, multi-turn boundary routes, and MoE route layout while keeping capture codec-free. After this update, 235 focused CPU tests and 3 cancellation tests passed with main's pinned Gym (3f6f20593). Lint, formatting, and configuration checks passed. Local type checking reports the same 38 diagnostics as clean main, with no new errors. The 21 vLLM-runtime tests and live-TransferQueue integration suite remain for CI; GPU E2E was not rerun for this update.

Main W&B run · PR W&B run

Screenshot 2026-09-30 at 9 36 33 AM

Keep native route tensors for admitted capture requests, slice the token
delta directly, and stage it through Gym's existing attachment interface.
Bind the tensor's dtype, shape, and raw-byte checksum with the existing
extras digest; verify it directly when assembling routes. Preserve the
existing codec behavior for ordinary HTTP responses and legacy records.

No new capture settings, transport, storage columns, or Gym runtime API.

Validation: 95 focused CPU tests pass; 2 vLLM-dependent tests deselected.
All pre-commit hooks pass except pyrefly, whose 40 diagnostics exactly
match unmodified main in the same local environment (zero added).

CPU route conversion/checksum microbenchmark, int16 [tokens,48,8], half
the tokens retained, median of 9 runs: 1K 8.60 -> 0.75 ms; 8K 59.92 ->
3.35 ms; 32K 316.85 -> 16.36 ms. This excludes inference and TQ I/O;
full GPU rollout throughput has not been measured.

Signed-off-by: Zeyu Zhou <[email protected]>
@copy-pr-bot

copy-pr-bot Bot commented Sep 29, 2026

Copy link
Copy Markdown

This pull request requires additional validation before any workflows can run on NVIDIA's runners.

Pull request vetters can view their responsibilities here.

Contributors can view more details about this message here.

@github-actions

Copy link
Copy Markdown

✅ Submodule Fast-Forward Check Results

Check based on commit: 23e1ca6 (PR #4345 from router-capture-no-codec)

✅ Submodules that are properly updated:

Gym: ✅ PR branch is ahead of main branch (fast-forward)

All submodule changes look good! ✨

@zyzhou5 zyzhou5 left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Team review generated by Codex using the review-pr-team skill.

Reviewed commit 23e1ca6 against main. Both P2 findings below were reproduced locally. One identifies preexisting vLLM encoding left outside the optimization, and the other identifies a startup regression introduced by the Gym dependency update.

Validation: 31 focused tests passed, plus 18 consumer/finalizer checks and 12 checks of the pinned TransferQueue tensor serializer. The passing capture tests exercise RL's codec bypass but omit vLLM's superclass response-building step. Reproductions used the pinned source with controlled local inputs; no live model inference, distributed rollout, or end-to-end throughput measurement was performed.

Comment thread 3rdparty/Gym-workspace/Gym Resolved
@github-actions

Copy link
Copy Markdown

✅ Submodule Fast-Forward Check Results

Check based on commit: 3b75faf (PR #4345 from router-capture-no-codec)

✅ Submodules that are properly updated:

Gym: ✅ PR branch is ahead of main branch (fast-forward)

All submodule changes look good! ✨

Merge current main while retaining native routed-expert attachments alongside captured media. Preserve media validation and combined staging, and cover simultaneous route and pixel capture without codec calls.

Signed-off-by: Zeyu Zhou <[email protected]>
@zyzhou5

zyzhou5 commented Sep 30, 2026

Copy link
Copy Markdown
Contributor Author

/ok to test 4237d71

@github-actions

Copy link
Copy Markdown

✅ Submodule Fast-Forward Check Results

Check based on commit: 4237d71 (PR #4345 from router-capture-no-codec)

✅ Submodules that are properly updated:

Gym: ✅ PR branch is ahead of main branch (fast-forward)

All submodule changes look good! ✨

@zyzhou5 zyzhou5 added the CI:Lfast Runs a fast test suite and re-use nightly `main` container (but sync dependencies to PRs version) label Sep 30, 2026
@zyzhou5

zyzhou5 commented Sep 30, 2026

Copy link
Copy Markdown
Contributor Author

/ok to test 4237d71

@zyzhou5

zyzhou5 commented Sep 30, 2026

Copy link
Copy Markdown
Contributor Author

/ok to test 9247b23

@github-actions

Copy link
Copy Markdown

✅ Submodule Fast-Forward Check Results

Check based on commit: 9247b23 (PR #4345 from router-capture-no-codec)

✅ Submodules that are properly updated:

Gym: ✅ PR branch is ahead of main branch (fast-forward)

All submodule changes look good! ✨

zyzhou5 added a commit to zyzhou5/RL that referenced this pull request Sep 30, 2026
Port compact hybrid router buffers from 1bc0ed1 to the pinned vLLM 0.29 capturer and scheduler. Resolve matching Megatron hybrid layer dimensions while retaining full-width payload support.

Keep this change independent of the token-capture codec PR. The additional native-capture integration-test extension is preserved separately for after NVIDIA-NeMo#4345 merges.

Validation on main: 103 focused tests passed, 16 deselected. CPU/CUDA buffer capture, replay route identity and gradients, and route assembly pass. Formatting and lint pass; pyrefly reports the same 40 diagnostics as the baseline.

Signed-off-by: Zeyu Zhou <[email protected]>
@zyzhou5

zyzhou5 commented Oct 8, 2026

Copy link
Copy Markdown
Contributor Author

This should be merged after #4517 so we dont need to bump Gym here

Merge current main and retain its Gym pin and dependency lockfile. PR NVIDIA-NeMo#4517 supplies the Gym update, so this PR now contains only the native router-capture optimization and its tests.

Signed-off-by: Zeyu Zhou <[email protected]>
@zyzhou5

zyzhou5 commented Oct 12, 2026

Copy link
Copy Markdown
Contributor Author

/ok to test 67424e2

…main

Merge main through 081b072 and retain the boundary row introduced by NVIDIA-NeMo#4610 in the native tensor capture path. Update capture and route-assembly tests for the boundary row and missing-route sentinel. Keep Gym and dependency pins unchanged from main.

Signed-off-by: Zeyu Zhou <[email protected]>
@zyzhou5

zyzhou5 commented Oct 13, 2026

Copy link
Copy Markdown
Contributor Author

/ok to test 3cb398c

pthombre
pthombre previously approved these changes Oct 13, 2026
@zyzhou5

zyzhou5 commented Oct 26, 2026

Copy link
Copy Markdown
Contributor Author

/ok to test 3e3b1fb

zyzhou5 added a commit to zyzhou5/RL that referenced this pull request Oct 28, 2026
Port compact hybrid router buffers from 1bc0ed1 to the pinned vLLM 0.29 capturer and scheduler. Resolve matching Megatron hybrid layer dimensions while retaining full-width payload support.

Keep this change independent of the token-capture codec PR. The additional native-capture integration-test extension is preserved separately for after NVIDIA-NeMo#4345 merges.

Validation on main: 103 focused tests passed, 16 deselected. CPU/CUDA buffer capture, replay route identity and gradients, and route assembly pass. Formatting and lint pass; pyrefly reports the same 40 diagnostics as the baseline.

Signed-off-by: Zeyu Zhou <[email protected]>
@zyzhou5
zyzhou5 requested a review from terrykong October 28, 2026 22:19
Keep both native-route metadata checks and main's routed-expert slice storage test.

Signed-off-by: Zeyu Zhou <[email protected]>
@zyzhou5

zyzhou5 commented Oct 29, 2026

Copy link
Copy Markdown
Contributor Author

/ok to test 7a59f54

@ZhiyuLi-Nvidia

Copy link
Copy Markdown
Contributor

Two follow-ups on router capture: one bug (vLLM path), one suggestion (Megatron/MInf path plus a shared helper).

1. Bug: the vLLM capture path stages a view, so each put carries the whole route buffer

_delta_align_routed_experts does routed = routed[start:] (vllm_worker_async.py:882). The slice shares storage with the engine's full [prompt+gen, L, K] tensor, and TQTokenSink.stage passes it on with only .unsqueeze(0), so nothing copies it. pickle and torch.save write a view's entire storage, so a continuation call can ship the whole sequence's routes instead of the delta.

I ran a test against 7a59f54 in the nemo-rl nightly-gym.2026-10-26 image (512-token prompt, parent covered 500):

AssertionError: staged routes view a 8208-byte buffer for 224 bytes of delta; pickle writes 8623 bytes

With routed = routed[start:].clone() the same test passes. The waste grows with sequence length.

Limit of the check: pickle is the only transport I measured. I did not check which serializer the SimpleStorage backend uses. The Mooncake path reads only the view's own bytes (adapters/transfer_queue.py:650-661), so it is not affected.

2. Suggestion: use one shared helper for vLLM and Megatron/MInf capture

The Megatron/MInf stager still calls encode_routed_experts(...) (token_capture.py:621), and the sink decodes it again (ROUTE_ENCODING_ENVELOPE). It already passes media through complete_call(..., attachments=...), so the native path applies there too. Its aligned slice, aligned[prev_len - boundary_route_rows(prev_len):], is also a view and needs the same copy.

Rather than repeat slice, CPU move, copy and metadata in two workers, put it in one function in routed_experts_codec.py:

def native_route_attachment(
    routes: torch.Tensor,
) -> tuple[dict[str, Any], torch.Tensor]:
    """Compact CPU tensor plus the descriptor that enters the extras digest."""
    routes = routes.detach().cpu()
    if routes.untyped_storage().nbytes() != routes.numel() * routes.element_size():
        # A view would drag its whole buffer through serialization.
        routes = routes.clone()
    return routed_experts_tensor_metadata(routes), routes

Callers:

  • vLLM: routed, meta = native_route_attachment(routed[start:]), then message["routed_experts"] = meta.
  • Megatron/MInf: meta, routes = native_route_attachment(routed_experts), then extras = {"routed_experts": meta} and attachments = {**(self._cast_media_pixels(media) or {}), "routed_experts": routes}.

This keeps the contract (CPU, compact, int8/int16/int32, descriptor matches the tensor) in one place. Note _delta_align_minf_routing_indices keeps routes.device, so the Megatron tensor may be on GPU; .cpu() in the helper handles that. The helper is a sketch and I did not run it. Only the vLLM .clone() was run. I found no Megatron route tests under tests/unit/models/generation/megatron.

Regression test used above (tests/unit/data_plane/test_route_staging_storage.py)
"""A staged route delta must not carry the engine's whole route buffer."""

from __future__ import annotations

import pickle
from types import SimpleNamespace

import pytest
import torch
from pydantic import BaseModel, ConfigDict

pytest.importorskip("nemo_gym.token_id_capture.staging")

from nemo_gym.token_id_capture.adapters.vllm import VLLMCaptureAdapter  # noqa: E402
from nemo_gym.token_id_capture.staging import RolloutTokenCapture  # noqa: E402

from nemo_rl.data_plane.schema import ROUTED_EXPERTS_FIELD  # noqa: E402
from nemo_rl.data_plane.tq_token_sink import TQTokenSink  # noqa: E402
from nemo_rl.models.generation.vllm import utils as vllm_utils  # noqa: E402
from nemo_rl.models.generation.vllm.vllm_worker_async import (  # noqa: E402
    VllmAsyncGenerationWorkerImpl,
)

pytestmark = pytest.mark.nemo_gym

NUM_LAYERS = 4
TOP_K = 2


class _StagingClient:
    def __init__(self):
        self.fields = None

    def put_samples(self, *, fields, **kwargs):
        self.fields = fields

    def get_samples(self, *, select_fields, **kwargs):
        return self.fields.select(*select_fields)


class _Message(BaseModel):
    model_config = ConfigDict(extra="allow")
    role: str = "assistant"
    content: str = "answer"


class _Choice(BaseModel):
    index: int = 0
    message: _Message


class _Response(BaseModel):
    choices: list[_Choice]


def _stage_continuation(prompt_len: int, prev_len: int) -> torch.Tensor:
    client = _StagingClient()
    worker = SimpleNamespace(_capture_calls={})
    worker.token_capture = RolloutTokenCapture(
        sink=TQTokenSink(client, staging_partition="staging"),
        weight_version_fn=lambda: 7,
        adapter=VLLMCaptureAdapter(),
    )
    worker._capture_admission = (
        VllmAsyncGenerationWorkerImpl._capture_admission.__get__(worker)
    )
    worker._delta_align_routed_experts = (
        VllmAsyncGenerationWorkerImpl._delta_align_routed_experts
    )
    prompt = list(range(10, 10 + prompt_len))
    request = SimpleNamespace(
        ng_capture={
            "rollout_id": "r",
            "model_call_id": "c",
            "mode": "token_in",
            "parent_call_id": "parent",
            "prev_len": prev_len,
            "required_prefix_token_ids": prompt[:prev_len],
            "parent_chain_hash": "1" * 64,
        },
        stream=False,
    )
    VllmAsyncGenerationWorkerImpl._begin_request_capture(worker, request, prompt)
    prompt_routes = torch.arange(
        (prompt_len - 1) * NUM_LAYERS * TOP_K, dtype=torch.int16
    ).reshape(-1, NUM_LAYERS, TOP_K)
    output = SimpleNamespace(
        prompt_token_ids=prompt,
        prompt_routed_experts=prompt_routes,
        outputs=[
            SimpleNamespace(
                index=0,
                token_ids=[999],
                logprobs=[{999: SimpleNamespace(logprob=-0.25)}],
                routed_experts=torch.ones(1, NUM_LAYERS, TOP_K, dtype=torch.int16),
            )
        ],
    )
    response = _Response(choices=[_Choice(message=_Message())])
    vllm_utils.attach_token_information_to_chat_response_choices(response, output)
    vllm_utils.attach_routed_experts_to_chat_response_choices(
        response,
        output,
        device=torch.device("cpu"),
        routed_experts_dtype=torch.int16,
        encode_for_wire=id(request) not in worker._capture_calls,
    )
    content = VllmAsyncGenerationWorkerImpl._finish_request_capture(
        worker,
        request,
        vllm_utils.model_dump_chat_response_with_dynamic_message_fields(response),
    )
    assert content["ng_commit_coords"]["disposition"] == "staged"
    return client.fields[ROUTED_EXPERTS_FIELD]


def test_staged_route_delta_owns_only_its_own_storage():
    # 512-token prompt, parent covered 500: the delta is a small tail.
    staged = _stage_continuation(prompt_len=512, prev_len=500)

    payload = staged.numel() * staged.element_size()
    storage = staged.untyped_storage().nbytes()
    # What a pickle-based transport would write for this put; pickle adds a
    # fixed header of a few hundred bytes, so allow 1 KiB over the payload.
    wire = len(pickle.dumps(staged))
    assert storage == payload and wire < payload + 1024, (
        f"staged routes view a {storage}-byte buffer for {payload} bytes of "
        f"delta; pickle writes {wire} bytes"
    )

Run with --nemo-gym-only (the repo's conftest.py deselects nemo_gym tests by default).

@ZhiyuLi-Nvidia

Copy link
Copy Markdown
Contributor

Correction to my earlier comment.

Withdrawing item 1 ("bug: each put carries the whole route buffer"). My pickle test did not establish excess traffic on the actual put path.

What I measured on TransferQueue 0.1.11: its own encoder (serial_utils.MsgpackEncoder, zmq_utils.encode) emits 768,039 B for both a 1,000-row tail view and its clone; simple_storage.py:467 flattens the tensor to bytes; Mooncake's writer reads only the view's bytes (adapters/transfer_queue.py:650-661). Pickle, torch.save and Ray serialization do write the whole storage (76.8 MB vs 0.77 MB for the view vs the clone).

What I did not do: trace the full SimpleStorage client-to-storage call chain, so I cannot rule out a Ray serialization hop between them, and I measured the encoder on a bare tensor rather than an end-to-end put. Until that is traced I am not asking for .clone(), and the data_ptr assertions in test_capture_route_tensors.py should stay as they are. Please disregard the regression test from my earlier comment too: it measures pickle, which is not TransferQueue's transport.

Item 2 (Megatron/MInf still round-trips through the codec, token_capture.py:621) stands as an optional, non-blocking follow-up.

@ZhiyuLi-Nvidia ZhiyuLi-Nvidia left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Three non-blocking nits, each with a proposed change.

Comment thread nemo_rl/utils/routed_experts_codec.py Resolved
Comment thread nemo_rl/data_plane/tq_token_sink.py Resolved
ZhiyuLi-Nvidia
ZhiyuLi-Nvidia previously approved these changes Nov 2, 2026

@ZhiyuLi-Nvidia ZhiyuLi-Nvidia left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you @zyzhou5. LGTM!

Just several nits and no blocking issues.

Merge main while retaining native router tensors alongside sampler top-k attachments. Update capture fixtures and verify both payloads survive the same staging write.

Signed-off-by: Zeyu Zhou <[email protected]>
@zyzhou5

zyzhou5 commented Nov 2, 2026

Copy link
Copy Markdown
Contributor Author

/ok to test 9cac286

@ZhiyuLi-Nvidia
ZhiyuLi-Nvidia enabled auto-merge (squash) November 2, 2026 23:24
@zyzhou5

zyzhou5 commented Nov 3, 2026

Copy link
Copy Markdown
Contributor Author

/ok to test 6b88ae9

@zyzhou5

zyzhou5 commented Nov 3, 2026

Copy link
Copy Markdown
Contributor Author

/ok to test ce6fb9d

@ZhiyuLi-Nvidia
ZhiyuLi-Nvidia merged commit 681ca04 into NVIDIA-NeMo:main Nov 4, 2026
92 checks passed
jthomson04 added a commit to jthomson04/RL that referenced this pull request Nov 4, 2026
Resolve utils.py: main's encode_for_wire (NVIDIA-NeMo#4345) moves into
chat_routed_experts, which the chat attach loop now calls.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: jthomson04 <[email protected]>
jthomson04 added a commit to jthomson04/RL that referenced this pull request Nov 4, 2026
Main's NVIDIA-NeMo#4345 makes capture stage routed experts as native tensors and
drop any other form. The Dynamo Gym capture path still passed the wire
envelope, so captured calls lost their routes. Pass encode_for_wire=False
there, as the native chat handler does; uncaptured calls keep the
envelope in engine_data.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: jthomson04 <[email protected]>
jthomson04 added a commit to jthomson04/RL that referenced this pull request Nov 4, 2026
…ake worker

NVIDIA-NeMo#4979 splits admission parsing out of _capture_admission so the Dynamo
engine can parse its annotation; the fake worker from main's NVIDIA-NeMo#4345 test
needs both bound.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: jthomson04 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

CI:Lfast Runs a fast test suite and re-use nightly `main` container (but sync dependencies to PRs version)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants