diff --git a/components/src/dynamo/vllm/handlers.py b/components/src/dynamo/vllm/handlers.py index 866ca92b7d26..07cf85eb07a9 100644 --- a/components/src/dynamo/vllm/handlers.py +++ b/components/src/dynamo/vllm/handlers.py @@ -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 @@ -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", "")), } @@ -746,6 +753,19 @@ def build_sampling_params( if value is not None and hasattr(sampling_params, key): setattr(sampling_params, key, value) + # routed_experts_prompt_start (RL capture offset) must be a non-negative + # int; reject bad client values so the worker emits a sane `start` instead + # of a bogus offset the consumer cannot align (vLLM clamps the upper bound). + reps = getattr(sampling_params, "routed_experts_prompt_start", None) + if reps is not None and ( + isinstance(reps, bool) or not isinstance(reps, int) or reps < 0 + ): + logger.warning( + "Ignoring invalid routed_experts_prompt_start=%r (want non-negative int)", + reps, + ) + sampling_params.routed_experts_prompt_start = 0 + # Apply stop_conditions for key, value in request.get("stop_conditions", {}).items(): if value is not None and hasattr(sampling_params, key): @@ -2993,7 +3013,7 @@ async def generate_tokens( "token_ids": token_ids, } # Capture the raw routed_experts cheaply here; serialize it - # only once on the final chunk (base85-encoding a tensor on + # only once on the final chunk (base64-encoding a tensor on # every streamed chunk would be wasted work, since only the # final value is emitted). raw_routed_experts = getattr(output, "routed_experts", None) @@ -3023,8 +3043,21 @@ async def generate_tokens( _attach_prompt_logprobs_engine_data( out, prompt_logprobs_payload ) + # Emit the EFFECTIVE trim offset: clamp the requested + # routed_experts_prompt_start to the prompt length. vLLM + # clamps the returned routing rows the same way, so an + # out-of-range request (e.g. start=999 on a 100-token + # prompt) would otherwise publish a `start` the consumer + # cannot align to the (clamped) tensor. + raw_start = int( + getattr(sampling_params, "routed_experts_prompt_start", 0) + or 0 + ) + prompt_len = len(getattr(res, "prompt_token_ids", None) or []) + effective_start = min(raw_start, prompt_len) routed_experts = _serialize_routed_experts( - raw_routed_experts_by_output.get(output_idx) + raw_routed_experts_by_output.get(output_idx), + start=effective_start, ) if routed_experts is not None: _attach_routed_experts_engine_data(out, routed_experts) diff --git a/components/src/dynamo/vllm/tests/test_vllm_worker_handler.py b/components/src/dynamo/vllm/tests/test_vllm_worker_handler.py index 5272736de2c3..1f66f4880aa1 100644 --- a/components/src/dynamo/vllm/tests/test_vllm_worker_handler.py +++ b/components/src/dynamo/vllm/tests/test_vllm_worker_handler.py @@ -293,7 +293,7 @@ async def test_generate_tokens_emits_routed_experts_on_final_chunk(self): handler = _make_handler() handler._extract_logprobs = MagicMock(return_value=(None, None)) - routed_experts = np.array([[[1]], [[2]]], dtype=np.int32) + routed_experts = np.array([[[1]], [[2]]], dtype=np.int16) async def fake_generate(*args, **kwargs): yield SimpleNamespace( @@ -345,12 +345,110 @@ async def fake_generate(*args, **kwargs): assert "disaggregated_params" not in chunks[1] routed = chunks[1]["engine_data"]["routed_experts"] assert routed["shape"] == [2, 1, 1] - assert routed["dtype"] == "int32" + assert routed["dtype"] == "int16" + # 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") + + handler = _make_handler() + handler._extract_logprobs = MagicMock(return_value=(None, None)) + routed_experts = np.array([[[3]], [[4]]], dtype=np.int16) + + # Prompt longer than the requested start, so the echoed offset is not + # clamped to the prompt length. + prompt_token_ids = [1, 2, 3, 4, 5, 6] + + 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=prompt_token_ids, + 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=prompt_token_ids), + sampling_params, + "req-2", + ): + chunks.append(chunk) + + assert chunks[-1]["engine_data"]["routed_experts"]["start"] == 5 + + @pytest.mark.asyncio + async def test_generate_tokens_routed_experts_start_clamped_to_prompt_len(self): + """An out-of-range routed_experts_prompt_start is clamped to the prompt + length (vLLM clamps the returned rows the same way).""" + from vllm.sampling_params import SamplingParams + + sampling_params = SamplingParams(max_tokens=1) + try: + sampling_params.routed_experts_prompt_start = 99 + except (AttributeError, TypeError): + pytest.skip("installed vLLM has no routed_experts_prompt_start support") + + handler = _make_handler() + handler._extract_logprobs = MagicMock(return_value=(None, None)) + routed_experts = np.array([[[3]], [[4]]], dtype=np.int16) + + 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, 3], + 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, 2, 3]), + sampling_params, + "req-3", + ): + chunks.append(chunk) + + # start=99 clamped to prompt_len=3 + assert chunks[-1]["engine_data"]["routed_experts"]["start"] == 3 + # ── Tests ────────────────────────────────────────────────────────────