Skip to content
21 changes: 17 additions & 4 deletions components/src/dynamo/vllm/handlers.py
Original file line number Diff line number Diff line change
Expand Up @@ -653,7 +653,9 @@ def _accumulate_engine_data(
tok["engine_data"] = engine_data


def _serialize_routed_experts(routed_experts: Any) -> Optional[Dict[str, Any]]:
def _serialize_routed_experts(
routed_experts: Any, start: int = 0
) -> Optional[Dict[str, Any]]:
if routed_experts is None:
return None

Expand All @@ -667,10 +669,15 @@ def _serialize_routed_experts(routed_experts: Any) -> Optional[Dict[str, Any]]:
return None

return {
"data": base64.b85encode(tobytes()).decode("ascii"),
# base64, matching vLLM-native encoding.
"data": base64.b64encode(tobytes()).decode("ascii"),
"shape": [int(dim) for dim in shape],
# Row offset of the first returned routing entry within the full
# sequence (= SamplingParams.routed_experts_prompt_start; vLLM trims the
# leading prompt rows). Lets the RL consumer align the completion.
"start": int(start),
# Encode dtype so the consumer decodes the raw bytes with the right
# element type instead of assuming int32.
# element type instead of assuming a fixed width.
"dtype": str(getattr(routed_experts, "dtype", "")),
}

Expand Down Expand Up @@ -3024,7 +3031,13 @@ async def generate_tokens(
out, prompt_logprobs_payload
)
routed_experts = _serialize_routed_experts(
raw_routed_experts_by_output.get(output_idx)
raw_routed_experts_by_output.get(output_idx),
start=int(
getattr(
sampling_params, "routed_experts_prompt_start", 0
)
or 0
),
)
if routed_experts is not None:
_attach_routed_experts_engine_data(out, routed_experts)
Expand Down
51 changes: 50 additions & 1 deletion components/src/dynamo/vllm/tests/test_vllm_worker_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -346,11 +346,60 @@ async def fake_generate(*args, **kwargs):
routed = chunks[1]["engine_data"]["routed_experts"]
assert routed["shape"] == [2, 1, 1]
assert routed["dtype"] == "int32"
Comment thread
biswapanda marked this conversation as resolved.
Resolved
# start defaults to 0 when routed_experts_prompt_start is unset.
assert routed["start"] == 0
decoded = np.frombuffer(
base64.b85decode(routed["data"]), dtype=np.dtype(routed["dtype"])
base64.b64decode(routed["data"]), dtype=np.dtype(routed["dtype"])
)
np.testing.assert_array_equal(decoded, routed_experts.reshape(-1))

@pytest.mark.asyncio
async def test_generate_tokens_routed_experts_start_echoes_prompt_start(self):
"""routed_experts.start echoes SamplingParams.routed_experts_prompt_start
(the offset vLLM trimmed) so the RL consumer can align the completion."""
from vllm.sampling_params import SamplingParams

# routed_experts_prompt_start is an RL-patch field; set it post-construct
# so the test runs against stock vLLM too (the worker reads it via
# getattr, defaulting to 0 when absent).
sampling_params = SamplingParams(max_tokens=1)
try:
sampling_params.routed_experts_prompt_start = 5
except (AttributeError, TypeError):
pytest.skip("installed vLLM has no routed_experts_prompt_start support")
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

handler = _make_handler()
handler._extract_logprobs = MagicMock(return_value=(None, None))
routed_experts = np.array([[[3]], [[4]]], dtype=np.int32)

async def fake_generate(*args, **kwargs):
yield SimpleNamespace(
outputs=[
SimpleNamespace(
index=0,
token_ids=[12],
routed_experts=routed_experts,
finish_reason="stop",
stop_reason=None,
)
],
prompt_token_ids=[1, 2],
prompt_logprobs=None,
)

handler.engine_client = MagicMock()
handler.engine_client.generate = fake_generate

chunks = []
async for chunk in handler.generate_tokens(
PatchedTokensPrompt(prompt_token_ids=[1]),
sampling_params,
"req-2",
):
chunks.append(chunk)

assert chunks[-1]["engine_data"]["routed_experts"]["start"] == 5


# ── Tests ────────────────────────────────────────────────────────────

Expand Down
Loading