router.py 6.96 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.


import asyncio
from argparse import Namespace
from enum import Enum
20
from typing import AsyncIterator
21
22

import uvloop
23
from common.protocol import Tokens
Neelay Shah's avatar
Neelay Shah committed
24
25
from vllm.logger import logger as vllm_logger

Neelay Shah's avatar
Neelay Shah committed
26
27
from dynamo.llm import KvIndexer, KvMetricsAggregator, KvRouter
from dynamo.runtime import DistributedRuntime, dynamo_endpoint, dynamo_worker
28

29
30
WorkerId = str

31
32
33
34
35
36
37
38
39
40
41
42
43
44

class RoutingStrategy(Enum):
    PREFIX = "prefix"
    ROUND_ROBIN = "round_robin"
    RANDOM = "random"


class Router:
    """
    Request handler for the generate endpoint
    """

    def __init__(
        self,
45
        router: KvRouter,
46
47
48
49
50
51
52
53
        routing_strategy: RoutingStrategy = RoutingStrategy.PREFIX,
    ):
        vllm_logger.info(
            f"Initializing KV Router with strategy: {routing_strategy.value}"
        )
        self.router = router
        self.routing_strategy = routing_strategy

Neelay Shah's avatar
Neelay Shah committed
54
    @dynamo_endpoint(Tokens, WorkerId)
55
    async def generate(self, request) -> AsyncIterator[WorkerId]:
56
        lora_id = 0
GuanLuo's avatar
GuanLuo committed
57
        worker_id = None
58
59
60
        if self.routing_strategy == RoutingStrategy.PREFIX:
            try:
                worker_id = await self.router.schedule(request.tokens, lora_id)
GuanLuo's avatar
GuanLuo committed
61
62
63
            # [NOTE][TODO] Now that the scheduler may return more error messages,
            # now we are catching all exceptions and logging them. Should have
            # catch specific router exceptions once we have dedicated types.
64
65
            except Exception as e:
                vllm_logger.info(f"{e}")
Alec's avatar
Alec committed
66
                worker_id = ""
GuanLuo's avatar
GuanLuo committed
67
                vllm_logger.exception(f"Error during worker selection: {e}")
68
69
70

            vllm_logger.info(f"Scheduling to worker_id: {worker_id}")

GuanLuo's avatar
GuanLuo committed
71
            yield str(worker_id)
72

73
        else:
74
75
76
77
            # TODO: Do we implement round_robin and random here?
            # or just skip this router and directly enable in preprocess?
            raise NotImplementedError(
                f"Routing strategy {self.routing_strategy} not implemented"
78
79
80
            )


81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
class CustomRouter:
    """
    Request handler for the generate endpoint
    """

    def __init__(
        self,
        indexer: KvIndexer,
        metrics_aggregator: KvMetricsAggregator,
    ):
        self.indexer = indexer
        self.metrics_aggregator = metrics_aggregator

    def _cost_function(self, scores, metrics):
        # naive cost function for demonstration purposes
        current_best = ("", 0)
        for worker_id, score in scores.scores.items():
            if score > current_best[1]:
                current_best = (worker_id, score)
        for endpoint in metrics.endpoints:
            if endpoint.worker_id == current_best[0]:
                print(f"Metrics of endpoint: {endpoint.worker_id}")
                print(
                    f"request slot usage: {endpoint.request_active_slots} / {endpoint.request_total_slots}"
                )
                print(
                    f"KV block usage: {endpoint.kv_active_blocks} / {endpoint.kv_total_blocks}"
                )
        return current_best[0]

Neelay Shah's avatar
Neelay Shah committed
111
    @dynamo_endpoint(Tokens, WorkerId)
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
    async def generate(self, request) -> AsyncIterator[WorkerId]:
        lora_id = 0
        worker_id = ""
        try:
            scores = await self.indexer.find_matches_for_request(
                request.tokens, lora_id
            )
            metrics = await self.metrics_aggregator.get_metrics()
            worker_id = self._cost_function(scores, metrics)

        # [NOTE][TODO] Now that the scheduler may return more error messages,
        # now we are catching all exceptions and logging them. Should have
        # catch specific router exceptions once we have dedicated types.
        except Exception as e:
            vllm_logger.info(f"{e}")
            worker_id = ""
            vllm_logger.exception(f"Error during worker selection: {e}")

        vllm_logger.info(f"Scheduling to worker_id: {worker_id}")

        yield str(worker_id)


Neelay Shah's avatar
Neelay Shah committed
135
@dynamo_worker()
136
async def worker(runtime: DistributedRuntime, args: Namespace):
137
138
    """
    Set up the worker clients.
Neelay Shah's avatar
Neelay Shah committed
139
    Serve the dynamo.router.generate endpoint.
140
    """
141
    workers_client = (
Neelay Shah's avatar
Neelay Shah committed
142
        await runtime.namespace("dynamo")
143
        .component("vllm")
144
        .endpoint("generate")
145
146
        .client()
    )
147
148
149
150
151
152
153
154
    wait_task = workers_client.wait_for_endpoints()
    await asyncio.sleep(1)

    while not wait_task.done():
        vllm_logger.info("Waiting for workers to be ready...")
        await asyncio.sleep(5)

    wait_task.result()
155
156
157
158
159
160
161
162
163
164
165
166

    while len(workers_client.endpoint_ids()) < args.min_workers:
        vllm_logger.info(
            f"Waiting for more workers... Current: {len(workers_client.endpoint_ids())}, Required: {args.min_workers}"
        )
        await asyncio.sleep(5)

    vllm_logger.info(
        f"Required number of workers ({args.min_workers}) are ready:\n"
        + "\n".join(f"id: {id}" for id in workers_client.endpoint_ids())
    )

Neelay Shah's avatar
Neelay Shah committed
167
    kv_listener = runtime.namespace("dynamo").component("vllm")
168
169
    await kv_listener.create_service()

Neelay Shah's avatar
Neelay Shah committed
170
    router_component = runtime.namespace("dynamo").component("router")
171
172
173
    await router_component.create_service()

    endpoint = router_component.endpoint("generate")
174
175
176
177
178
179
180
181
182
183

    if args.custom_router:
        indexer = KvIndexer(kv_listener)
        metrics_aggregator = KvMetricsAggregator(kv_listener)
        await endpoint.serve_endpoint(
            CustomRouter(indexer, metrics_aggregator).generate
        )
    else:
        router = KvRouter(runtime, kv_listener)
        await endpoint.serve_endpoint(Router(router, args.routing_strategy).generate)
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204


if __name__ == "__main__":
    uvloop.install()

    import argparse

    parser = argparse.ArgumentParser()
    parser.add_argument(
        "--routing-strategy",
        type=RoutingStrategy,
        default=RoutingStrategy.PREFIX,
        choices=list(RoutingStrategy),
        help="Routing strategy to use",
    )
    parser.add_argument(
        "--min-workers",
        type=int,
        default=1,
        help="Minimum number of workers required before proceeding",
    )
205
206
207
208
209
210
    parser.add_argument(
        "--model-name",
        type=str,
        default="deepseek-ai/DeepSeek-R1-Distill-Llama-8B",
        help="Model that is being served",
    )
211
212
213
214
215
216
    parser.add_argument(
        "--custom-router",
        type=bool,
        default=False,
        help="Whether to use custom router or not",
    )
217
218
219
    args = parser.parse_args()

    asyncio.run(worker(args))