-
Notifications
You must be signed in to change notification settings - Fork 550
fix: eliminate JSON serialization bottleneck in r3 + NeMo-Gym rollouts #3292
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
terrykong
merged 4 commits into
NVIDIA-NeMo:main
from
zyzhou5:zezhou/r3-gym-routes-b64-transport
Jul 30, 2026
Merged
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
c7f9bcf
perf: encode gym routed_experts as base64 envelope instead of JSON in…
zyzhou5 d6be365
ci: add routed_experts_codec.py to pyrefly project-includes
zyzhou5 0cbe0ac
perf: encode routed_experts buffer zero-copy via memoryview
zyzhou5 79fb96b
refactor: decode routed_experts via torch.frombuffer on a writable by…
zyzhou5 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
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
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
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,106 @@ | ||
| # Copyright (c) 2026, NVIDIA CORPORATION. All rights reserved. | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
| """Compact wire codec for router-replay routed-expert indices. | ||
|
|
||
| Routed experts for a long-context sample are millions of ints (shape | ||
| [tokens, num_moe_layers, topk]). Serialized as nested JSON lists they cost | ||
| ~1s of single-threaded CPU per serialize/parse hop, and every HTTP hop on | ||
| the NeMo Gym path (model server, agent, resources server) pays that again | ||
| for pydantic validation and re-serialization. Encoded as a single base64 | ||
| string the payload stays one opaque Python object end to end, so | ||
| intermediate hops only pay a string copy. | ||
|
|
||
| Envelope format (version 1): | ||
| "nrlre1:<dtype>:<S>x<L>x<K>:<base64 of C-contiguous array bytes>" | ||
|
|
||
| This module must stay importable inside the NeMo Gym actor, so it may only | ||
| depend on torch. | ||
| """ | ||
|
|
||
| import base64 | ||
| from typing import Any, Union | ||
|
|
||
| import torch | ||
|
|
||
| _MAGIC = "nrlre1" | ||
|
zyzhou5 marked this conversation as resolved.
|
||
| _WIRE_TORCH_DTYPES = { | ||
| "int8": torch.int8, | ||
| "int16": torch.int16, | ||
| "int32": torch.int32, | ||
| } | ||
| _TORCH_DTYPE_NAMES = {v: k for k, v in _WIRE_TORCH_DTYPES.items()} | ||
|
|
||
|
|
||
| def encode_routed_experts(routed_experts: torch.Tensor) -> str: | ||
| """Encode a [tokens, num_moe_layers, topk] tensor as a base64 envelope. | ||
|
|
||
| The tensor's own dtype (int8/int16/int32, as resolved by | ||
| ``resolve_routed_experts_dtype``) is preserved on the wire. | ||
| """ | ||
| if routed_experts.dim() != 3: | ||
| raise ValueError( | ||
| "routed_experts must have shape [tokens, num_moe_layers, topk], " | ||
| f"got {tuple(routed_experts.shape)}." | ||
| ) | ||
| dtype_name = _TORCH_DTYPE_NAMES.get(routed_experts.dtype) | ||
| if dtype_name is None: | ||
| raise ValueError( | ||
| f"Unsupported routed_experts dtype {routed_experts.dtype}; " | ||
| f"expected one of {sorted(_WIRE_TORCH_DTYPES)}." | ||
| ) | ||
| arr = routed_experts.detach().cpu().contiguous().numpy() | ||
| tokens, num_layers, topk = arr.shape | ||
| # memoryview feeds the buffer to b64encode zero-copy; tobytes() would | ||
| # materialize a full-size intermediate copy of the payload. | ||
| data = base64.b64encode(memoryview(arr)).decode("ascii") | ||
| return f"{_MAGIC}:{dtype_name}:{tokens}x{num_layers}x{topk}:{data}" | ||
|
|
||
|
|
||
| def decode_routed_experts(payload: Union[str, Any], dtype: torch.dtype) -> torch.Tensor: | ||
| """Decode routed experts into a tensor of the requested dtype. | ||
|
|
||
| Accepts the base64 envelope produced by ``encode_routed_experts`` or the | ||
| legacy nested-list format. | ||
| """ | ||
| if not isinstance(payload, str): | ||
| return torch.as_tensor(payload, dtype=dtype) | ||
| parts = payload.split(":", 3) | ||
| if len(parts) != 4 or parts[0] != _MAGIC: | ||
| raise ValueError( | ||
| "routed_experts string payload is not a valid " | ||
| f"'{_MAGIC}:<dtype>:<SxLxK>:<base64>' envelope." | ||
| ) | ||
| _, dtype_name, shape_str, data = parts | ||
| wire_dtype = _WIRE_TORCH_DTYPES.get(dtype_name) | ||
| if wire_dtype is None: | ||
| raise ValueError(f"Unsupported routed_experts dtype '{dtype_name}'.") | ||
| shape = tuple(int(dim) for dim in shape_str.split("x")) | ||
| if len(shape) != 3: | ||
| raise ValueError( | ||
| f"routed_experts envelope shape '{shape_str}' is not 3-dimensional." | ||
| ) | ||
| # Decode into a writable bytearray so torch.frombuffer can share its | ||
| # memory directly (frombuffer writability follows the underlying buffer; | ||
| # the bytearray construction is the single unavoidable copy). | ||
| raw = bytearray(base64.b64decode(data, validate=True)) | ||
| expected = shape[0] * shape[1] * shape[2] | ||
| if len(raw) != expected * wire_dtype.itemsize: | ||
| raise ValueError( | ||
| f"routed_experts envelope has {len(raw) // wire_dtype.itemsize} " | ||
| f"elements, expected {expected} for shape {shape}." | ||
| ) | ||
| if expected == 0: | ||
| return torch.empty(shape, dtype=dtype) | ||
| tensor = torch.frombuffer(raw, dtype=wire_dtype).reshape(shape) | ||
| return tensor if tensor.dtype == dtype else tensor.to(dtype) | ||
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
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
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,62 @@ | ||
| # Copyright (c) 2026, NVIDIA CORPORATION. All rights reserved. | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
|
|
||
| import pytest | ||
| import torch | ||
|
|
||
| from nemo_rl.utils.routed_experts_codec import ( | ||
| decode_routed_experts, | ||
| encode_routed_experts, | ||
| ) | ||
|
|
||
|
|
||
| @pytest.mark.parametrize("dtype", [torch.int8, torch.int16, torch.int32]) | ||
| def test_round_trip_preserves_values_and_wire_dtype(dtype): | ||
| routes = torch.randint(0, 100, (7, 3, 2), dtype=torch.int32) | ||
| routes[2, 1, 0] = -1 # missing-route sentinel survives signed dtypes | ||
| routes = routes.to(dtype) | ||
|
|
||
| payload = encode_routed_experts(routes) | ||
| assert isinstance(payload, str) | ||
| assert payload.startswith(f"nrlre1:{str(dtype).removeprefix('torch.')}:7x3x2:") | ||
|
|
||
| decoded = decode_routed_experts(payload, dtype=torch.int32) | ||
| assert decoded.dtype == torch.int32 | ||
| assert torch.equal(decoded, routes.to(torch.int32)) | ||
|
|
||
|
|
||
| def test_decode_accepts_legacy_nested_lists(): | ||
| decoded = decode_routed_experts([[[1, 2]], [[3, 4]]], dtype=torch.int16) | ||
| assert decoded.dtype == torch.int16 | ||
| assert decoded.tolist() == [[[1, 2]], [[3, 4]]] | ||
|
|
||
|
|
||
| def test_decode_rejects_malformed_payloads(): | ||
| with pytest.raises(ValueError, match="envelope"): | ||
| decode_routed_experts("not-an-envelope", dtype=torch.int32) | ||
|
|
||
| good = encode_routed_experts(torch.zeros(2, 3, 2, dtype=torch.int16)) | ||
| magic, dtype_name, _, data = good.split(":", 3) | ||
| with pytest.raises(ValueError, match="expected"): | ||
| # Element count does not match the declared shape. | ||
| decode_routed_experts(f"{magic}:{dtype_name}:5x3x2:{data}", dtype=torch.int32) | ||
| with pytest.raises(ValueError, match="dtype"): | ||
| decode_routed_experts(f"{magic}:int64:2x3x2:{data}", dtype=torch.int32) | ||
|
|
||
|
|
||
| def test_encode_rejects_bad_inputs(): | ||
| with pytest.raises(ValueError, match="shape"): | ||
| encode_routed_experts(torch.zeros(3, 2, dtype=torch.int16)) | ||
| with pytest.raises(ValueError, match="dtype"): | ||
| encode_routed_experts(torch.zeros(2, 3, 2, dtype=torch.int64)) |
Oops, something went wrong.
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.
Uh oh!
There was an error while loading. Please reload this page.