ADAPT-Chase commited on
Commit
180aa83
·
verified ·
1 Parent(s): 538afc9

Add files using upload-large-folder tool

Browse files
Files changed (20) hide show
  1. tool_server/.venv/lib/python3.12/site-packages/vllm/v1/attention/backends/mla/__pycache__/flashmla.cpython-312.pyc +0 -0
  2. tool_server/.venv/lib/python3.12/site-packages/vllm/v1/attention/backends/mla/__pycache__/rocm_aiter_mla.cpython-312.pyc +0 -0
  3. tool_server/.venv/lib/python3.12/site-packages/vllm/v1/attention/backends/mla/__pycache__/triton_mla.cpython-312.pyc +0 -0
  4. tool_server/.venv/lib/python3.12/site-packages/vllm/v1/core/__pycache__/__init__.cpython-312.pyc +0 -0
  5. tool_server/.venv/lib/python3.12/site-packages/vllm/v1/core/__pycache__/block_pool.cpython-312.pyc +0 -0
  6. tool_server/.venv/lib/python3.12/site-packages/vllm/v1/core/__pycache__/encoder_cache_manager.cpython-312.pyc +0 -0
  7. tool_server/.venv/lib/python3.12/site-packages/vllm/v1/core/__pycache__/kv_cache_coordinator.cpython-312.pyc +0 -0
  8. tool_server/.venv/lib/python3.12/site-packages/vllm/v1/core/__pycache__/kv_cache_manager.cpython-312.pyc +0 -0
  9. tool_server/.venv/lib/python3.12/site-packages/vllm/v1/core/__pycache__/kv_cache_utils.cpython-312.pyc +0 -0
  10. tool_server/.venv/lib/python3.12/site-packages/vllm/v1/core/__pycache__/single_type_kv_cache_manager.cpython-312.pyc +0 -0
  11. tool_server/.venv/lib/python3.12/site-packages/vllm/v1/core/sched/__init__.py +0 -0
  12. tool_server/.venv/lib/python3.12/site-packages/vllm/v1/core/sched/__pycache__/__init__.cpython-312.pyc +0 -0
  13. tool_server/.venv/lib/python3.12/site-packages/vllm/v1/core/sched/__pycache__/async_scheduler.cpython-312.pyc +0 -0
  14. tool_server/.venv/lib/python3.12/site-packages/vllm/v1/core/sched/__pycache__/interface.cpython-312.pyc +0 -0
  15. tool_server/.venv/lib/python3.12/site-packages/vllm/v1/core/sched/async_scheduler.py +47 -0
  16. tool_server/.venv/lib/python3.12/site-packages/vllm/v1/core/sched/interface.py +150 -0
  17. tool_server/.venv/lib/python3.12/site-packages/vllm/v1/core/sched/output.py +157 -0
  18. tool_server/.venv/lib/python3.12/site-packages/vllm/v1/core/sched/request_queue.py +224 -0
  19. tool_server/.venv/lib/python3.12/site-packages/vllm/v1/core/sched/scheduler.py +1161 -0
  20. tool_server/.venv/lib/python3.12/site-packages/vllm/v1/core/sched/utils.py +36 -0
