"docs/guides/README.md" did not exist on "5161250a934078ad1fdf567bf64914079c0a22e2"
engine.rs 6.29 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
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
// 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.

use anyhow::{Error, Result};
use async_trait::async_trait;
use futures::stream;
use tokio::sync::mpsc;
use tokio_util::sync::CancellationToken;
use triton_distributed_runtime::engine::{AsyncEngine, AsyncEngineContextProvider, ResponseStream};
use triton_distributed_runtime::pipeline::{ManyOut, SingleIn};
use triton_distributed_runtime::protocols::annotated::Annotated;

use super::Executor;
use crate::protocols::common::llm_backend::{BackendInput, LLMEngineOutput};

struct State {
    request_id: String,

    cancel_token: CancellationToken,

    response_rx: mpsc::Receiver<Result<super::protocols::Output>>,

    _link_to_cancel_task: tokio::sync::oneshot::Receiver<()>,

    // set to true if we send what we expect to be a final message
    // if the engine's response stream is closed before we send a final message, we can
    // detect that condition and report an unknown error engine stream termination event
    sentinel: bool,
}

// impl Drop for State {
//     fn drop(&mut self) {
//         tracing::trace!(request_id = self.stream.id(), "dropping state");
//     }
// }

#[async_trait]
impl AsyncEngine<SingleIn<BackendInput>, ManyOut<Annotated<LLMEngineOutput>>, Error> for Executor {
    async fn generate(
        &self,
        request: SingleIn<BackendInput>,
    ) -> Result<ManyOut<Annotated<LLMEngineOutput>>, Error> {
        // unpack the request and context
        let (request, context) = request.into_parts();

        // grab the core context
        let context = context.context();
        let context_cloned = context.clone();

        // create a cancellation token and request id
        let cancel_token = CancellationToken::new();
        let request_id = context.id().to_string();

        let mut engine_context = self.enqueue_request(request.into())?;
        let (mut tx, rx) = tokio::sync::oneshot::channel::<()>();

        let state = State {
            request_id,
            cancel_token: cancel_token.clone(),
            _link_to_cancel_task: rx,
            response_rx: engine_context
                .take_response_rx()
                .ok_or(Error::msg("no response rx"))?,
            sentinel: false,
        };

        // create a task to monitor the the requests cancellation state
        // todo: spawn on low priority async thread pool
        tokio::spawn(async move {
            tokio::select! {
                _ = context.stopped() => {
                    tracing::debug!(request_id = context.id(), "request cancelled");
                    engine_context.cancel();
                    cancel_token.cancel();
                }
                _ = tx.closed() => {
                    tracing::debug!(request_id = context.id(), "response stream closed");
                }
            }
        });

        // create the response stream
        let stream = stream::unfold(state, |mut state| async move {
            if state.sentinel {
                tracing::debug!(
                    request_id = state.request_id,
                    "sentinel set, closing stream"
                );
                return None;
            }

            // let output = tokio::select! {
            let output = tokio::select! {
                biased;

                // await a response from the trtllm engine's response processor
                output = state.response_rx.recv() => {
                    output
                }

                // if the stream is stopped, we need to:
                // - cancel the request on the trtll engine
                // - return an output with a finish reason of cancelled
                // - mark the state as completed by setting the sentinel to true
                _ = state.cancel_token.cancelled() => {
                    tracing::debug!(request_id = state.request_id, "request cancelled");
                    // state.engine.cancel();
                    state.sentinel = true;
                    let output = LLMEngineOutput::cancelled();
                    return Some((Annotated::from_data(output), state))
                }
            };

            match output {
                Some(Ok(output)) => {
                    if output.is_final {
                        tracing::debug!(request_id = state.request_id, "final response");
                        state.sentinel = true;
                    }
                    tracing::trace!(request_id = state.request_id, "issue response");
                    let output = LLMEngineOutput::from(output);
                    Some((Annotated::from_data(output), state))
                }
                Some(Err(err)) => {
                    tracing::debug!(request_id = state.request_id, "request failed: {:?}", err);
                    state.sentinel = true;
                    Some((Annotated::from_error(err.to_string()), state))
                }
                None => {
                    tracing::debug!(request_id = state.request_id, "request completed");
                    if !state.sentinel {
                        tracing::warn!(
                            request_id = state.request_id,
                            "engine stream terminated before final response or error"
                        );
                        state.sentinel = true;
                        Some((
                            Annotated::<LLMEngineOutput>::from_error(
                                "engine stream terminated before final response".to_string(),
                            ),
                            state,
                        ))
                    } else {
                        None
                    }
                }
            }
        });

        Ok(ResponseStream::new(Box::pin(stream), context_cloned))
    }
}