diff --git a/tests/v1/engine/test_output_processor.py b/tests/v1/engine/test_output_processor.py index 9630f8cae3ed..dbb5af023c53 100644 --- a/tests/v1/engine/test_output_processor.py +++ b/tests/v1/engine/test_output_processor.py @@ -1340,3 +1340,196 @@ def test_abort_requests(runner: str, abort_by: str, dummy_test_vectors): output_processor.abort_requests([request.request_id], internal=True) else: output_processor.abort_requests([request.external_req_id], internal=False) + + +@pytest.mark.parametrize("stream_interval_ms", [0, 100]) +def test_stream_interval_ms( + stream_interval_ms: int, + dummy_test_vectors, +): + """Test time-based stream interval throttling.""" + output_processor = OutputProcessor( + dummy_test_vectors.tokenizer, + log_stats=False, + stream_interval=1, + stream_interval_ms=stream_interval_ms, + ) + + requests = [ + EngineCoreRequest( + request_id=f"request-{idx}-int", + external_req_id=f"request-{idx}", + prompt_token_ids=prompt_tokens, + mm_features=None, + eos_token_id=None, + arrival_time=0, + lora_request=None, + cache_salt=None, + data_parallel_rank=None, + sampling_params=SamplingParams( + skip_special_tokens=False, + spaces_between_special_tokens=False, + output_kind=RequestOutputKind.DELTA, + stop=[], + include_stop_str_in_output=False, + ), + pooling_params=None, + ) + for idx, prompt_tokens in enumerate(dummy_test_vectors.prompt_tokens) + ] + + engine_core = MockEngineCore( + tokens_list=dummy_test_vectors.generation_tokens, + request_ids=[req.request_id for req in requests], + ) + for request, prompt in zip(requests, dummy_test_vectors.prompt_strings): + output_processor.add_request(request, prompt) + + gen_strings: dict[str, str] = {} + total_outputs = 0 + while True: + outputs = engine_core.get_outputs() + if not outputs: + break + processed = output_processor.process_outputs(outputs) + total_outputs += len(processed.request_outputs) + for ro in processed.request_outputs: + gen_strings.setdefault(ro.request_id, "") + gen_strings[ro.request_id] += ro.outputs[0].text + + # Final text must always be correct regardless of interval. + for idx, ref in enumerate(dummy_test_vectors.generation_strings): + assert gen_strings[f"request-{idx}"] == ref + + if stream_interval_ms > 0: + # With time-based batching, total outputs should be fewer than + # one-per-token since iterations are faster than the interval. + total_tokens = sum(len(t) for t in dummy_test_vectors.generation_tokens) + assert total_outputs < total_tokens + len(requests) + + +def test_per_request_stream_interval_override(dummy_test_vectors): + """Per-request stream_interval in SamplingParams overrides global.""" + # Global: no batching (stream_interval=1) + output_processor = OutputProcessor( + dummy_test_vectors.tokenizer, + log_stats=False, + stream_interval=1, + stream_interval_ms=0, + ) + + per_request_interval = 5 + requests = [ + EngineCoreRequest( + request_id=f"request-{idx}-int", + external_req_id=f"request-{idx}", + prompt_token_ids=prompt_tokens, + mm_features=None, + eos_token_id=None, + arrival_time=0, + lora_request=None, + cache_salt=None, + data_parallel_rank=None, + sampling_params=SamplingParams( + skip_special_tokens=False, + spaces_between_special_tokens=False, + output_kind=RequestOutputKind.DELTA, + stop=[], + include_stop_str_in_output=False, + stream_interval=per_request_interval, + ), + pooling_params=None, + ) + for idx, prompt_tokens in enumerate(dummy_test_vectors.prompt_tokens) + ] + + engine_core = MockEngineCore( + tokens_list=dummy_test_vectors.generation_tokens, + request_ids=[req.request_id for req in requests], + ) + for request, prompt in zip(requests, dummy_test_vectors.prompt_strings): + output_processor.add_request(request, prompt) + + gen_strings: dict[str, str] = {} + gen_token_chunks: dict[str, list[int]] = {} + while True: + outputs = engine_core.get_outputs() + if not outputs: + break + processed = output_processor.process_outputs(outputs) + for ro in processed.request_outputs: + rid = ro.request_id + new_tokens = ro.outputs[0].token_ids + gen_strings.setdefault(rid, "") + gen_strings[rid] += ro.outputs[0].text + gen_token_chunks.setdefault(rid, []) + gen_token_chunks[rid].append(len(new_tokens)) + + # Final text must be correct. + for idx, ref in enumerate(dummy_test_vectors.generation_strings): + assert gen_strings[f"request-{idx}"] == ref + + # Each non-first, non-final emission should have >= per_request_interval tokens. + for rid, chunk_sizes in gen_token_chunks.items(): + for i, size in enumerate(chunk_sizes): + if i == 0: + assert size == 1, f"First token should emit immediately, got {size}" + elif i < len(chunk_sizes) - 1: + assert size >= per_request_interval, f"{size=}, {per_request_interval=}" + + +def test_both_intervals_whichever_first(dummy_test_vectors): + """When both stream_interval and stream_interval_ms are set, + whichever threshold is reached first triggers emission.""" + output_processor = OutputProcessor( + dummy_test_vectors.tokenizer, + log_stats=False, + stream_interval=100, # very high token threshold (won't trigger) + stream_interval_ms=1, # very low time threshold (triggers fast) + ) + + request = EngineCoreRequest( + request_id="request-0-int", + external_req_id="request-0", + prompt_token_ids=dummy_test_vectors.prompt_tokens[0], + mm_features=None, + eos_token_id=None, + arrival_time=0, + lora_request=None, + cache_salt=None, + data_parallel_rank=None, + sampling_params=SamplingParams( + skip_special_tokens=False, + spaces_between_special_tokens=False, + output_kind=RequestOutputKind.DELTA, + stop=[], + include_stop_str_in_output=False, + ), + pooling_params=None, + ) + + engine_core = MockEngineCore( + tokens_list=[dummy_test_vectors.generation_tokens[0]], + request_ids=["request-0-int"], + ) + output_processor.add_request(request, dummy_test_vectors.prompt_strings[0]) + + gen_string = "" + output_count = 0 + while True: + outputs = engine_core.get_outputs() + if not outputs: + break + # Sleep 2ms so the 1ms time threshold fires each iteration. + time.sleep(0.002) + processed = output_processor.process_outputs(outputs) + output_count += len(processed.request_outputs) + for ro in processed.request_outputs: + gen_string += ro.outputs[0].text + + # Final text must be correct. + assert gen_string == dummy_test_vectors.generation_strings[0] + # Time threshold (1ms) fires frequently since we sleep 2ms between iterations. + # Token threshold (100) would rarely fire for short sequences. + # So we should get many outputs despite the high token threshold. + assert output_count > 2 diff --git a/vllm/config/scheduler.py b/vllm/config/scheduler.py index 5ff9fc930a56..a1ac835d0ee0 100644 --- a/vllm/config/scheduler.py +++ b/vllm/config/scheduler.py @@ -141,6 +141,11 @@ class SchedulerConfig: while a larger value (e.g., 10) reduces host overhead and may increase throughput by batching multiple tokens before sending.""" + stream_interval_ms: int = Field(default=0, ge=0) + """Time-based streaming interval in milliseconds. 0 means disabled. + When both stream_interval and stream_interval_ms are set, + whichever threshold is reached first triggers emission.""" + @staticmethod def default_factory(**kwargs): """ diff --git a/vllm/engine/arg_utils.py b/vllm/engine/arg_utils.py index 16e3dcc6708f..d1f6bc243869 100644 --- a/vllm/engine/arg_utils.py +++ b/vllm/engine/arg_utils.py @@ -572,6 +572,7 @@ class EngineArgs: async_scheduling: bool | None = SchedulerConfig.async_scheduling stream_interval: int = SchedulerConfig.stream_interval + stream_interval_ms: int = SchedulerConfig.stream_interval_ms kv_sharing_fast_prefill: bool = CacheConfig.kv_sharing_fast_prefill optimization_level: OptimizationLevel = VllmConfig.optimization_level @@ -1134,6 +1135,9 @@ def add_cli_args(parser: FlexibleArgumentParser) -> FlexibleArgumentParser: scheduler_group.add_argument( "--stream-interval", **scheduler_kwargs["stream_interval"] ) + scheduler_group.add_argument( + "--stream-interval-ms", **scheduler_kwargs["stream_interval_ms"] + ) # Compilation arguments compilation_kwargs = get_kwargs(CompilationConfig) @@ -1651,6 +1655,7 @@ def create_engine_config( disable_hybrid_kv_cache_manager=self.disable_hybrid_kv_cache_manager, async_scheduling=self.async_scheduling, stream_interval=self.stream_interval, + stream_interval_ms=self.stream_interval_ms, ) if not model_config.is_multimodal_model and self.default_mm_loras: diff --git a/vllm/entrypoints/openai/chat_completion/serving.py b/vllm/entrypoints/openai/chat_completion/serving.py index 265cee554db6..336994c82a5b 100644 --- a/vllm/entrypoints/openai/chat_completion/serving.py +++ b/vllm/entrypoints/openai/chat_completion/serving.py @@ -401,6 +401,16 @@ async def create_chat_completion( sampling_params, ) + if request.stream and request.stream_options: + if request.stream_options.stream_interval is not None: + sampling_params.stream_interval = ( + request.stream_options.stream_interval + ) + if request.stream_options.stream_interval_ms is not None: + sampling_params.stream_interval_ms = ( + request.stream_options.stream_interval_ms + ) + self._log_inputs( sub_request_id, engine_prompt, diff --git a/vllm/entrypoints/openai/completion/serving.py b/vllm/entrypoints/openai/completion/serving.py index 92156c7f2416..3c7eb8e89077 100644 --- a/vllm/entrypoints/openai/completion/serving.py +++ b/vllm/entrypoints/openai/completion/serving.py @@ -200,6 +200,16 @@ async def create_completion( sampling_params, ) + if request.stream and request.stream_options: + if request.stream_options.stream_interval is not None: + sampling_params.stream_interval = ( + request.stream_options.stream_interval + ) + if request.stream_options.stream_interval_ms is not None: + sampling_params.stream_interval_ms = ( + request.stream_options.stream_interval_ms + ) + request_id_item = f"{request_id}-{i}" self._log_inputs( diff --git a/vllm/entrypoints/openai/engine/protocol.py b/vllm/entrypoints/openai/engine/protocol.py index e64cfd1c5e4e..8c6f27d4d302 100644 --- a/vllm/entrypoints/openai/engine/protocol.py +++ b/vllm/entrypoints/openai/engine/protocol.py @@ -162,6 +162,8 @@ class ResponseFormat(OpenAIBaseModel): class StreamOptions(OpenAIBaseModel): include_usage: bool | None = True continuous_usage_stats: bool | None = False + stream_interval: int | None = None + stream_interval_ms: int | None = None class FunctionDefinition(OpenAIBaseModel): diff --git a/vllm/sampling_params.py b/vllm/sampling_params.py index 1d097852e194..c6b25ee11edf 100644 --- a/vllm/sampling_params.py +++ b/vllm/sampling_params.py @@ -243,6 +243,14 @@ class SamplingParams( implementations, plugins, etc. Not used by any in-tree sampling implementations.""" + # Per-request stream interval overrides + stream_interval: int | None = None + """Per-request token-count stream interval override. Overrides the + global --stream-interval when set.""" + stream_interval_ms: int | None = None + """Per-request time-based stream interval in milliseconds. Overrides + the global --stream-interval-ms when set.""" + # Fields used for bad words bad_words: list[str] | None = None """Words that are not allowed to be generated. More precisely, only the diff --git a/vllm/v1/engine/async_llm.py b/vllm/v1/engine/async_llm.py index 2fba48ab0ad6..1d1cadb7ef1f 100644 --- a/vllm/v1/engine/async_llm.py +++ b/vllm/v1/engine/async_llm.py @@ -145,6 +145,7 @@ def __init__( self.tokenizer, log_stats=self.log_stats, stream_interval=self.vllm_config.scheduler_config.stream_interval, + stream_interval_ms=self.vllm_config.scheduler_config.stream_interval_ms, ) endpoint = self.observability_config.otlp_traces_endpoint if endpoint is not None: diff --git a/vllm/v1/engine/llm_engine.py b/vllm/v1/engine/llm_engine.py index 5811e94dd3cc..186a5ba5bb22 100644 --- a/vllm/v1/engine/llm_engine.py +++ b/vllm/v1/engine/llm_engine.py @@ -96,6 +96,7 @@ def __init__( self.tokenizer, log_stats=self.log_stats, stream_interval=self.vllm_config.scheduler_config.stream_interval, + stream_interval_ms=self.vllm_config.scheduler_config.stream_interval_ms, ) endpoint = self.observability_config.otlp_traces_endpoint if endpoint is not None: diff --git a/vllm/v1/engine/output_processor.py b/vllm/v1/engine/output_processor.py index c497468bbd3e..1ecb87bca614 100644 --- a/vllm/v1/engine/output_processor.py +++ b/vllm/v1/engine/output_processor.py @@ -2,6 +2,7 @@ # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import asyncio +import time from collections import defaultdict, deque from collections.abc import Iterable from dataclasses import dataclass @@ -140,6 +141,7 @@ def __init__( queue: RequestOutputCollector | None, log_stats: bool, stream_interval: int, + stream_interval_ms: int = 0, top_p: float | None = None, n: int | None = None, temperature: float | None = None, @@ -172,7 +174,9 @@ def __init__( # Stream Interval self.stream_interval = stream_interval + self.stream_interval_ms = stream_interval_ms self.sent_tokens_offset = 0 # Offset of sent tokens + self.last_emit_time: float = 0.0 # Streaming input queue self.streaming_input = stream_input @@ -210,7 +214,11 @@ def from_new_request( queue: RequestOutputCollector | None, log_stats: bool, stream_interval: int, + stream_interval_ms: int = 0, ) -> "RequestState": + # Per-request overrides (from SamplingParams) with global fallback + effective_stream_interval = stream_interval + effective_stream_interval_ms = stream_interval_ms if sampling_params := request.sampling_params: if not sampling_params.detokenize: tokenizer = None @@ -227,6 +235,10 @@ def from_new_request( top_p = sampling_params.top_p n = sampling_params.n temperature = sampling_params.temperature + if sampling_params.stream_interval is not None: + effective_stream_interval = sampling_params.stream_interval + if sampling_params.stream_interval_ms is not None: + effective_stream_interval_ms = sampling_params.stream_interval_ms else: logprobs_processor = None detokenizer = None @@ -257,7 +269,8 @@ def from_new_request( arrival_time=request.arrival_time, queue=queue, log_stats=log_stats, - stream_interval=stream_interval, + stream_interval=effective_stream_interval, + stream_interval_ms=effective_stream_interval_ms, stream_input=request.resumable, ) @@ -277,20 +290,39 @@ def make_request_output( # Only the final output is required in FINAL_ONLY mode. return None - if self.stream_interval > 1: + has_token_interval = self.stream_interval > 1 + has_time_interval = self.stream_interval_ms > 0 + + if has_token_interval or has_time_interval: assert self.detokenizer is not None - # Send output request only when - # 1. It has finished, or - # 2. It is the first token, or - # 3. It has reached the stream interval number of tokens - if not ( - finished - or self.sent_tokens_offset == 0 - or len(self.detokenizer.output_token_ids) - self.sent_tokens_offset - >= self.stream_interval - ): - return None + if finished or self.sent_tokens_offset == 0: + # Always emit on finish or first token + self.last_emit_time = time.monotonic() + else: + token_ok = ( + has_token_interval + and len(self.detokenizer.output_token_ids) - self.sent_tokens_offset + >= self.stream_interval + ) + time_ok = ( + has_time_interval + and (time.monotonic() - self.last_emit_time) * 1000 + >= self.stream_interval_ms + ) + + # When both are configured, emit on whichever comes first. + # When only one is configured, wait for that one. + if has_token_interval and has_time_interval: + should_emit = token_ok or time_ok + elif has_token_interval: + should_emit = token_ok + else: + should_emit = time_ok + + if not should_emit: + return None + self.last_emit_time = time.monotonic() if self.output_kind == RequestOutputKind.DELTA: # Send tokens from the offset in DELTA mode, otherwise all @@ -414,10 +446,12 @@ def __init__( tokenizer: TokenizerLike | None, log_stats: bool, stream_interval: int = 1, + stream_interval_ms: int = 0, ): self.log_stats = log_stats self.tokenizer = tokenizer self.stream_interval = stream_interval + self.stream_interval_ms = stream_interval_ms self.request_states: dict[str, RequestState] = {} self.parent_requests: dict[str, ParentRequest] = {} self.external_req_ids: defaultdict[str, list[str]] = defaultdict(list) @@ -531,6 +565,7 @@ def add_request( queue=queue, log_stats=self.log_stats, stream_interval=self.stream_interval, + stream_interval_ms=self.stream_interval_ms, ) if self._requests_drained.is_set(): self._requests_drained.clear()