tool_server/.venv/lib/python3.12/site-packages/vllm/v1/attention/backends/mla/__pycache__/flashmla.cpython-312.pyc ADDED
Binary file (8.81 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/vllm/v1/attention/backends/mla/__pycache__/rocm_aiter_mla.cpython-312.pyc ADDED
Binary file (10.8 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/vllm/v1/attention/backends/mla/__pycache__/triton_mla.cpython-312.pyc ADDED
Binary file (6.53 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/vllm/v1/core/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (182 Bytes). View file
 
tool_server/.venv/lib/python3.12/site-packages/vllm/v1/core/__pycache__/block_pool.cpython-312.pyc ADDED
Binary file (12.4 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/vllm/v1/core/__pycache__/encoder_cache_manager.cpython-312.pyc ADDED
Binary file (11.3 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/vllm/v1/core/__pycache__/kv_cache_coordinator.cpython-312.pyc ADDED
Binary file (18.1 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/vllm/v1/core/__pycache__/kv_cache_manager.cpython-312.pyc ADDED
Binary file (17.3 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/vllm/v1/core/__pycache__/kv_cache_utils.cpython-312.pyc ADDED
Binary file (45.7 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/vllm/v1/core/__pycache__/single_type_kv_cache_manager.cpython-312.pyc ADDED
Binary file (23.4 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/vllm/v1/core/sched/__init__.py ADDED
File without changes
tool_server/.venv/lib/python3.12/site-packages/vllm/v1/core/sched/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (188 Bytes). View file
 
tool_server/.venv/lib/python3.12/site-packages/vllm/v1/core/sched/__pycache__/async_scheduler.cpython-312.pyc ADDED
Binary file (2.3 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/vllm/v1/core/sched/__pycache__/interface.cpython-312.pyc ADDED
Binary file (7.43 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/vllm/v1/core/sched/async_scheduler.py ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # SPDX-FileCopyrightText: Copyright contributors to the vLLM project
3
+
4
+ from __future__ import annotations
5
+
6
+ from vllm.logger import init_logger
7
+ from vllm.v1.core.sched.output import SchedulerOutput
8
+ from vllm.v1.core.sched.scheduler import Scheduler
9
+ from vllm.v1.request import Request, RequestStatus
10
+
11
+ logger = init_logger(__name__)
12
+
13
+
14
+ class AsyncScheduler(Scheduler):
15
+
16
+ def _update_after_schedule(
17
+ self,
18
+ scheduler_output: SchedulerOutput,
19
+ ) -> None:
20
+ super()._update_after_schedule(scheduler_output)
21
+ for req_id in scheduler_output.num_scheduled_tokens:
22
+ request = self.requests[req_id]
23
+ if (request.num_computed_tokens == request.num_tokens +
24
+ request.num_output_placeholders):
25
+ # The request will generate a new token in this scheduling step.
26
+ # TODO(woosuk): Support speculative decoding.
27
+ request.num_output_placeholders += 1
28
+
29
+ def _update_request_with_output(
30
+ self,
31
+ request: Request,
32
+ new_token_ids: list[int],
33
+ ) -> tuple[list[int], bool]:
34
+ status_before_update = request.status
35
+ new_token_ids, stopped = super()._update_request_with_output(
36
+ request, new_token_ids)
37
+
38
+ # Update the number of output placeholders.
39
+ request.num_output_placeholders -= len(new_token_ids)
40
+ assert request.num_output_placeholders >= 0
41
+
42
+ # Cache the new tokens. Preempted requests should be skipped.
43
+ if status_before_update == RequestStatus.RUNNING:
44
+ self.kv_cache_manager.cache_blocks(
45
+ request,
46
+ request.num_computed_tokens - request.num_output_placeholders)
47
+ return new_token_ids, stopped
tool_server/.venv/lib/python3.12/site-packages/vllm/v1/core/sched/interface.py ADDED
@@ -0,0 +1,150 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # SPDX-FileCopyrightText: Copyright contributors to the vLLM project
3
+ from abc import ABC, abstractmethod
4
+ from collections.abc import Iterable
5
+ from typing import TYPE_CHECKING, Optional, Union
6
+
7
+ if TYPE_CHECKING:
8
+ from vllm.distributed.kv_transfer.kv_connector.v1 import KVConnectorBase_V1
9
+ from vllm.v1.core.sched.output import SchedulerOutput
10
+ from vllm.v1.engine import EngineCoreOutputs
11
+ from vllm.v1.metrics.stats import SchedulerStats
12
+ from vllm.v1.outputs import ModelRunnerOutput
13
+ from vllm.v1.request import Request, RequestStatus
14
+
15
+
16
+ class SchedulerInterface(ABC):
17
+
18
+ @abstractmethod
19
+ def schedule(self) -> "SchedulerOutput":
20
+ """Schedule the requests to process in this scheduling step.
21
+
22
+ The scheduling decision is made at the iteration level. Each scheduling
23
+ step corresponds to a single forward pass of the model. Therefore, this
24
+ method is called repeatedly by a busy loop in the engine.
25
+
26
+ Essentially, the scheduler produces a dictionary of {req_id: num_tokens}
27
+ that specifies how many tokens to process for each request in this
28
+ scheduling step. For example, num_tokens can be as large as the number
29
+ of prompt tokens for new requests, or it can be 1 for the requests that
30
+ are auto-regressively generating new tokens one by one. Otherwise, it
31
+ can be somewhere in between in case of chunked prefills, prefix caching,
32
+ speculative decoding, etc.
33
+
34
+ Additionally, the scheduler also returns useful data about each request
35
+ or the batch as a whole. The model runner will use this information in
36
+ preparing inputs to the model.
37
+
38
+ Returns:
39
+ A SchedulerOutput object containing information about the scheduled
40
+ requests.
41
+ """
42
+ raise NotImplementedError
43
+
44
+ @abstractmethod
45
+ def update_from_output(
46
+ self,
47
+ scheduler_output: "SchedulerOutput",
48
+ model_runner_output: "ModelRunnerOutput",
49
+ ) -> dict[int, "EngineCoreOutputs"]:
50
+ """Update the scheduler state based on the model runner output.
51
+
52
+ This method is called after the model runner has processed the scheduled
53
+ requests. The model runner output includes generated token ids, draft
54
+ token ids for next step, etc. The scheduler uses this information to
55
+ update its states, checks the finished requests, and returns the output
56
+ for each request.
57
+
58
+ Returns:
59
+ A dict of client index to EngineCoreOutputs object containing the
60
+ outputs for each request originating from that client.
61
+ """
62
+ raise NotImplementedError
63
+
64
+ @abstractmethod
65
+ def add_request(self, request: "Request") -> None:
66
+ """Add a new request to the scheduler's internal queue.
67
+
68
+ Args:
69
+ request: The new request being added.
70
+ """
71
+ raise NotImplementedError
72
+
73
+ @abstractmethod
74
+ def finish_requests(
75
+ self,
76
+ request_ids: Union[str, Iterable[str]],
77
+ finished_status: "RequestStatus",
78
+ ) -> None:
79
+ """Finish the requests in the scheduler's internal queue. If the request
80
+ is not in the queue, this method will do nothing.
81
+
82
+ This method is called in two cases:
83
+ 1. When the request is aborted by the client.
84
+ 2. When the frontend process detects a stop string of the request after
85
+ de-tokenizing its generated tokens.
86
+
87
+ Args:
88
+ request_ids: A single or a list of request IDs.
89
+ finished_status: The finished status of the given requests.
90
+ """
91
+ raise NotImplementedError
92
+
93
+ @abstractmethod
94
+ def get_num_unfinished_requests(self) -> int:
95
+ """Number of unfinished requests in the scheduler's internal queue."""
96
+ raise NotImplementedError
97
+
98
+ def has_unfinished_requests(self) -> bool:
99
+ """Returns True if there are unfinished requests in the scheduler's
100
+ internal queue."""
101
+ return self.get_num_unfinished_requests() > 0
102
+
103
+ @abstractmethod
104
+ def has_finished_requests(self) -> bool:
105
+ """Returns True if there are finished requests that need to be cleared.
106
+ NOTE: This is different from `not self.has_unfinished_requests()`.
107
+
108
+ The scheduler maintains an internal list of the requests finished in the
109
+ previous step. This list is returned from the next call to schedule(),
110
+ to be sent to the model runner in the next step to clear cached states
111
+ for these finished requests.
112
+
113
+ This method checks if this internal list of finished requests is
114
+ non-empty. This information is useful for DP attention.
115
+ """
116
+ raise NotImplementedError
117
+
118
+ def has_requests(self) -> bool:
119
+ """Returns True if there are unfinished requests, or finished requests
120
+ not yet returned in SchedulerOutputs."""
121
+ return self.has_unfinished_requests() or self.has_finished_requests()
122
+
123
+ @abstractmethod
124
+ def reset_prefix_cache(self) -> bool:
125
+ """Reset the prefix cache for KV cache.
126
+
127
+ This is particularly required when the model weights are live-updated.
128
+ """
129
+ raise NotImplementedError
130
+
131
+ @abstractmethod
132
+ def get_request_counts(self) -> tuple[int, int]:
133
+ """Returns (num_running_reqs, num_waiting_reqs)."""
134
+ raise NotImplementedError
135
+
136
+ @abstractmethod
137
+ def make_stats(self) -> Optional["SchedulerStats"]:
138
+ """Make a SchedulerStats object for logging.
139
+
140
+ The SchedulerStats object is created for every scheduling step.
141
+ """
142
+ raise NotImplementedError
143
+
144
+ @abstractmethod
145
+ def shutdown(self) -> None:
146
+ """Shutdown the scheduler."""
147
+ raise NotImplementedError
148
+
149
+ def get_kv_connector(self) -> Optional["KVConnectorBase_V1"]:
150
+ return None
tool_server/.venv/lib/python3.12/site-packages/vllm/v1/core/sched/output.py ADDED
@@ -0,0 +1,157 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # SPDX-FileCopyrightText: Copyright contributors to the vLLM project
3
+
4
+ from __future__ import annotations
5
+
6
+ from dataclasses import dataclass
7
+ from typing import TYPE_CHECKING, Optional
8
+
9
+ if TYPE_CHECKING:
10
+ import numpy as np
11
+ import numpy.typing as npt
12
+
13
+ from vllm.distributed.kv_transfer.kv_connector.v1.base import (
14
+ KVConnectorMetadata)
15
+ from vllm.lora.request import LoRARequest
16
+ from vllm.multimodal.inputs import MultiModalKwargsItem, PlaceholderRange
17
+ from vllm.pooling_params import PoolingParams
18
+ from vllm.sampling_params import SamplingParams
19
+ from vllm.v1.request import Request
20
+
21
+
22
+ @dataclass
23
+ class NewRequestData:
24
+
25
+ req_id: str
26
+ prompt_token_ids: list[int]
27
+ mm_kwargs: list[MultiModalKwargsItem]
28
+ mm_hashes: list[str]
29
+ mm_positions: list[PlaceholderRange]
30
+ sampling_params: Optional[SamplingParams]
31
+ pooling_params: Optional[PoolingParams]
32
+ block_ids: tuple[list[int], ...]
33
+ num_computed_tokens: int
34
+ lora_request: Optional[LoRARequest]
35
+
36
+ @classmethod
37
+ def from_request(
38
+ cls,
39
+ request: Request,
40
+ block_ids: tuple[list[int], ...],
41
+ ) -> NewRequestData:
42
+ return cls(
43
+ req_id=request.request_id,
44
+ prompt_token_ids=request.prompt_token_ids,
45
+ mm_kwargs=request.mm_kwargs,
46
+ mm_hashes=request.mm_hashes,
47
+ mm_positions=request.mm_positions,
48
+ sampling_params=request.sampling_params,
49
+ pooling_params=request.pooling_params,
50
+ block_ids=block_ids,
51
+ num_computed_tokens=request.num_computed_tokens,
52
+ lora_request=request.lora_request,
53
+ )
54
+
55
+ def __repr__(self):
56
+ return (f"NewRequestData("
57
+ f"req_id={self.req_id},"
58
+ f"prompt_token_ids={self.prompt_token_ids},"
59
+ f"mm_kwargs={self.mm_kwargs},"
60
+ f"mm_hashes={self.mm_hashes},"
61
+ f"mm_positions={self.mm_positions},"
62
+ f"sampling_params={self.sampling_params},"
63
+ f"block_ids={self.block_ids},"
64
+ f"num_computed_tokens={self.num_computed_tokens},"
65
+ f"lora_request={self.lora_request}"
66
+ ")")
67
+
68
+ # Version of __repr__ with the prompt data obfuscated
69
+ def anon_repr(self):
70
+ return (f"NewRequestData("
71
+ f"req_id={self.req_id},"
72
+ f"prompt_token_ids_len={len(self.prompt_token_ids)},"
73
+ f"mm_kwargs={self.mm_kwargs},"
74
+ f"mm_hashes={self.mm_hashes},"
75
+ f"mm_positions={self.mm_positions},"
76
+ f"sampling_params={self.sampling_params},"
77
+ f"block_ids={self.block_ids},"
78
+ f"num_computed_tokens={self.num_computed_tokens},"
79
+ f"lora_request={self.lora_request}"
80
+ ")")
81
+
82
+
83
+ @dataclass
84
+ class CachedRequestData:
85
+
86
+ req_ids: list[str]
87
+ # If resumed_from_preemption is False, new_block_ids will be appended to
88
+ # the request's block IDs. If True, new_block_ids will be used as the
89
+ # request's block IDs instead of appending to the existing block IDs.
90
+ resumed_from_preemption: list[bool]
91
+ # NOTE(woosuk): new_token_ids is only used for pipeline parallelism.
92
+ # When PP is not used, new_token_ids will be empty.
93
+ new_token_ids: list[list[int]]
94
+ new_block_ids: list[tuple[list[int], ...]]
95
+ num_computed_tokens: list[int]
96
+
97
+ @property
98
+ def num_reqs(self) -> int:
99
+ return len(self.req_ids)
100
+
101
+ @classmethod
102
+ def make_empty(cls) -> CachedRequestData:
103
+ return cls(
104
+ req_ids=[],
105
+ resumed_from_preemption=[],
106
+ new_token_ids=[],
107
+ new_block_ids=[],
108
+ num_computed_tokens=[],
109
+ )
110
+
111
+
112
+ @dataclass
113
+ class SchedulerOutput:
114
+
115
+ # list of the requests that are scheduled for the first time.
116
+ # We cache the request's data in each worker process, so that we don't
117
+ # need to re-send it every scheduling step.
118
+ scheduled_new_reqs: list[NewRequestData]
119
+ # list of the requests that have been scheduled before.
120
+ # Since the request's data is already cached in the worker processes,
121
+ # we only send the diff to minimize the communication cost.
122
+ scheduled_cached_reqs: CachedRequestData
123
+
124
+ # req_id -> num_scheduled_tokens
125
+ # Number of tokens scheduled for each request.
126
+ num_scheduled_tokens: dict[str, int]
127
+ # Total number of tokens scheduled for all requests.
128
+ # Equal to sum(num_scheduled_tokens.values())
129
+ total_num_scheduled_tokens: int
130
+ # req_id -> spec_token_ids
131
+ # If a request does not have any spec decode tokens, it will not be
132
+ # included in the dictionary.
133
+ scheduled_spec_decode_tokens: dict[str, list[int]]
134
+ # req_id -> encoder input indices that need processing.
135
+ # E.g., if a request has [0, 1], it could mean the vision encoder needs
136
+ # to process that the request's 0-th and 1-th images in the current step.
137
+ scheduled_encoder_inputs: dict[str, list[int]]
138
+ # Number of common prefix blocks for all requests in each KV cache group.
139
+ # This can be used for cascade attention.
140
+ num_common_prefix_blocks: list[int]
141
+
142
+ # Request IDs that are finished in between the previous and the current
143
+ # steps. This is used to notify the workers about the finished requests
144
+ # so that they can free the cached states for those requests.
145
+ finished_req_ids: set[str]
146
+ # list of (req_id, encoder_input_index) tuples.
147
+ # Used to free the encoder cache.
148
+ free_encoder_input_ids: list[tuple[str, int]]
149
+
150
+ # Dict of request ids to their index within the batch
151
+ # for filling the next token bitmask
152
+ structured_output_request_ids: dict[str, int]
153
+ # the bitmask for the whole batch
154
+ grammar_bitmask: Optional[npt.NDArray[np.int32]]
155
+
156
+ # KV Cache Connector metadata.
157
+ kv_connector_metadata: Optional[KVConnectorMetadata] = None
tool_server/.venv/lib/python3.12/site-packages/vllm/v1/core/sched/request_queue.py ADDED
@@ -0,0 +1,224 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # SPDX-FileCopyrightText: Copyright contributors to the vLLM project
3
+
4
+ from __future__ import annotations
5
+
6
+ import heapq
7
+ from abc import ABC, abstractmethod
8
+ from collections import deque
9
+ from collections.abc import Iterable, Iterator
10
+ from enum import Enum
11
+
12
+ from vllm.v1.request import Request
13
+
14
+
15
+ class SchedulingPolicy(Enum):
16
+ """Enum for scheduling policies."""
17
+ FCFS = "fcfs"
18
+ PRIORITY = "priority"
19
+
20
+
21
+ class RequestQueue(ABC):
22
+ """Abstract base class for request queues."""
23
+
24
+ @abstractmethod
25
+ def add_request(self, request: Request) -> None:
26
+ """Add a request to the queue according to the policy."""
27
+ pass
28
+
29
+ @abstractmethod
30
+ def pop_request(self) -> Request:
31
+ """Pop a request from the queue according to the policy."""
32
+ pass
33
+
34
+ @abstractmethod
35
+ def peek_request(self) -> Request:
36
+ """Peek at the request at the front of the queue without removing it."""
37
+ pass
38
+
39
+ @abstractmethod
40
+ def prepend_request(self, request: Request) -> None:
41
+ """Prepend a request to the front of the queue."""
42
+ pass
43
+
44
+ @abstractmethod
45
+ def prepend_requests(self, requests: RequestQueue) -> None:
46
+ """Prepend all requests from another queue to the front of this
47
+ queue."""
48
+ pass
49
+
50
+ @abstractmethod
51
+ def remove_request(self, request: Request) -> None:
52
+ """Remove a specific request from the queue."""
53
+ pass
54
+
55
+ @abstractmethod
56
+ def remove_requests(self, requests: Iterable[Request]) -> None:
57
+ """Remove multiple specific requests from the queue."""
58
+ pass
59
+
60
+ @abstractmethod
61
+ def __bool__(self) -> bool:
62
+ """Check if queue has any requests."""
63
+ pass
64
+
65
+ @abstractmethod
66
+ def __len__(self) -> int:
67
+ """Get number of requests in queue."""
68
+ pass
69
+
70
+ @abstractmethod
71
+ def __iter__(self) -> Iterator[Request]:
72
+ """Iterate over the queue according to the policy."""
73
+ pass
74
+
75
+ @abstractmethod
76
+ def __reversed__(self) -> Iterator[Request]:
77
+ """Iterate over the queue in reverse order."""
78
+ pass
79
+
80
+
81
+ class FCFSRequestQueue(deque[Request], RequestQueue):
82
+ """A first-come-first-served queue that supports deque operations."""
83
+
84
+ def add_request(self, request: Request) -> None:
85
+ """Add a request to the queue according to FCFS policy."""
86
+ self.append(request)
87
+
88
+ def pop_request(self) -> Request:
89
+ """Pop a request from the queue according to FCFS policy."""
90
+ return self.popleft()
91
+
92
+ def peek_request(self) -> Request:
93
+ """Peek at the next request in the queue without removing it."""
94
+ if not self:
95
+ raise IndexError("peek from an empty queue")
96
+ return self[0]
97
+
98
+ def prepend_request(self, request: Request) -> None:
99
+ """Prepend a request to the front of the queue."""
100
+ self.appendleft(request)
101
+
102
+ def prepend_requests(self, requests: RequestQueue) -> None:
103
+ """Prepend all requests from another queue to the front of this
104
+ queue."""
105
+ self.extendleft(reversed(requests))
106
+
107
+ def remove_request(self, request: Request) -> None:
108
+ """Remove a specific request from the queue."""
109
+ self.remove(request)
110
+
111
+ def remove_requests(self, requests: Iterable[Request]) -> None:
112
+ """Remove multiple specific requests from the queue."""
113
+ requests_to_remove = set(requests)
114
+ filtered_requests = [
115
+ req for req in self if req not in requests_to_remove
116
+ ]
117
+ # deque does not support in-place filtering, so we need to clear
118
+ # and extend
119
+ self.clear()
120
+ self.extend(filtered_requests)
121
+
122
+ def __bool__(self) -> bool:
123
+ """Check if queue has any requests."""
124
+ return len(self) > 0
125
+
126
+ def __len__(self) -> int:
127
+ """Get number of requests in queue."""
128
+ return super().__len__()
129
+
130
+ def __iter__(self) -> Iterator[Request]:
131
+ """Iterate over the queue according to FCFS policy."""
132
+ return super().__iter__()
133
+
134
+ def __reversed__(self) -> Iterator[Request]:
135
+ """Iterate over the queue in reverse order."""
136
+ return super().__reversed__()
137
+
138
+
139
+ class PriorityRequestQueue(RequestQueue):
140
+ """
141
+ A priority queue that supports heap operations.
142
+
143
+ Requests with a smaller value of `priority` are processed first.
144
+ If multiple requests have the same priority, the one with the earlier
145
+ `arrival_time` is processed first.
146
+ """
147
+
148
+ def __init__(self) -> None:
149
+ self._heap: list[tuple[int, float, Request]] = []
150
+
151
+ def add_request(self, request: Request) -> None:
152
+ """Add a request to the queue according to priority policy."""
153
+ heapq.heappush(self._heap,
154
+ (request.priority, request.arrival_time, request))
155
+
156
+ def pop_request(self) -> Request:
157
+ """Pop a request from the queue according to priority policy."""
158
+ if not self._heap:
159
+ raise IndexError("pop from empty heap")
160
+ _, _, request = heapq.heappop(self._heap)
161
+ return request
162
+
163
+ def peek_request(self) -> Request:
164
+ """Peek at the next request in the queue without removing it."""
165
+ if not self._heap:
166
+ raise IndexError("peek from empty heap")
167
+ _, _, request = self._heap[0]
168
+ return request
169
+
170
+ def prepend_request(self, request: Request) -> None:
171
+ """Add a request to the queue according to priority policy.
172
+
173
+ Note: In a priority queue, there is no concept of prepending to the
174
+ front. Requests are ordered by (priority, arrival_time)."""
175
+ self.add_request(request)
176
+
177
+ def prepend_requests(self, requests: RequestQueue) -> None:
178
+ """Add all requests from another queue according to priority policy.
179
+
180
+ Note: In a priority queue, there is no concept of prepending to the
181
+ front. Requests are ordered by (priority, arrival_time)."""
182
+ for request in requests:
183
+ self.add_request(request)
184
+
185
+ def remove_request(self, request: Request) -> None:
186
+ """Remove a specific request from the queue."""
187
+ self._heap = [(p, t, r) for p, t, r in self._heap if r != request]
188
+ heapq.heapify(self._heap)
189
+
190
+ def remove_requests(self, requests: Iterable[Request]) -> None:
191
+ """Remove multiple specific requests from the queue."""
192
+ requests_to_remove = set(requests)
193
+ self._heap = [(p, t, r) for p, t, r in self._heap
194
+ if r not in requests_to_remove]
195
+ heapq.heapify(self._heap)
196
+
197
+ def __bool__(self) -> bool:
198
+ """Check if queue has any requests."""
199
+ return bool(self._heap)
200
+
201
+ def __len__(self) -> int:
202
+ """Get number of requests in queue."""
203
+ return len(self._heap)
204
+
205
+ def __iter__(self) -> Iterator[Request]:
206
+ """Iterate over the queue according to priority policy."""
207
+ heap_copy = self._heap[:]
208
+ while heap_copy:
209
+ _, _, request = heapq.heappop(heap_copy)
210
+ yield request
211
+
212
+ def __reversed__(self) -> Iterator[Request]:
213
+ """Iterate over the queue in reverse priority order."""
214
+ return reversed(list(self))
215
+
216
+
217
+ def create_request_queue(policy: SchedulingPolicy) -> RequestQueue:
218
+ """Create request queue based on scheduling policy."""
219
+ if policy == SchedulingPolicy.PRIORITY:
220
+ return PriorityRequestQueue()
221
+ elif policy == SchedulingPolicy.FCFS:
222
+ return FCFSRequestQueue()
223
+ else:
224
+ raise ValueError(f"Unknown scheduling policy: {policy}")
tool_server/.venv/lib/python3.12/site-packages/vllm/v1/core/sched/scheduler.py ADDED
@@ -0,0 +1,1161 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # SPDX-FileCopyrightText: Copyright contributors to the vLLM project
3
+
4
+ from __future__ import annotations
5
+
6
+ import itertools
7
+ import time
8
+ from collections import defaultdict
9
+ from collections.abc import Iterable
10
+ from typing import Any, Optional, Union
11
+
12
+ from vllm.config import VllmConfig
13
+ from vllm.distributed.kv_events import EventPublisherFactory, KVEventBatch
14
+ from vllm.distributed.kv_transfer.kv_connector.factory import (
15
+ KVConnectorFactory)
16
+ from vllm.distributed.kv_transfer.kv_connector.v1 import (KVConnectorBase_V1,
17
+ KVConnectorRole)
18
+ from vllm.logger import init_logger
19
+ from vllm.multimodal import MULTIMODAL_REGISTRY, MultiModalRegistry
20
+ from vllm.v1.core.encoder_cache_manager import (EncoderCacheManager,
21
+ compute_encoder_budget)
22
+ from vllm.v1.core.kv_cache_manager import KVCacheManager
23
+ from vllm.v1.core.sched.interface import SchedulerInterface
24
+ from vllm.v1.core.sched.output import (CachedRequestData, NewRequestData,
25
+ SchedulerOutput)
26
+ from vllm.v1.core.sched.request_queue import (SchedulingPolicy,
27
+ create_request_queue)
28
+ from vllm.v1.core.sched.utils import check_stop
29
+ from vllm.v1.engine import (EngineCoreEventType, EngineCoreOutput,
30
+ EngineCoreOutputs)
31
+ from vllm.v1.kv_cache_interface import KVCacheConfig
32
+ from vllm.v1.metrics.stats import SchedulerStats
33
+ from vllm.v1.outputs import KVConnectorOutput, ModelRunnerOutput
34
+ from vllm.v1.request import Request, RequestStatus
35
+ from vllm.v1.spec_decode.metrics import SpecDecodingStats
36
+ from vllm.v1.structured_output import StructuredOutputManager
37
+
38
+ logger = init_logger(__name__)
39
+
40
+
41
+ class Scheduler(SchedulerInterface):
42
+
43
+ def __init__(
44
+ self,
45
+ vllm_config: VllmConfig,
46
+ kv_cache_config: KVCacheConfig,
47
+ structured_output_manager: StructuredOutputManager,
48
+ mm_registry: MultiModalRegistry = MULTIMODAL_REGISTRY,
49
+ include_finished_set: bool = False,
50
+ log_stats: bool = False,
51
+ ) -> None:
52
+ self.vllm_config = vllm_config
53
+ self.scheduler_config = vllm_config.scheduler_config
54
+ self.cache_config = vllm_config.cache_config
55
+ self.lora_config = vllm_config.lora_config
56
+ self.kv_cache_config = kv_cache_config
57
+ self.kv_events_config = vllm_config.kv_events_config
58
+ self.parallel_config = vllm_config.parallel_config
59
+ self.log_stats = log_stats
60
+ self.structured_output_manager = structured_output_manager
61
+
62
+ # include_finished_set controls whether a separate set of finished
63
+ # request ids should be included in the EngineCoreOutputs returned
64
+ # by update_from_outputs(). This is currently used in the multi-engine
65
+ # case to track request lifetimes efficiently.
66
+ self.finished_req_ids_dict: Optional[dict[int, set[str]]] = (
67
+ defaultdict(set) if include_finished_set else None)
68
+
69
+ # Scheduling constraints.
70
+ self.max_num_running_reqs = self.scheduler_config.max_num_seqs
71
+ self.max_num_scheduled_tokens = \
72
+ self.scheduler_config.max_num_batched_tokens
73
+ self.max_model_len = self.scheduler_config.max_model_len
74
+ self.enable_kv_cache_events = (
75
+ self.kv_events_config is not None
76
+ and self.kv_events_config.enable_kv_cache_events)
77
+
78
+ # Create KVConnector for the Scheduler. Note that each Worker
79
+ # will have a corresponding KVConnector with Role=WORKER.
80
+ # KV Connector pushes/pull of remote KVs for P/D and offloading.
81
+ self.connector = None
82
+ if self.vllm_config.kv_transfer_config is not None:
83
+ assert len(self.kv_cache_config.kv_cache_groups) == 1, (
84
+ "Multiple KV cache groups are not currently supported "
85
+ "with KV connectors")
86
+ self.connector = KVConnectorFactory.create_connector(
87
+ config=self.vllm_config, role=KVConnectorRole.SCHEDULER)
88
+
89
+ self.kv_event_publisher = EventPublisherFactory.create(
90
+ self.kv_events_config,
91
+ self.parallel_config.data_parallel_rank,
92
+ )
93
+
94
+ num_gpu_blocks = self.cache_config.num_gpu_blocks
95
+ assert num_gpu_blocks is not None and num_gpu_blocks > 0
96
+
97
+ self.block_size = self.cache_config.block_size
98
+
99
+ # req_id -> Request
100
+ self.requests: dict[str, Request] = {}
101
+ # Scheduling policy
102
+ if self.scheduler_config.policy == "priority":
103
+ self.policy = SchedulingPolicy.PRIORITY
104
+ elif self.scheduler_config.policy == "fcfs":
105
+ self.policy = SchedulingPolicy.FCFS
106
+ else:
107
+ raise ValueError(
108
+ f"Unknown scheduling policy: {self.scheduler_config.policy}")
109
+ # Priority queues for requests.
110
+ self.waiting = create_request_queue(self.policy)
111
+ self.running: list[Request] = []
112
+
113
+ # The request IDs that are finished in between the previous and the
114
+ # current steps. This is used to notify the workers about the finished
115
+ # requests so that they can free the cached states for those requests.
116
+ # This is flushed at the end of each scheduling step.
117
+ self.finished_req_ids: set[str] = set()
118
+
119
+ # KV Connector: requests in process of async KV loading or recving
120
+ self.finished_recving_kv_req_ids: set[str] = set()
121
+
122
+ # Encoder-related.
123
+ # Calculate encoder cache size if applicable
124
+ # NOTE: For now we use the same budget for both compute and space.
125
+ # This can be changed when we make encoder cache for embedding caching
126
+ # across requests.
127
+ encoder_compute_budget, encoder_cache_size = compute_encoder_budget(
128
+ model_config=vllm_config.model_config,
129
+ scheduler_config=vllm_config.scheduler_config,
130
+ mm_registry=mm_registry,
131
+ )
132
+
133
+ # NOTE(woosuk): Here, "encoder" includes the vision encoder (and
134
+ # projector if needed). Currently, we assume that the encoder also
135
+ # has the Transformer architecture (e.g., ViT).
136
+ self.max_num_encoder_input_tokens = encoder_compute_budget
137
+ # NOTE: For the models without encoder (e.g., text-only models),
138
+ # the encoder cache will not be initialized because cache size is 0
139
+ # for these models.
140
+ self.encoder_cache_manager = EncoderCacheManager(
141
+ cache_size=encoder_cache_size)
142
+
143
+ speculative_config = vllm_config.speculative_config
144
+
145
+ self.use_eagle = False
146
+ self.num_spec_tokens = self.num_lookahead_tokens = 0
147
+ if speculative_config:
148
+ self.num_spec_tokens = speculative_config.num_speculative_tokens
149
+ if speculative_config.use_eagle():
150
+ self.use_eagle = True
151
+ self.num_lookahead_tokens = self.num_spec_tokens
152
+
153
+ # Create the KV cache manager.
154
+ self.kv_cache_manager = KVCacheManager(
155
+ kv_cache_config=kv_cache_config,
156
+ max_model_len=self.max_model_len,
157
+ enable_caching=self.cache_config.enable_prefix_caching,
158
+ use_eagle=self.use_eagle,
159
+ log_stats=self.log_stats,
160
+ enable_kv_cache_events=self.enable_kv_cache_events,
161
+ )
162
+ self.use_pp = self.parallel_config.pipeline_parallel_size > 1
163
+
164
+ def schedule(self) -> SchedulerOutput:
165
+ # NOTE(woosuk) on the scheduling algorithm:
166
+ # There's no "decoding phase" nor "prefill phase" in the scheduler.
167
+ # Each request just has the num_computed_tokens and
168
+ # num_tokens_with_spec. num_tokens_with_spec =
169
+ # len(prompt_token_ids) + len(output_token_ids) + len(spec_token_ids).
170
+ # At each step, the scheduler tries to assign tokens to the requests
171
+ # so that each request's num_computed_tokens can catch up its
172
+ # num_tokens_with_spec. This is general enough to cover
173
+ # chunked prefills, prefix caching, speculative decoding,
174
+ # and the "jump decoding" optimization in the future.
175
+
176
+ scheduled_new_reqs: list[Request] = []
177
+ scheduled_resumed_reqs: list[Request] = []
178
+ scheduled_running_reqs: list[Request] = []
179
+ preempted_reqs: list[Request] = []
180
+
181
+ # NOTE: structured_output_request_ids maps
182
+ # a request's (request that uses structured output)
183
+ # request_id to the running request index.
184
+ # This will helps us determine to slice the grammar bitmask
185
+ # and only applies valid mask for requests that
186
+ # uses structured decoding.
187
+ structured_output_request_ids: dict[str, int] = {}
188
+
189
+ req_to_new_block_ids: dict[str, tuple[list[int], ...]] = {}
190
+ num_scheduled_tokens: dict[str, int] = {}
191
+ token_budget = self.max_num_scheduled_tokens
192
+ # Encoder-related.
193
+ scheduled_encoder_inputs: dict[str, list[int]] = {}
194
+ encoder_budget = self.max_num_encoder_input_tokens
195
+ # Spec decode-related.
196
+ scheduled_spec_decode_tokens: dict[str, list[int]] = {}
197
+
198
+ # For logging.
199
+ scheduled_timestamp = time.monotonic()
200
+
201
+ # First, schedule the RUNNING requests.
202
+ req_index = 0
203
+ while req_index < len(self.running) and token_budget > 0:
204
+ request = self.running[req_index]
205
+
206
+ num_new_tokens = (request.num_tokens_with_spec +
207
+ request.num_output_placeholders -
208
+ request.num_computed_tokens)
209
+ if (0 < self.scheduler_config.long_prefill_token_threshold <
210
+ num_new_tokens):
211
+ num_new_tokens = (
212
+ self.scheduler_config.long_prefill_token_threshold)
213
+ num_new_tokens = min(num_new_tokens, token_budget)
214
+
215
+ # Make sure the input position does not exceed the max model len.
216
+ # This is necessary when using spec decoding.
217
+ num_new_tokens = min(
218
+ num_new_tokens,
219
+ self.max_model_len - 1 - request.num_computed_tokens)
220
+
221
+ # Schedule encoder inputs.
222
+ encoder_inputs_to_schedule = None
223
+ new_encoder_budget = encoder_budget
224
+ if request.has_encoder_inputs:
225
+ (encoder_inputs_to_schedule, num_new_tokens,
226
+ new_encoder_budget) = self._try_schedule_encoder_inputs(
227
+ request, request.num_computed_tokens, num_new_tokens,
228
+ encoder_budget)
229
+
230
+ if num_new_tokens == 0:
231
+ # The request cannot be scheduled because one of the following
232
+ # reasons:
233
+ # 1. No new tokens to schedule. This may happen when
234
+ # (1) PP>1 and we have already scheduled all prompt tokens
235
+ # but they are not finished yet.
236
+ # (2) Async scheduling and the request has reached to either
237
+ # its max_total_tokens or max_model_len.
238
+ # 2. The encoder budget is exhausted.
239
+ # 3. The encoder cache is exhausted.
240
+ # NOTE(woosuk): Here, by doing `continue` instead of `break`,
241
+ # we do not strictly follow the FCFS scheduling policy and
242
+ # allow the lower-priority requests to be scheduled.
243
+ req_index += 1
244
+ continue
245
+
246
+ while True:
247
+ new_blocks = self.kv_cache_manager.allocate_slots(
248
+ request,
249
+ num_new_tokens,
250
+ num_lookahead_tokens=self.num_lookahead_tokens)
251
+ if new_blocks is None:
252
+ # The request cannot be scheduled.
253
+ # Preempt the lowest-priority request.
254
+ if self.policy == SchedulingPolicy.PRIORITY:
255
+ preempted_req = max(
256
+ self.running,
257
+ key=lambda r: (r.priority, r.arrival_time),
258
+ )
259
+ self.running.remove(preempted_req)
260
+ else:
261
+ preempted_req = self.running.pop()
262
+
263
+ self.kv_cache_manager.free(preempted_req)
264
+ preempted_req.status = RequestStatus.PREEMPTED
265
+ preempted_req.num_computed_tokens = 0
266
+ if self.log_stats:
267
+ preempted_req.record_event(
268
+ EngineCoreEventType.PREEMPTED, scheduled_timestamp)
269
+
270
+ self.waiting.prepend_request(preempted_req)
271
+ preempted_reqs.append(preempted_req)
272
+ if preempted_req == request:
273
+ # No more request to preempt.
274
+ can_schedule = False
275
+ break
276
+ else:
277
+ # The request can be scheduled.
278
+ can_schedule = True
279
+ break
280
+ if not can_schedule:
281
+ break
282
+ assert new_blocks is not None
283
+
284
+ # Schedule the request.
285
+ scheduled_running_reqs.append(request)
286
+ if request.use_structured_output:
287
+ # PERF: in case of chunked prefill,
288
+ # request might not include any new tokens.
289
+ # Therefore, we might introduce some additional
290
+ # cycle to fill in the bitmask, which could be a big no-op.
291
+ structured_output_request_ids[request.request_id] = req_index
292
+ req_to_new_block_ids[request.request_id] = (
293
+ new_blocks.get_block_ids())
294
+ num_scheduled_tokens[request.request_id] = num_new_tokens
295
+ token_budget -= num_new_tokens
296
+ req_index += 1
297
+
298
+ # Speculative decode related.
299
+ if request.spec_token_ids:
300
+ num_scheduled_spec_tokens = (num_new_tokens +
301
+ request.num_computed_tokens -
302
+ request.num_tokens)
303
+ if num_scheduled_spec_tokens > 0:
304
+ # Trim spec_token_ids list to num_scheduled_spec_tokens.
305
+ del request.spec_token_ids[num_scheduled_spec_tokens:]
306
+ scheduled_spec_decode_tokens[request.request_id] = (
307
+ request.spec_token_ids)
308
+
309
+ # Encoder-related.
310
+ if encoder_inputs_to_schedule:
311
+ scheduled_encoder_inputs[request.request_id] = (
312
+ encoder_inputs_to_schedule)
313
+ # Allocate the encoder cache.
314
+ for i in encoder_inputs_to_schedule:
315
+ self.encoder_cache_manager.allocate(request, i)
316
+ encoder_budget = new_encoder_budget
317
+
318
+ # Record the LoRAs in scheduled_running_reqs
319
+ scheduled_loras: set[int] = set()
320
+ if self.lora_config:
321
+ scheduled_loras = set(
322
+ req.lora_request.lora_int_id for req in scheduled_running_reqs
323
+ if req.lora_request and req.lora_request.lora_int_id > 0)
324
+ assert len(scheduled_loras) <= self.lora_config.max_loras
325
+
326
+ # Use a temporary RequestQueue to collect requests that need to be
327
+ # skipped and put back at the head of the waiting queue later
328
+ skipped_waiting_requests = create_request_queue(self.policy)
329
+
330
+ # Next, schedule the WAITING requests.
331
+ if not preempted_reqs:
332
+ while self.waiting and token_budget > 0:
333
+ if len(self.running) == self.max_num_running_reqs:
334
+ break
335
+
336
+ request = self.waiting.peek_request()
337
+
338
+ # KVTransfer: skip request if still waiting for remote kvs.
339
+ if request.status == RequestStatus.WAITING_FOR_REMOTE_KVS:
340
+ is_ready = self._update_waiting_for_remote_kv(request)
341
+ if is_ready:
342
+ request.status = RequestStatus.WAITING
343
+ else:
344
+ logger.debug(
345
+ "%s is still in WAITING_FOR_REMOTE_KVS state.",
346
+ request.request_id)
347
+ self.waiting.pop_request()
348
+ skipped_waiting_requests.prepend_request(request)
349
+ continue
350
+
351
+ # Skip request if the structured output request is still waiting
352
+ # for FSM compilation.
353
+ if request.status == RequestStatus.WAITING_FOR_FSM:
354
+ structured_output_req = request.structured_output_request
355
+ if structured_output_req and structured_output_req.grammar:
356
+ request.status = RequestStatus.WAITING
357
+ else:
358
+ self.waiting.pop_request()
359
+ skipped_waiting_requests.prepend_request(request)
360
+ continue
361
+
362
+ # Check that adding the request still respects the max_loras
363
+ # constraint.
364
+ if (self.lora_config and request.lora_request and
365
+ (len(scheduled_loras) == self.lora_config.max_loras and
366
+ request.lora_request.lora_int_id not in scheduled_loras)):
367
+ # Scheduling would exceed max_loras, skip.
368
+ self.waiting.pop_request()
369
+ skipped_waiting_requests.prepend_request(request)
370
+ continue
371
+
372
+ num_external_computed_tokens = 0
373
+ load_kv_async = False
374
+
375
+ # Get already-cached tokens.
376
+ if request.num_computed_tokens == 0:
377
+ # Get locally-cached tokens.
378
+ new_computed_blocks, num_new_local_computed_tokens = \
379
+ self.kv_cache_manager.get_computed_blocks(
380
+ request)
381
+
382
+ # Get externally-cached tokens if using a KVConnector.
383
+ if self.connector is not None:
384
+ num_external_computed_tokens, load_kv_async = (
385
+ self.connector.get_num_new_matched_tokens(
386
+ request, num_new_local_computed_tokens))
387
+
388
+ # Total computed tokens (local + external).
389
+ num_computed_tokens = (num_new_local_computed_tokens +
390
+ num_external_computed_tokens)
391
+ # KVTransfer: WAITING reqs have num_computed_tokens > 0
392
+ # after async KV recvs are completed.
393
+ else:
394
+ new_computed_blocks = (
395
+ self.kv_cache_manager.create_empty_block_list())
396
+ num_new_local_computed_tokens = 0
397
+ num_computed_tokens = request.num_computed_tokens
398
+
399
+ encoder_inputs_to_schedule = None
400
+ new_encoder_budget = encoder_budget
401
+
402
+ # KVTransfer: loading remote KV, do not allocate for new work.
403
+ if load_kv_async:
404
+ assert num_external_computed_tokens > 0
405
+ num_new_tokens = 0
406
+ # Number of tokens to be scheduled.
407
+ else:
408
+ # We use `request.num_tokens` instead of
409
+ # `request.num_prompt_tokens` to consider the resumed
410
+ # requests, which have output tokens.
411
+ num_new_tokens = request.num_tokens - num_computed_tokens
412
+ if (0 < self.scheduler_config.long_prefill_token_threshold
413
+ < num_new_tokens):
414
+ num_new_tokens = (
415
+ self.scheduler_config.long_prefill_token_threshold)
416
+
417
+ # chunked prefill has to be enabled explicitly to allow
418
+ # pooling requests to be chunked
419
+ if not self.scheduler_config.chunked_prefill_enabled and \
420
+ num_new_tokens > token_budget:
421
+ self.waiting.pop_request()
422
+ skipped_waiting_requests.prepend_request(request)
423
+ continue
424
+
425
+ num_new_tokens = min(num_new_tokens, token_budget)
426
+ assert num_new_tokens > 0
427
+
428
+ # Schedule encoder inputs.
429
+ if request.has_encoder_inputs:
430
+ (encoder_inputs_to_schedule, num_new_tokens,
431
+ new_encoder_budget
432
+ ) = self._try_schedule_encoder_inputs(
433
+ request, num_computed_tokens, num_new_tokens,
434
+ encoder_budget)
435
+ if num_new_tokens == 0:
436
+ # The request cannot be scheduled.
437
+ break
438
+
439
+ # Handles an edge case when P/D Disaggregation
440
+ # is used with Spec Decoding where an
441
+ # extra block gets allocated which
442
+ # creates a mismatch between the number
443
+ # of local and remote blocks.
444
+ effective_lookahead_tokens = (0 if request.num_computed_tokens
445
+ == 0 else
446
+ self.num_lookahead_tokens)
447
+
448
+ new_blocks = self.kv_cache_manager.allocate_slots(
449
+ request,
450
+ num_new_tokens + num_external_computed_tokens,
451
+ num_new_local_computed_tokens,
452
+ new_computed_blocks,
453
+ num_lookahead_tokens=effective_lookahead_tokens,
454
+ delay_cache_blocks=load_kv_async,
455
+ )
456
+
457
+ if new_blocks is None:
458
+ # The request cannot be scheduled.
459
+ break
460
+
461
+ # KVTransfer: the connector uses this info to determine
462
+ # if a load is needed. Note that
463
+ # This information is used to determine if a load is
464
+ # needed for this request.
465
+ if self.connector is not None:
466
+ self.connector.update_state_after_alloc(
467
+ request,
468
+ new_computed_blocks + new_blocks,
469
+ num_external_computed_tokens,
470
+ )
471
+
472
+ # Request was already popped from self.waiting
473
+ # unless it was re-added above due to new_blocks being None.
474
+ request = self.waiting.pop_request()
475
+ if load_kv_async:
476
+ # If loading async, allocate memory and put request
477
+ # into the WAITING_FOR_REMOTE_KV state.
478
+ skipped_waiting_requests.prepend_request(request)
479
+ request.status = RequestStatus.WAITING_FOR_REMOTE_KVS
480
+ continue
481
+
482
+ if request.use_structured_output:
483
+ structured_output_request_ids[request.request_id] = (
484
+ req_index)
485
+ req_index += 1
486
+ self.running.append(request)
487
+ if self.log_stats:
488
+ request.record_event(EngineCoreEventType.SCHEDULED,
489
+ scheduled_timestamp)
490
+ if request.status == RequestStatus.WAITING:
491
+ scheduled_new_reqs.append(request)
492
+ elif request.status == RequestStatus.PREEMPTED:
493
+ scheduled_resumed_reqs.append(request)
494
+ else:
495
+ raise RuntimeError(
496
+ f"Invalid request status: {request.status}")
497
+
498
+ if self.lora_config and request.lora_request:
499
+ scheduled_loras.add(request.lora_request.lora_int_id)
500
+ req_to_new_block_ids[request.request_id] = (
501
+ self.kv_cache_manager.get_block_ids(request.request_id))
502
+ num_scheduled_tokens[request.request_id] = num_new_tokens
503
+ token_budget -= num_new_tokens
504
+ request.status = RequestStatus.RUNNING
505
+ request.num_computed_tokens = num_computed_tokens
506
+ # Count the number of prefix cached tokens.
507
+ if request.num_cached_tokens < 0:
508
+ request.num_cached_tokens = num_computed_tokens
509
+ # Encoder-related.
510
+ if encoder_inputs_to_schedule:
511
+ scheduled_encoder_inputs[request.request_id] = (
512
+ encoder_inputs_to_schedule)
513
+ # Allocate the encoder cache.
514
+ for i in encoder_inputs_to_schedule:
515
+ self.encoder_cache_manager.allocate(request, i)
516
+ encoder_budget = new_encoder_budget
517
+
518
+ # Put back any skipped requests at the head of the waiting queue
519
+ if skipped_waiting_requests:
520
+ self.waiting.prepend_requests(skipped_waiting_requests)
521
+
522
+ # Check if the scheduling constraints are satisfied.
523
+ total_num_scheduled_tokens = sum(num_scheduled_tokens.values())
524
+ assert total_num_scheduled_tokens <= self.max_num_scheduled_tokens
525
+ assert token_budget >= 0
526
+ assert len(self.running) <= self.max_num_running_reqs
527
+ # Since some requests in the RUNNING queue may not be scheduled in
528
+ # this step, the total number of scheduled requests can be smaller than
529
+ # len(self.running).
530
+ assert (len(scheduled_new_reqs) + len(scheduled_resumed_reqs) +
531
+ len(scheduled_running_reqs) <= len(self.running))
532
+
533
+ # Get the longest common prefix among all requests in the running queue.
534
+ # This can be potentially used for cascade attention.
535
+ num_common_prefix_blocks = [0] * len(
536
+ self.kv_cache_config.kv_cache_groups)
537
+ if self.running:
538
+ any_request = self.running[0]
539
+ num_common_prefix_blocks = (
540
+ self.kv_cache_manager.get_num_common_prefix_blocks(
541
+ any_request, len(self.running)))
542
+
543
+ grammar_bitmask = self.structured_output_manager.grammar_bitmask(
544
+ self.requests,
545
+ structured_output_request_ids,
546
+ scheduled_spec_decode_tokens,
547
+ )
548
+ # Construct the scheduler output.
549
+ new_reqs_data = [
550
+ NewRequestData.from_request(req,
551
+ req_to_new_block_ids[req.request_id])
552
+ for req in scheduled_new_reqs
553
+ ]
554
+ cached_reqs_data = self._make_cached_request_data(
555
+ scheduled_running_reqs,
556
+ scheduled_resumed_reqs,
557
+ num_scheduled_tokens,
558
+ scheduled_spec_decode_tokens,
559
+ req_to_new_block_ids,
560
+ )
561
+ scheduler_output = SchedulerOutput(
562
+ scheduled_new_reqs=new_reqs_data,
563
+ scheduled_cached_reqs=cached_reqs_data,
564
+ num_scheduled_tokens=num_scheduled_tokens,
565
+ total_num_scheduled_tokens=total_num_scheduled_tokens,
566
+ scheduled_spec_decode_tokens=scheduled_spec_decode_tokens,
567
+ scheduled_encoder_inputs=scheduled_encoder_inputs,
568
+ num_common_prefix_blocks=num_common_prefix_blocks,
569
+ # finished_req_ids is an existing state in the scheduler,
570
+ # instead of being newly scheduled in this step.
571
+ # It contains the request IDs that are finished in between
572
+ # the previous and the current steps.
573
+ finished_req_ids=self.finished_req_ids,
574
+ free_encoder_input_ids=self.encoder_cache_manager.get_freed_ids(),
575
+ structured_output_request_ids=structured_output_request_ids,
576
+ grammar_bitmask=grammar_bitmask,
577
+ )
578
+
579
+ # NOTE(Kuntai): this function is designed for multiple purposes:
580
+ # 1. Plan the KV cache store
581
+ # 2. Wrap up all the KV cache load / save ops into an opaque object
582
+ # 3. Clear the internal states of the connector
583
+ if self.connector is not None:
584
+ meta = self.connector.build_connector_meta(scheduler_output)
585
+ scheduler_output.kv_connector_metadata = meta
586
+
587
+ events = self.kv_cache_manager.take_events()
588
+ if events:
589
+ batch = KVEventBatch(ts=time.time(), events=events)
590
+ self.kv_event_publisher.publish(batch)
591
+
592
+ self._update_after_schedule(scheduler_output)
593
+ return scheduler_output
594
+
595
+ def _update_after_schedule(
596
+ self,
597
+ scheduler_output: SchedulerOutput,
598
+ ) -> None:
599
+ # Advance the number of computed tokens for the request AFTER
600
+ # the request is scheduled.
601
+ # 1. The scheduler_output of the current step has to include the
602
+ # original number of scheduled tokens to determine input IDs.
603
+ # 2. Advance the number of computed tokens here allowing us to
604
+ # schedule the prefill request again immediately in the next
605
+ # scheduling step.
606
+ # 3. If some tokens (e.g. spec tokens) are rejected later, the number of
607
+ # computed tokens will be adjusted in update_from_output.
608
+ num_scheduled_tokens = scheduler_output.num_scheduled_tokens
609
+ for req_id, num_scheduled_token in num_scheduled_tokens.items():
610
+ request = self.requests[req_id]
611
+ request.num_computed_tokens += num_scheduled_token
612
+
613
+ # NOTE: _free_encoder_inputs relies on num_computed_tokens, which
614
+ # may be updated again in _update_from_output for speculative
615
+ # decoding. However, it is safe to call the method here because
616
+ # encoder inputs are always part of the prompt, not the output,
617
+ # and thus are unaffected by speculative decoding.
618
+ if request.has_encoder_inputs:
619
+ self._free_encoder_inputs(request)
620
+
621
+ # Clear the finished request IDs.
622
+ # NOTE: We shouldn't do self.finished_req_ids.clear() here because
623
+ # it will also affect the scheduler output.
624
+ self.finished_req_ids = set()
625
+
626
+ def _make_cached_request_data(
627
+ self,
628
+ running_reqs: list[Request],
629
+ resumed_reqs: list[Request],
630
+ num_scheduled_tokens: dict[str, int],
631
+ spec_decode_tokens: dict[str, list[int]],
632
+ req_to_new_block_ids: dict[str, tuple[list[int], ...]],
633
+ ) -> CachedRequestData:
634
+ req_ids: list[str] = []
635
+ new_token_ids: list[list[int]] = []
636
+ new_block_ids: list[tuple[list[int], ...]] = []
637
+ num_computed_tokens: list[int] = []
638
+
639
+ use_connector = self.connector is not None
640
+ for req in itertools.chain(running_reqs, resumed_reqs):
641
+ req_id = req.request_id
642
+ req_ids.append(req_id)
643
+ num_tokens = (num_scheduled_tokens[req_id] -
644
+ len(spec_decode_tokens.get(req_id, ())))
645
+ if self.use_pp:
646
+ # When using PP, the scheduler sends the sampled tokens back,
647
+ # because there's no direct communication between the first-
648
+ # stage worker and the last-stage worker. Otherwise, we don't
649
+ # need to send the sampled tokens back because the model runner
650
+ # will cache them.
651
+ token_ids = req.all_token_ids[req.num_computed_tokens:req.
652
+ num_computed_tokens + num_tokens]
653
+ new_token_ids.append(token_ids)
654
+ elif use_connector:
655
+ # When using a KVConnector, we add a placeholder to avoid index
656
+ # out of bounds errors. TODO: Remove this once the KVConnector
657
+ # is updated to handle token IDs properly.
658
+ new_token_ids.append([])
659
+ new_block_ids.append(req_to_new_block_ids[req_id])
660
+ num_computed_tokens.append(req.num_computed_tokens)
661
+ # Because resumed_reqs is usually empty, it is more efficient to do
662
+ # in-place appending so that we don't need to allocate a new list.
663
+ resumed_from_preemption = [False] * len(running_reqs)
664
+ resumed_from_preemption += [True] * len(resumed_reqs)
665
+
666
+ return CachedRequestData(
667
+ req_ids=req_ids,
668
+ resumed_from_preemption=resumed_from_preemption,
669
+ new_token_ids=new_token_ids,
670
+ new_block_ids=new_block_ids,
671
+ num_computed_tokens=num_computed_tokens,
672
+ )
673
+
674
+ def _try_schedule_encoder_inputs(
675
+ self,
676
+ request: Request,
677
+ num_computed_tokens: int,
678
+ num_new_tokens: int,
679
+ encoder_budget: int,
680
+ ) -> tuple[list[int], int, int]:
681
+ """
682
+ Determine which encoder inputs need to be scheduled in the current step,
683
+ and update `num_new_tokens` and encoder token budget accordingly.
684
+
685
+ An encoder input will be scheduled if:
686
+ - Its output tokens overlap with the range of tokens being computed
687
+ in this step, i.e.,
688
+ [num_computed_tokens, num_computed_tokens + num_new_tokens).
689
+ - It is not already computed and stored in the encoder cache.
690
+ - There is sufficient encoder token budget to process it.
691
+ - The encoder cache has space to store it.
692
+
693
+ If an encoder input cannot be scheduled due to cache or budget
694
+ limitations, the method adjusts `num_new_tokens` to schedule only the
695
+ decoder tokens up to just before the unschedulable encoder input.
696
+
697
+ Note that num_computed_tokens includes both locally cached
698
+ blocks and externally cached blocks (via KVConnector).
699
+ """
700
+ if num_new_tokens == 0 or not request.has_encoder_inputs:
701
+ return [], num_new_tokens, encoder_budget
702
+ encoder_inputs_to_schedule: list[int] = []
703
+ mm_positions = request.mm_positions
704
+ assert mm_positions is not None
705
+ assert len(mm_positions) > 0
706
+ for i, pos_info in enumerate(mm_positions):
707
+ start_pos = pos_info.offset
708
+ num_encoder_tokens = pos_info.length
709
+
710
+ # The encoder output is needed if the two ranges overlap:
711
+ # [num_computed_tokens, num_computed_tokens + num_new_tokens) and
712
+ # [start_pos, start_pos + num_encoder_tokens)
713
+ if start_pos >= num_computed_tokens + num_new_tokens:
714
+ # The encoder input is not needed in this step.
715
+ break
716
+ if start_pos + num_encoder_tokens <= num_computed_tokens:
717
+ # The encoder input is already computed and stored
718
+ # in the decoder's KV cache.
719
+ continue
720
+
721
+ if self.encoder_cache_manager.has_cache(request, i):
722
+ # The encoder input is already computed and cached.
723
+ continue
724
+
725
+ # If no encoder input chunking is allowed, we do not want to
726
+ # partially schedule a multimodal item. If the scheduled range would
727
+ # only cover part of the mm input, roll back to before the mm item.
728
+ if (self.scheduler_config.disable_chunked_mm_input
729
+ and num_computed_tokens < start_pos
730
+ and (num_computed_tokens + num_new_tokens)
731
+ < (start_pos + num_encoder_tokens)):
732
+ num_new_tokens = start_pos - num_computed_tokens
733
+ break
734
+
735
+ if (not self.encoder_cache_manager.can_allocate(request, i)
736
+ or num_encoder_tokens > encoder_budget):
737
+ # The encoder cache is full or the encoder budget is exhausted.
738
+ # NOTE(woosuk): We assume that the encoder input tokens should
739
+ # be processed altogether, as the encoder usually uses
740
+ # bidirectional attention.
741
+ if num_computed_tokens < start_pos:
742
+ # We only schedule the decoder tokens just before the
743
+ # encoder input.
744
+ num_new_tokens = start_pos - num_computed_tokens
745
+ else:
746
+ # Because of prefix caching, num_computed_tokens is greater
747
+ # than start_pos even though its encoder input is not
748
+ # available. In this case, we can't schedule any token for
749
+ # the request in this step.
750
+ num_new_tokens = 0
751
+ break
752
+
753
+ encoder_budget -= num_encoder_tokens
754
+ encoder_inputs_to_schedule.append(i)
755
+ return encoder_inputs_to_schedule, num_new_tokens, encoder_budget
756
+
757
+ def update_from_output(
758
+ self,
759
+ scheduler_output: SchedulerOutput,
760
+ model_runner_output: ModelRunnerOutput,
761
+ ) -> dict[int, EngineCoreOutputs]:
762
+ sampled_token_ids = model_runner_output.sampled_token_ids
763
+ spec_token_ids = model_runner_output.spec_token_ids
764
+ logprobs = model_runner_output.logprobs
765
+ prompt_logprobs_dict = model_runner_output.prompt_logprobs_dict
766
+ num_scheduled_tokens = scheduler_output.num_scheduled_tokens
767
+ pooler_outputs = model_runner_output.pooler_output
768
+ num_nans_in_logits = model_runner_output.num_nans_in_logits
769
+
770
+ outputs: dict[int, list[EngineCoreOutput]] = defaultdict(list)
771
+ spec_decoding_stats: Optional[SpecDecodingStats] = None
772
+
773
+ # NOTE(woosuk): As len(num_scheduled_tokens) can be up to 1K or more,
774
+ # the below loop can be a performance bottleneck. We should do our best
775
+ # to avoid expensive operations inside the loop.
776
+ stopped_running_reqs: set[Request] = set()
777
+ stopped_preempted_reqs: set[Request] = set()
778
+ for req_id, num_tokens_scheduled in num_scheduled_tokens.items():
779
+ assert num_tokens_scheduled > 0
780
+ request = self.requests.get(req_id)
781
+ if request is None:
782
+ # The request is already finished. This can happen if the
783
+ # request is aborted while the model is executing it (e.g.,
784
+ # in pipeline parallelism).
785
+ continue
786
+
787
+ req_index = model_runner_output.req_id_to_index[req_id]
788
+ generated_token_ids = sampled_token_ids[
789
+ req_index] if sampled_token_ids else []
790
+
791
+ scheduled_spec_token_ids = (
792
+ scheduler_output.scheduled_spec_decode_tokens.get(req_id))
793
+ if scheduled_spec_token_ids:
794
+ # num_computed_tokens represents the number of tokens
795
+ # processed in the current step, considering scheduled
796
+ # tokens and rejections. If some tokens are rejected,
797
+ # num_computed_tokens is decreased by the number of rejected
798
+ # tokens, where is given by:
799
+ # len(scheduled_spec_token_ids) + 1 - len(generated_token_ids).
800
+ num_tokens_rejected = (len(scheduled_spec_token_ids) + 1 -
801
+ len(generated_token_ids))
802
+ request.num_computed_tokens -= num_tokens_rejected
803
+ spec_decoding_stats = self.make_spec_decoding_stats(
804
+ spec_decoding_stats,
805
+ num_draft_tokens=len(scheduled_spec_token_ids),
806
+ num_accepted_tokens=len(generated_token_ids) - 1)
807
+
808
+ stopped = False
809
+ new_logprobs = None
810
+ new_token_ids = generated_token_ids
811
+ kv_transfer_params = None
812
+ status_before_stop = request.status
813
+
814
+ # Check for stop and update request status.
815
+ if new_token_ids:
816
+ new_token_ids, stopped = self._update_request_with_output(
817
+ request, new_token_ids)
818
+
819
+ # Stop checking for pooler models.
820
+ pooler_output = None
821
+ if pooler_outputs:
822
+ pooler_output = pooler_outputs[req_index]
823
+ stopped = check_stop(request, self.max_model_len,
824
+ pooler_output)
825
+
826
+ if stopped:
827
+ kv_transfer_params = self._free_request(request)
828
+ if status_before_stop == RequestStatus.RUNNING:
829
+ stopped_running_reqs.add(request)
830
+ else:
831
+ stopped_preempted_reqs.add(request)
832
+
833
+ # Extract sample logprobs if needed.
834
+ if request.sampling_params is not None \
835
+ and request.sampling_params.logprobs is not None and logprobs:
836
+ # NOTE: once we support N tokens per step (spec decode),
837
+ # the outer lists can be of length > 1.
838
+ new_logprobs = logprobs.slice(req_index, req_index + 1)
839
+
840
+ if new_token_ids and self.structured_output_manager.should_advance(
841
+ request):
842
+ # NOTE: structured_output_request
843
+ # should not be None if use_structured_output, we have
844
+ # check above, so safe to ignore type warning
845
+ request.structured_output_request.grammar.accept_tokens( # type: ignore[union-attr]
846
+ req_id, new_token_ids)
847
+
848
+ # spec_token_ids comes from the model runner output
849
+ if num_nans_in_logits is not None and req_id in num_nans_in_logits:
850
+ request.num_nans_in_logits = num_nans_in_logits[req_id]
851
+
852
+ # Add newly generated spec token ids to the request.
853
+ if spec_token_ids is not None:
854
+ if self.structured_output_manager.should_advance(request):
855
+ metadata = request.structured_output_request
856
+ # Needs to happen after new_token_ids are accepted.
857
+ request.spec_token_ids = metadata.grammar.validate_tokens( # type: ignore[union-attr]
858
+ spec_token_ids[req_index])
859
+ else:
860
+ request.spec_token_ids = spec_token_ids[req_index]
861
+
862
+ # Get prompt logprobs for this request.
863
+ prompt_logprobs_tensors = prompt_logprobs_dict.get(req_id)
864
+ if new_token_ids or pooler_output is not None \
865
+ or kv_transfer_params:
866
+
867
+ # Add EngineCoreOutput for this Request.
868
+ outputs[request.client_index].append(
869
+ EngineCoreOutput(
870
+ request_id=req_id,
871
+ new_token_ids=new_token_ids,
872
+ finish_reason=request.get_finished_reason(),
873
+ new_logprobs=new_logprobs,
874
+ new_prompt_logprobs_tensors=prompt_logprobs_tensors,
875
+ pooling_output=pooler_output,
876
+ stop_reason=request.stop_reason,
877
+ events=request.take_events(),
878
+ kv_transfer_params=kv_transfer_params,
879
+ num_cached_tokens=request.num_cached_tokens,
880
+ ))
881
+
882
+ else:
883
+ # Invariant: EngineCore returns no partial prefill outputs.
884
+ assert not prompt_logprobs_tensors
885
+
886
+ # Remove the stopped requests from the running and waiting queues.
887
+ if stopped_running_reqs:
888
+ self.running = [
889
+ req for req in self.running if req not in stopped_running_reqs
890
+ ]
891
+ if stopped_preempted_reqs:
892
+ # This is a rare case and unlikely to impact performance.
893
+ self.waiting.remove_requests(stopped_preempted_reqs)
894
+
895
+ # KV Connector: update state for finished KV Transfers.
896
+ if model_runner_output.kv_connector_output:
897
+ self._update_from_kv_xfer_finished(
898
+ model_runner_output.kv_connector_output)
899
+
900
+ # Create EngineCoreOutputs for all clients that have requests with
901
+ # outputs in this step.
902
+ engine_core_outputs = {
903
+ client_index: EngineCoreOutputs(outputs=outs)
904
+ for client_index, outs in outputs.items()
905
+ }
906
+
907
+ finished_req_ids = self.finished_req_ids_dict
908
+ if finished_req_ids:
909
+ # Include ids of requests that finished since last outputs
910
+ # were sent.
911
+ for client_index, finished_set in finished_req_ids.items():
912
+ # Set finished request set in EngineCoreOutputs for this client.
913
+ if (eco := engine_core_outputs.get(client_index)) is not None:
914
+ eco.finished_requests = finished_set
915
+ else:
916
+ engine_core_outputs[client_index] = EngineCoreOutputs(
917
+ finished_requests=finished_set)
918
+ finished_req_ids.clear()
919
+
920
+ if engine_core_outputs:
921
+ # Return stats to only one of the front-ends.
922
+ next(iter(engine_core_outputs.values())).scheduler_stats = (
923
+ self.make_stats(spec_decoding_stats))
924
+
925
+ return engine_core_outputs
926
+
927
+ def _update_request_with_output(
928
+ self,
929
+ request: Request,
930
+ new_token_ids: list[int],
931
+ ) -> tuple[list[int], bool]:
932
+ # Append generated tokens and check for stop. Note that if
933
+ # a request is still being prefilled, we expect the model runner
934
+ # to return empty token ids for the request.
935
+ stopped = False
936
+ for num_new, output_token_id in enumerate(new_token_ids, 1):
937
+ request.append_output_token_ids(output_token_id)
938
+
939
+ # Check for stop and update request state.
940
+ # This must be called before we make the EngineCoreOutput.
941
+ stopped = check_stop(request, self.max_model_len)
942
+ if stopped:
943
+ del new_token_ids[num_new:] # Trim new tokens if needed.
944
+ break
945
+ return new_token_ids, stopped
946
+
947
+ def _free_encoder_inputs(self, request: Request) -> None:
948
+ cached_encoder_input_ids = (
949
+ self.encoder_cache_manager.get_cached_input_ids(request))
950
+ # OPTIMIZATION: Avoid list(set) if the set is empty.
951
+ if not cached_encoder_input_ids:
952
+ return
953
+
954
+ # Here, we use list(set) to avoid modifying the set while iterating
955
+ # over it.
956
+ for input_id in list(cached_encoder_input_ids):
957
+ mm_positions = request.mm_positions[input_id]
958
+ start_pos = mm_positions.offset
959
+ num_tokens = mm_positions.length
960
+ if start_pos + num_tokens <= request.num_computed_tokens:
961
+ # The encoder output is already processed and stored
962
+ # in the decoder's KV cache.
963
+ self.encoder_cache_manager.free_encoder_input(
964
+ request, input_id)
965
+
966
+ def get_request_counts(self) -> tuple[int, int]:
967
+ """Returns (num_running_reqs, num_waiting_reqs)."""
968
+ return len(self.running), len(self.waiting)
969
+
970
+ def add_request(self, request: Request) -> None:
971
+ self.waiting.add_request(request)
972
+ self.requests[request.request_id] = request
973
+ if self.log_stats:
974
+ request.record_event(EngineCoreEventType.QUEUED)
975
+
976
+ def finish_requests(
977
+ self,
978
+ request_ids: Union[str, Iterable[str]],
979
+ finished_status: RequestStatus,
980
+ ) -> None:
981
+ """Handles the finish signal from outside the scheduler.
982
+
983
+ For example, the API server can abort a request when the client
984
+ disconnects.
985
+ """
986
+ assert RequestStatus.is_finished(finished_status)
987
+ if isinstance(request_ids, str):
988
+ request_ids = (request_ids, )
989
+ else:
990
+ request_ids = set(request_ids)
991
+
992
+ running_requests_to_remove = []
993
+ waiting_requests_to_remove = []
994
+ valid_requests = []
995
+
996
+ # First pass: collect requests to remove from queues
997
+ for req_id in request_ids:
998
+ request = self.requests.get(req_id)
999
+ if request is None:
1000
+ # Invalid request ID.
1001
+ continue
1002
+
1003
+ valid_requests.append(request)
1004
+ if request.status == RequestStatus.RUNNING:
1005
+ running_requests_to_remove.append(request)
1006
+ else:
1007
+ waiting_requests_to_remove.append(request)
1008
+
1009
+ # Remove all requests from queues at once for better efficiency
1010
+ for request in running_requests_to_remove:
1011
+ self.running.remove(request)
1012
+ if waiting_requests_to_remove:
1013
+ self.waiting.remove_requests(waiting_requests_to_remove)
1014
+
1015
+ # Second pass: set status and free requests
1016
+ for request in valid_requests:
1017
+ request.status = finished_status
1018
+ self._free_request(request)
1019
+
1020
+ def _free_request(self, request: Request) -> Optional[dict[str, Any]]:
1021
+ assert request.is_finished()
1022
+
1023
+ delay_free_blocks, kv_xfer_params = self._connector_finished(request)
1024
+ self.encoder_cache_manager.free(request)
1025
+ request_id = request.request_id
1026
+ self.finished_req_ids.add(request_id)
1027
+ if self.finished_req_ids_dict is not None:
1028
+ self.finished_req_ids_dict[request.client_index].add(request_id)
1029
+
1030
+ if not delay_free_blocks:
1031
+ self._free_blocks(request)
1032
+
1033
+ return kv_xfer_params
1034
+
1035
+ def _free_blocks(self, request: Request):
1036
+ assert request.is_finished()
1037
+ self.kv_cache_manager.free(request)
1038
+ del self.requests[request.request_id]
1039
+
1040
+ def get_num_unfinished_requests(self) -> int:
1041
+ return len(self.waiting) + len(self.running)
1042
+
1043
+ def has_finished_requests(self) -> bool:
1044
+ return len(self.finished_req_ids) > 0
1045
+
1046
+ def reset_prefix_cache(self) -> bool:
1047
+ return self.kv_cache_manager.reset_prefix_cache()
1048
+
1049
+ def make_stats(
1050
+ self,
1051
+ spec_decoding_stats: Optional[SpecDecodingStats] = None,
1052
+ ) -> Optional[SchedulerStats]:
1053
+ if not self.log_stats:
1054
+ return None
1055
+ prefix_cache_stats = self.kv_cache_manager.make_prefix_cache_stats()
1056
+ assert prefix_cache_stats is not None
1057
+ return SchedulerStats(
1058
+ num_running_reqs=len(self.running),
1059
+ num_waiting_reqs=len(self.waiting),
1060
+ kv_cache_usage=self.kv_cache_manager.usage,
1061
+ prefix_cache_stats=prefix_cache_stats,
1062
+ spec_decoding_stats=spec_decoding_stats,
1063
+ num_corrupted_reqs=sum(req.is_output_corrupted
1064
+ for req in self.running),
1065
+ )
1066
+
1067
+ def make_spec_decoding_stats(
1068
+ self,
1069
+ spec_decoding_stats: Optional[SpecDecodingStats],
1070
+ num_draft_tokens: int,
1071
+ num_accepted_tokens: int,
1072
+ ) -> Optional[SpecDecodingStats]:
1073
+ if not self.log_stats:
1074
+ return None
1075
+ if spec_decoding_stats is None:
1076
+ spec_decoding_stats = SpecDecodingStats.new(self.num_spec_tokens)
1077
+ spec_decoding_stats.observe_draft(
1078
+ num_draft_tokens=num_draft_tokens,
1079
+ num_accepted_tokens=num_accepted_tokens)
1080
+ return spec_decoding_stats
1081
+
1082
+ def shutdown(self) -> None:
1083
+ if self.kv_event_publisher:
1084
+ self.kv_event_publisher.shutdown()
1085
+
1086
+ ########################################################################
1087
+ # KV Connector Related Methods
1088
+ ########################################################################
1089
+
1090
+ def get_kv_connector(self) -> Optional[KVConnectorBase_V1]:
1091
+ return self.connector
1092
+
1093
+ def _connector_finished(
1094
+ self, request: Request) -> tuple[bool, Optional[dict[str, Any]]]:
1095
+ """
1096
+ Invoke the KV connector request_finished() method if applicable.
1097
+
1098
+ Returns optional kv transfer parameters to be included with the
1099
+ request outputs.
1100
+ """
1101
+ if self.connector is None:
1102
+ return False, None
1103
+
1104
+ (block_ids, ) = self.kv_cache_manager.get_block_ids(request.request_id)
1105
+ return self.connector.request_finished(request, block_ids)
1106
+
1107
+ def _update_waiting_for_remote_kv(self, request: Request) -> bool:
1108
+ """
1109
+ KV Connector: check if the request_id is finished_recving.
1110
+
1111
+ The finished_recving_kv_req_ids list is populated
1112
+ on the previous steps()'s update_from_output based
1113
+ on the worker side connector.
1114
+
1115
+ When the kv transfer is ready, we cache the blocks
1116
+ and the request state will be moved back to WAITING from
1117
+ WAITING_FOR_REMOTE_KV.
1118
+ """
1119
+ assert self.connector is not None
1120
+ if request.request_id not in self.finished_recving_kv_req_ids:
1121
+ return False
1122
+
1123
+ # Now that the blocks are ready, actually cache them.
1124
+ (block_ids, ) = self.kv_cache_manager.get_block_ids(request.request_id)
1125
+ num_computed_tokens = len(block_ids) * self.block_size
1126
+ # Handle the case where num request tokens less then one block.
1127
+ num_computed_tokens = min(num_computed_tokens, request.num_tokens)
1128
+ if num_computed_tokens == request.num_tokens:
1129
+ num_computed_tokens -= 1
1130
+ # This will cache the blocks iff caching is enabled.
1131
+ self.kv_cache_manager.cache_blocks(request, num_computed_tokens)
1132
+
1133
+ # Update the request state for scheduling.
1134
+ request.num_computed_tokens = num_computed_tokens
1135
+
1136
+ # Return that we are ready.
1137
+ self.finished_recving_kv_req_ids.remove(request.request_id)
1138
+ return True
1139
+
1140
+ def _update_from_kv_xfer_finished(self,
1141
+ kv_connector_output: KVConnectorOutput):
1142
+ """
1143
+ KV Connector: update the scheduler state based on the output.
1144
+
1145
+ The Worker side connectors add finished_recving and
1146
+ finished_sending reqs to the output.
1147
+ * if finished_sending: free the blocks
1148
+ # if finished_recving: add to state so we can
1149
+ scheduler the request during the next step.
1150
+ """
1151
+
1152
+ if self.connector is not None:
1153
+ self.connector.update_connector_output(kv_connector_output)
1154
+
1155
+ # KV Connector:: update recv and send status from last step.
1156
+ for req_id in (kv_connector_output.finished_recving or ()):
1157
+ logger.debug("Finished recving KV transfer for request %s", req_id)
1158
+ self.finished_recving_kv_req_ids.add(req_id)
1159
+ for req_id in (kv_connector_output.finished_sending or ()):
1160
+ logger.debug("Finished sending KV transfer for request %s", req_id)
1161
+ self._free_blocks(self.requests[req_id])
tool_server/.venv/lib/python3.12/site-packages/vllm/v1/core/sched/utils.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # SPDX-FileCopyrightText: Copyright contributors to the vLLM project
3
+ from typing import Optional
4
+
5
+ import torch
6
+
7
+ from vllm.v1.request import Request, RequestStatus
8
+
9
+
10
+ def check_stop(request: Request,
11
+ max_model_len: int,
12
+ pooler_output: Optional[torch.Tensor] = None) -> bool:
13
+ if (request.num_tokens >= max_model_len
14
+ or request.num_output_tokens >= request.max_tokens):
15
+ request.status = RequestStatus.FINISHED_LENGTH_CAPPED
16
+ return True
17
+
18
+ if request.pooling_params:
19
+ if pooler_output is not None:
20
+ request.status = RequestStatus.FINISHED_STOPPED
21
+ return True
22
+ return False
23
+
24
+ sampling_params = request.sampling_params
25
+ assert sampling_params is not None
26
+ last_token_id = request.output_token_ids[-1]
27
+ if (not sampling_params.ignore_eos
28
+ and last_token_id == request.eos_token_id):
29
+ request.status = RequestStatus.FINISHED_STOPPED
30
+ return True
31
+
32
+ if last_token_id in (sampling_params.stop_token_ids or ()):
33
+ request.status = RequestStatus.FINISHED_STOPPED
34
+ request.stop_reason = last_token_id
35
+ return True
36
+ return False