engine.rs 3.61 KB
Newer Older
Graham King's avatar
Graham King committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// SPDX-FileCopyrightText: Copyright (c) 2024-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.

16
use std::path::{Path, PathBuf};
17
use std::sync::Arc;
Graham King's avatar
Graham King committed
18
19
20
21

use async_stream::stream;
use async_trait::async_trait;

22
use dynamo_llm::engines::MultiNodeConfig;
23
use dynamo_llm::kv_router::publisher::KvMetricsPublisher;
24
use dynamo_llm::protocols::common::llm_backend::{BackendInput, LLMEngineOutput};
Neelay Shah's avatar
Neelay Shah committed
25
26
27
28
use dynamo_runtime::engine::{AsyncEngine, AsyncEngineContextProvider, ResponseStream};
use dynamo_runtime::pipeline::{Error, ManyOut, SingleIn};
use dynamo_runtime::protocols::annotated::Annotated;
use dynamo_runtime::runtime::CancellationToken;
Graham King's avatar
Graham King committed
29

30
31
use crate::worker;

Graham King's avatar
Graham King committed
32
33
34
35
36
37
38
39
40
41
pub struct VllmEngine {
    cancel_token: CancellationToken,
    worker: worker::VllmWorker,
}

impl VllmEngine {
    pub async fn new(
        cancel_token: CancellationToken,
        sock_code: &str,
        model_path: &Path,
42
43
        node_conf: MultiNodeConfig,
        tensor_parallel_size: u32,
44
        extra_engine_args: Option<PathBuf>,
45
        kv_metrics_publisher: Option<Arc<KvMetricsPublisher>>,
Graham King's avatar
Graham King committed
46
    ) -> anyhow::Result<Self> {
47
48
49
50
51
52
        let w = worker::start(
            cancel_token.clone(),
            sock_code,
            model_path,
            node_conf,
            tensor_parallel_size,
53
            extra_engine_args,
54
            kv_metrics_publisher,
55
56
        )
        .await?;
Graham King's avatar
Graham King committed
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
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
111
112
113
114
        let engine = VllmEngine {
            cancel_token,
            worker: w,
        };

        Ok(engine)
    }

    pub fn take_vllm_worker_handle(&mut self) -> tokio::task::JoinHandle<()> {
        self.worker.take_vllm_handle()
    }
}

#[async_trait]
impl AsyncEngine<SingleIn<BackendInput>, ManyOut<Annotated<LLMEngineOutput>>, Error>
    for VllmEngine
{
    async fn generate(
        &self,
        request: SingleIn<BackendInput>,
    ) -> Result<ManyOut<Annotated<LLMEngineOutput>>, Error> {
        let (request, context) = request.into_parts();
        let ctx = context.context();
        let request_id = ctx.id().to_string();

        let (resp_tx, mut resp_rx) = tokio::sync::mpsc::channel(128);
        let work_req = worker::WorkRequest {
            request_id: context.id().to_string(),
            request,
            response_channel: resp_tx,
        };
        self.worker.enqueue_request(work_req).await?;

        let cancel_token = self.cancel_token.clone();
        let output = stream! {
            loop {
                let maybe_resp = tokio::select!{
                    _ = cancel_token.cancelled() => {
                        break;
                    }
                    maybe_resp = resp_rx.recv() => {
                        maybe_resp
                    }
                };
                match maybe_resp {
                    Some(out) => {
                        yield out;
                    },
                    None => {
                        tracing::trace!(request_id, "generate: response channel closed");
                        break;
                    }
                }
            }
        };
        Ok(ResponseStream::new(Box::pin(output), ctx))
    }
}