Merge remote-tracking branch 'upstream/main' into patches

Signed-off-by: MOVZX <movzx@yahoo.com>
This commit is contained in:
2026-09-29 12:54:18 +07:00
264 changed files with 13095 additions and 1541 deletions
+3 -3
View File
@@ -41,7 +41,7 @@ class RequestQueue(ABC):
pass
@abstractmethod
def prepend_requests(self, requests: "RequestQueue") -> None:
def prepend_requests(self, requests: Iterable[Request]) -> None:
"""Prepend all requests from another queue to the front of this
queue."""
pass
@@ -93,7 +93,7 @@ class FCFSRequestQueue(deque[Request], RequestQueue):
"""Prepend a request to the front of the queue."""
self.appendleft(request)
def prepend_requests(self, requests: RequestQueue) -> None:
def prepend_requests(self, requests: Iterable[Request]) -> None:
"""Prepend all requests from another queue to the front of this
queue.
@@ -163,7 +163,7 @@ class PriorityRequestQueue(RequestQueue):
front. Requests are ordered by (priority, arrival_time)."""
self.add_request(request)
def prepend_requests(self, requests: RequestQueue) -> None:
def prepend_requests(self, requests: Iterable[Request]) -> None:
"""Add all requests from another queue according to priority policy.
Note: In a priority queue, there is no concept of prepending to the
+118 -99
View File
@@ -210,8 +210,13 @@ class Scheduler(SchedulerInterface):
) from e
# Priority queues for requests.
self.waiting = create_request_queue(self.policy)
# requests skipped in waiting flow due async deps or constraints.
self.skipped_waiting = create_request_queue(self.policy)
# Waiting requests that hold KV blocks are always drained before
# self.waiting: a block-holder must never sit behind a request whose
# failed allocation would stop the scheduling scan.
self.kv_holding_waiting = create_request_queue(self.policy)
# Waiting requests that are deferred, i.e. were skipped by the scheduling
# scan or enqueued in a blocked status.
self.deferred_waiting: set[Request] = set()
self.running: list[Request] = []
# The request IDs that are finished in between the previous and the
@@ -606,9 +611,8 @@ class Scheduler(SchedulerInterface):
# `long_prefill_token_threshold` exists to stop a long prefill from
# starving other requests of the token budget. When it is the only
# request there is nobody to starve, so let it use the whole budget.
num_eligible_reqs = (
len(self.running) + len(self.waiting) + len(self.skipped_waiting)
)
num_running, num_waiting = self.get_request_counts()
num_eligible_reqs = num_running + num_waiting
long_prefill_token_threshold = (
self.scheduler_config.long_prefill_token_threshold
if num_eligible_reqs > 1
@@ -867,10 +871,21 @@ class Scheduler(SchedulerInterface):
# Next, schedule the WAITING requests.
if not preempted_reqs and self._pause_state == PauseState.UNPAUSED:
step_skipped_waiting = create_request_queue(self.policy)
step_skipped_waiting: deque[Request] = deque()
step_skipped_kv_holding: deque[Request] = deque()
while (self.waiting or self.skipped_waiting) and token_budget > 0:
if input_budget <= draft_slots:
def skip_request(from_queue: RequestQueue) -> None:
request_to_skip = from_queue.pop_request()
self.deferred_waiting.add(request_to_skip)
if self._holds_kv_blocks(request_to_skip):
step_skipped_kv_holding.appendleft(request_to_skip)
else:
step_skipped_waiting.appendleft(request_to_skip)
while token_budget > 0:
# Requests holding KV blocks are always drained first.
request_queue = self.kv_holding_waiting or self.waiting
if not request_queue or input_budget <= draft_slots:
break
# Paused streaming sessions (WAITING_FOR_STREAMING_REQ) are not
# in `running` but still hold a model-runner request slot.
@@ -878,38 +893,22 @@ class Scheduler(SchedulerInterface):
if num_running >= self.max_num_active_reqs:
break
request_queue = self._select_waiting_queue_for_scheduling()
assert request_queue is not None
request = request_queue.peek_request()
request_id = request.request_id
# try to promote blocked statuses while traversing skipped queue.
if self._is_blocked_waiting_status(
request.status
) and not self._try_promote_blocked_waiting_request(request):
if request.status == RequestStatus.WAITING_FOR_REMOTE_KVS:
logger.debug(
"%s is still in WAITING_FOR_REMOTE_KVS state.",
request_id,
)
request_queue.pop_request()
step_skipped_waiting.prepend_request(request)
ready_to_schedule = self._handle_blocked_waiting_request(request)
if not ready_to_schedule:
skip_request(request_queue)
continue
if (
request.num_stale_output_tokens > 0
and not request.drop_stale_output
):
if request.num_stale_output_tokens and not request.drop_stale_output:
# Deliverable stale output still in flight: resuming now
# could resample a position that output later delivers.
# It drains within the pipeline depth.
request_queue.pop_request()
step_skipped_waiting.prepend_request(request)
skip_request(request_queue)
continue
# Check that adding the request still respects the max_loras
# constraint.
# Check that adding the request still respects the max_loras constraint.
if (
self.lora_config
and request.lora_request
@@ -919,8 +918,7 @@ class Scheduler(SchedulerInterface):
)
):
# Scheduling would exceed max_loras, skip.
request_queue.pop_request()
step_skipped_waiting.prepend_request(request)
skip_request(request_queue)
continue
num_external_computed_tokens = 0
@@ -959,8 +957,7 @@ class Scheduler(SchedulerInterface):
# The request cannot be scheduled because
# the KVConnector couldn't determine
# the number of matched tokens.
request_queue.pop_request()
step_skipped_waiting.prepend_request(request)
skip_request(request_queue)
continue
if self.prefix_replay_tokens:
@@ -1030,8 +1027,7 @@ class Scheduler(SchedulerInterface):
# Skip request with pending mm encoding prefetches
if self._ec_transfer_pending(request, num_computed_tokens):
request_queue.pop_request()
step_skipped_waiting.prepend_request(request)
skip_request(request_queue)
continue
# Track first scheduled prefill, not post-preemption repeat prefills
@@ -1052,8 +1048,7 @@ class Scheduler(SchedulerInterface):
num_computed_tokens = request.num_computed_tokens
if self._ec_transfer_pending(request, num_computed_tokens):
request_queue.pop_request()
step_skipped_waiting.prepend_request(request)
skip_request(request_queue)
continue
encoder_inputs_to_schedule = None
@@ -1260,12 +1255,10 @@ class Scheduler(SchedulerInterface):
request, num_new_local_computed_tokens
)
request = request_queue.pop_request()
if load_kv_async:
# If loading async, allocate memory and put request
# into the WAITING_FOR_REMOTE_KV state.
request.status = RequestStatus.WAITING_FOR_REMOTE_KVS
step_skipped_waiting.prepend_request(request)
# Set num_computed_tokens even though KVs are not yet loaded.
# request.num_computed_tokens will not be used anywhere until
# the request finished the KV transfer.
@@ -1286,13 +1279,16 @@ class Scheduler(SchedulerInterface):
# overwrite; the zeroing could race the write.
self._skip_zero_block_ids.update(
self.kv_cache_manager.get_zeroing_block_ids_in_range(
request.request_id,
request_id,
num_new_local_computed_tokens,
num_computed_tokens,
)
)
skip_request(request_queue)
continue
request = request_queue.pop_request()
self.deferred_waiting.discard(request)
self.running.append(request)
if num_external_computed_tokens > 0:
# load_kv_async is False here
@@ -1343,13 +1339,16 @@ class Scheduler(SchedulerInterface):
self.ec_connector.update_state_after_alloc(request, i)
# re-queue requests skipped in this pass ahead of older skipped items.
if step_skipped_kv_holding:
self.kv_holding_waiting.prepend_requests(step_skipped_kv_holding)
if step_skipped_waiting:
self.skipped_waiting.prepend_requests(step_skipped_waiting)
self.waiting.prepend_requests(step_skipped_waiting)
# DP prefill balancing: on a step that admitted prefills (release),
# record whether it was capacity-bound.
if not defer_prefills:
self.prefill_capacity_bound = bool(self.waiting)
_, num_waiting = self.get_request_counts()
self.prefill_capacity_bound = num_waiting > len(self.deferred_waiting)
# Check if the scheduling constraints are satisfied.
total_num_scheduled_tokens = sum(num_scheduled_tokens.values())
@@ -1649,6 +1648,7 @@ class Scheduler(SchedulerInterface):
session.num_prompt_tokens = len(session.prompt_token_ids)
session.arrival_time = update.arrival_time
session.sampling_params = update.sampling_params
session.max_tokens = update.max_tokens
if session.status == RequestStatus.WAITING_FOR_STREAMING_REQ:
self.num_waiting_for_streaming_input -= 1
session.status = RequestStatus.WAITING
@@ -1972,6 +1972,9 @@ class Scheduler(SchedulerInterface):
sampled_token_ids = model_runner_output.sampled_token_ids
logprobs = model_runner_output.logprobs
prompt_logprobs_dict = model_runner_output.prompt_logprobs_dict
prompt_token_id_logprobs_dict = (
model_runner_output.prompt_token_id_logprobs_dict
)
num_scheduled_tokens = scheduler_output.num_scheduled_tokens
pooler_outputs = model_runner_output.pooler_output
num_nans_in_logits = model_runner_output.num_nans_in_logits
@@ -2149,6 +2152,15 @@ class Scheduler(SchedulerInterface):
self.kv_cache_manager.estimate_cached_tokens(request)
)
# Extract sample logprobs before stop handling can replace the
# sampling parameters for a streaming continuation.
if (
request.sampling_params is not None
and request.sampling_params.num_logprobs is not None
and logprobs
):
new_logprobs = logprobs.slice_request(req_index, len(new_token_ids))
finish_reason = None
if stopped:
# Capture finish_reason BEFORE _handle_stopped_request, which may
@@ -2174,14 +2186,6 @@ class Scheduler(SchedulerInterface):
else:
stopped_preempted_reqs.add(request)
# Extract sample logprobs if needed.
if (
request.sampling_params is not None
and request.sampling_params.num_logprobs is not None
and logprobs
):
new_logprobs = logprobs.slice_request(req_index, len(new_token_ids))
if self.return_sampling_mask:
sampling_masks = model_runner_output.sampling_masks
if new_token_ids and sampling_masks is not None:
@@ -2194,6 +2198,7 @@ class Scheduler(SchedulerInterface):
# Get prompt logprobs for this request.
prompt_logprobs_tensors = prompt_logprobs_dict.get(req_id)
prompt_token_id_logprobs = prompt_token_id_logprobs_dict.get(req_id)
if should_emit_output:
# Add EngineCoreOutput for this Request.
outputs[request.client_index].append(
@@ -2204,6 +2209,7 @@ class Scheduler(SchedulerInterface):
new_logprobs=new_logprobs,
new_sampling_mask=new_sampling_mask,
new_prompt_logprobs_tensors=prompt_logprobs_tensors,
prompt_token_id_logprobs=prompt_token_id_logprobs,
pooling_output=pooler_output,
stop_reason=request.stop_reason,
events=request.take_events(),
@@ -2223,6 +2229,7 @@ class Scheduler(SchedulerInterface):
else:
# Invariant: EngineCore returns no partial prefill outputs.
assert not prompt_logprobs_tensors
assert prompt_token_id_logprobs is None
# Remove the stopped requests from the running and waiting queues.
if stopped_running_reqs:
@@ -2230,7 +2237,8 @@ class Scheduler(SchedulerInterface):
if stopped_preempted_reqs:
# This is a rare case and unlikely to impact performance.
self.waiting.remove_requests(stopped_preempted_reqs)
self.skipped_waiting.remove_requests(stopped_preempted_reqs)
self.kv_holding_waiting.remove_requests(stopped_preempted_reqs)
self.deferred_waiting.difference_update(stopped_preempted_reqs)
error_req_ids = set(self.grammar_compile_error_reqs)
self.grammar_compile_error_reqs.clear()
@@ -2374,29 +2382,42 @@ class Scheduler(SchedulerInterface):
RequestStatus.WAITING_FOR_STREAMING_REQ,
)
@staticmethod
def _holds_kv_blocks(request: Request) -> bool:
# Whether a request currently has kv blocks allocated.
# While always the case when status is WAITING_FOR_REMOTE_KVS
# or WAITING_FOR_STREAMING_REQ, there are such cases where it's
# WAITING or PREEMPTED.
return (
request.num_computed_tokens > 0
# num_computed_tokens is reset to 0 if kv transfer fails for requests in
# WAITING_FOR_REMOTE_KVS state, before their allocated blocks are freed.
or request.status == RequestStatus.WAITING_FOR_REMOTE_KVS
)
def _enqueue_waiting_request(self, request: Request) -> None:
if self._is_blocked_waiting_status(request.status):
self.skipped_waiting.add_request(request)
self.deferred_waiting.add(request)
if self._holds_kv_blocks(request):
self.kv_holding_waiting.add_request(request)
else:
self.waiting.add_request(request)
def _select_waiting_queue_for_scheduling(self) -> RequestQueue | None:
if self.policy == SchedulingPolicy.FCFS:
return self.skipped_waiting or self.waiting or None
# PRIORITY mode: compare queue heads when both queues are non-empty.
if self.waiting and self.skipped_waiting:
waiting_req = self.waiting.peek_request()
skipped_req = self.skipped_waiting.peek_request()
return self.waiting if waiting_req < skipped_req else self.skipped_waiting
return self.waiting or self.skipped_waiting or None
def _handle_stopped_request(self, request: Request) -> bool:
"""Return True if finished (can be False for resumable requests)."""
if not request.resumable:
return True
# Drop the finished turn's in-flight work and resume from the
# materialized frontier.
safe_frontier = request.num_computed_tokens - request.num_output_placeholders
assert safe_frontier >= 0
request.num_computed_tokens = safe_frontier
request.spec_token_ids = []
request.drop_stale_output = True
request.num_stale_output_tokens = request.num_in_flight_tokens
request.num_output_placeholders = 0
if request.streaming_queue:
update = request.streaming_queue.popleft()
if update is None:
@@ -2527,7 +2548,7 @@ class Scheduler(SchedulerInterface):
def get_request_counts(self) -> tuple[int, int]:
"""Returns (num_running_reqs, num_waiting_reqs)."""
return len(self.running), len(self.waiting) + len(self.skipped_waiting)
return len(self.running), len(self.waiting) + len(self.kv_holding_waiting)
def get_kv_cache_usage(self) -> float:
"""Returns the fraction of the KV cache currently in use (0.0-1.0)."""
@@ -2608,7 +2629,8 @@ class Scheduler(SchedulerInterface):
self.running = remove_all(self.running, running_requests_to_remove)
if waiting_requests_to_remove:
self.waiting.remove_requests(waiting_requests_to_remove)
self.skipped_waiting.remove_requests(waiting_requests_to_remove)
self.kv_holding_waiting.remove_requests(waiting_requests_to_remove)
self.deferred_waiting.difference_update(waiting_requests_to_remove)
# Second pass: set status and free requests
for request in valid_requests:
@@ -2716,14 +2738,11 @@ class Scheduler(SchedulerInterface):
def get_num_unfinished_requests(self) -> int:
if self._pause_state == PauseState.PAUSED_ALL:
return 0
num_running, num_waiting = self.get_request_counts()
if self._pause_state == PauseState.PAUSED_NEW:
return len(self.running)
num_waiting = (
len(self.waiting)
+ len(self.skipped_waiting)
- self.num_waiting_for_streaming_input
)
return num_waiting + len(self.running)
return num_running
num_waiting -= self.num_waiting_for_streaming_input
return num_waiting + num_running
def has_finished_requests(self) -> bool:
if self.finished_req_ids:
@@ -2732,10 +2751,8 @@ class Scheduler(SchedulerInterface):
return False
# Finished requests waiting on delayed connector cleanup remain in
# self.requests after they have been removed from scheduling queues.
num_in_queues = (
len(self.waiting) + len(self.skipped_waiting) + len(self.running)
)
return len(self.requests) > num_in_queues
num_running, num_waiting = self.get_request_counts()
return len(self.requests) > (num_running + num_waiting)
def has_requests(self) -> bool:
# Override the interface default to also keep the engine alive while a
@@ -2867,10 +2884,12 @@ class Scheduler(SchedulerInterface):
ec_connector_stats_payload = (
ec_connector_stats.data if ec_connector_stats else None
)
num_running, num_waiting = self.get_request_counts()
num_deferred = len(self.deferred_waiting)
return SchedulerStats(
num_running_reqs=len(self.running),
num_waiting_reqs=len(self.waiting),
num_skipped_waiting_reqs=len(self.skipped_waiting),
num_running_reqs=num_running,
num_waiting_reqs=num_waiting - num_deferred,
num_skipped_waiting_reqs=num_deferred,
kv_cache_usage=self.kv_cache_manager.usage,
prefix_cache_stats=prefix_cache_stats,
connector_prefix_cache_stats=connector_prefix_cache_stats,
@@ -3076,39 +3095,39 @@ class Scheduler(SchedulerInterface):
request.num_computed_tokens = request.num_tokens - 1
self.finished_recving_kv_req_ids.remove(request.request_id)
def _try_promote_blocked_waiting_request(self, request: Request) -> bool:
"""Try to promote a blocked waiting request back to schedulable states."""
def _handle_blocked_waiting_request(self, request: Request) -> bool:
"""Returns True if scheduling of this request should proceed, False if
it should be skipped for this step."""
if request.status == RequestStatus.WAITING_FOR_REMOTE_KVS:
# finished_recving_kv_req_ids is populated during
# update_from_output(), based on worker-side connector signals
# in KVConnectorOutput.finished_recving
if request.request_id not in self.finished_recving_kv_req_ids:
# Check whether async loading requests are finished.
request_id = request.request_id
if request_id not in self.finished_recving_kv_req_ids:
logger.debug("%s is still in WAITING_FOR_REMOTE_KVS state.", request_id)
return False
# Promote request to waiting or preempted.
self._update_waiting_for_remote_kv(request)
if request.num_preemptions:
request.status = RequestStatus.PREEMPTED
else:
request.status = RequestStatus.WAITING
return True
if request.status == RequestStatus.WAITING_FOR_STRUCTURED_OUTPUT_GRAMMAR:
structured_output_req = request.structured_output_request
if not structured_output_req or structured_output_req.grammar is None:
elif request.status == RequestStatus.WAITING_FOR_STRUCTURED_OUTPUT_GRAMMAR:
# Check whether grammar compilation has finished.
struct_output_req = request.structured_output_request
if not struct_output_req or struct_output_req.grammar is None:
return False
if isinstance(structured_output_req.grammar, Exception):
if isinstance(struct_output_req.grammar, Exception):
self.grammar_compile_error_reqs.add(request.request_id)
return False
# Grammar is ready, promote to waiting state.
request.status = RequestStatus.WAITING
return True
if request.status == RequestStatus.WAITING_FOR_STREAMING_REQ:
elif request.status == RequestStatus.WAITING_FOR_STREAMING_REQ:
# Streaming input request waiting for more input.
assert not request.streaming_queue
return False
raise AssertionError(
"Unexpected blocked waiting status in promotion: "
f"{request.status.name} for request {request.request_id}"
)
return True
def _update_from_kv_xfer_finished(self, kv_connector_output: KVConnectorOutput):
"""KV Connector: update the scheduler state based on the output.
@@ -3281,7 +3300,7 @@ class Scheduler(SchedulerInterface):
# handle async KV loads (not cached yet, evict_blocks=False)
async_load_reqs = (
req
for req in self.skipped_waiting
for req in self.kv_holding_waiting
if req.status == RequestStatus.WAITING_FOR_REMOTE_KVS
)
async_failed_req_ids, num_failed_tokens, _ = (