Repository navigation
perf(token-capture): stage routed experts without codec round trips - #4345
Conversation
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]>
Signed-off-by: Zeyu Zhou <[email protected]>
Signed-off-by: Zeyu Zhou <[email protected]>
zyzhou5
left a comment
There was a problem hiding this comment.
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.
Signed-off-by: Zeyu Zhou <[email protected]>
Signed-off-by: Zeyu Zhou <[email protected]>
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]>
|
/ok to test 4237d71 |
|
/ok to test 4237d71 |
Signed-off-by: Zeyu Zhou <[email protected]>
|
/ok to test 9247b23 |
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]>
|
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]>
|
/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]>
|
/ok to test 3cb398c |
…utes Signed-off-by: Zeyu Zhou <[email protected]>
|
/ok to test 3e3b1fb |
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]>
Keep both native-route metadata checks and main's routed-expert slice storage test. Signed-off-by: Zeyu Zhou <[email protected]>
|
/ok to test 7a59f54 |
|
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
I ran a test against 7a59f54 in the With 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 captureThe Megatron/MInf stager still calls Rather than repeat slice, CPU move, copy and metadata in two workers, put it in one function in 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), routesCallers:
This keeps the contract (CPU, compact, int8/int16/int32, descriptor matches the tensor) in one place. Note 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 |
|
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 ( 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 Item 2 (Megatron/MInf still round-trips through the codec, token_capture.py:621) stands as an optional, non-blocking follow-up. |
ZhiyuLi-Nvidia
left a comment
There was a problem hiding this comment.
Three non-blocking nits, each with a proposed change.
ZhiyuLi-Nvidia
left a comment
There was a problem hiding this comment.
Thank you @zyzhou5. LGTM!
Just several nits and no blocking issues.
Signed-off-by: Zeyu Zhou <[email protected]>
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]>
|
/ok to test 9cac286 |
Signed-off-by: Zeyu Zhou <[email protected]>
|
/ok to test 6b88ae9 |
Signed-off-by: Zeyu Zhou <[email protected]>
|
/ok to test ce6fb9d |
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]>
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]>
…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]>
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
TQTokenSinkin 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