"lib/runtime/src/vscode:/vscode.git/clone" did not exist on "8a14f9edc16923f0f885f6178260abc063cf8519"
engine.rs 12.1 KB
Newer Older
1
// SPDX-FileCopyrightText: Copyright (c) 2024-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
3
// SPDX-License-Identifier: Apache-2.0

4
5
6
use std::sync::Arc;

use anyhow::{Error, Result};
7
use pyo3::prelude::*;
8
9
use pyo3::types::{PyDict, PyModule};
use pyo3::{PyAny, PyErr};
10
11
use pyo3_async_runtimes::TaskLocals;
use pythonize::{depythonize, pythonize};
12
pub use serde::{Deserialize, Serialize};
13
use tokio::sync::mpsc;
14
use tokio_stream::{StreamExt, wrappers::ReceiverStream};
15
use tokio_util::sync::CancellationToken;
16

17
use dynamo_runtime::error::{BackendError, DynamoError, ErrorType};
18
use dynamo_runtime::logging::get_distributed_tracing_context;
Neelay Shah's avatar
Neelay Shah committed
19
pub use dynamo_runtime::{
20
    pipeline::{AsyncEngine, AsyncEngineContextProvider, Data, ManyOut, ResponseStream, SingleIn},
21
    protocols::{annotated::Annotated, maybe_error::MaybeError},
22
};
23
24

use super::context::{Context, callable_accepts_kwarg};
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

/// Add bingings from this crate to the provided module
pub fn add_to_module(m: &Bound<'_, PyModule>) -> PyResult<()> {
    m.add_class::<PythonAsyncEngine>()?;
    Ok(())
}
// todos:
// - [ ] enable context cancellation
//   - this will likely require a change to the function signature python calling arguments
// - [ ] other `AsyncEngine` implementations will have a similar pattern, i.e. one AsyncEngine
//       implementation per struct

/// Rust/Python bridge that maps to the [`AsyncEngine`] trait
///
/// Currently this is only implemented for the [`SingleIn`] and [`ManyOut`] types; however,
/// more [`AsyncEngine`] implementations can be added in the future.
///
/// For the [`SingleIn`] and [`ManyOut`] case, this implementation will take a Python async
/// generator and convert it to a Rust async stream.
///
/// ```python
/// class ComputeEngine:
///     def __init__(self):
///         self.compute_engine = make_compute_engine()
///
///     def generate(self, request):
///         async generator():
///            async for output in self.compute_engine.generate(request):
///                yield output
///         return generator()
///
/// def main():
///     loop = asyncio.create_event_loop()
///     compute_engine = ComputeEngine()
///     engine = PythonAsyncEngine(compute_engine.generate, loop)
///     service = RustService()
///     service.add_engine("model_name", engine)
///     loop.run_until_complete(service.run())
/// ```
#[pyclass]
#[derive(Clone)]
66
pub struct PythonAsyncEngine(PythonServerStreamingEngine);
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81

#[pymethods]
impl PythonAsyncEngine {
    /// Create a new instance of the PythonAsyncEngine
    ///
    /// # Arguments
    /// - `generator`: a Python async generator that will be used to generate responses
    /// - `event_loop`: the Python event loop that will be used to run the generator
    ///
    /// Note: In Rust land, the request and the response are both concrete; however, in
    /// Python land, the request and response not strongly typed, meaning the generator
    /// could accept a different type of request or return a different type of response
    /// and we would not know until runtime.
    #[new]
    pub fn new(generator: PyObject, event_loop: PyObject) -> PyResult<Self> {
82
83
84
85
86
87
        let cancel_token = CancellationToken::new();
        Ok(PythonAsyncEngine(PythonServerStreamingEngine::new(
            cancel_token,
            Arc::new(generator),
            Arc::new(event_loop),
        )))
88
89
90
    }
}

91
#[async_trait::async_trait]
92
93
94
95
96
97
impl<Req, Resp> AsyncEngine<SingleIn<Req>, ManyOut<Annotated<Resp>>, Error> for PythonAsyncEngine
where
    Req: Data + Serialize,
    Resp: Data + for<'de> Deserialize<'de>,
{
    async fn generate(&self, request: SingleIn<Req>) -> Result<ManyOut<Annotated<Resp>>, Error> {
98
        self.0.generate(request).await
99
100
    }
}
101
102
103
104
105
106

#[derive(Clone)]
pub struct PythonServerStreamingEngine {
    _cancel_token: CancellationToken,
    generator: Arc<PyObject>,
    event_loop: Arc<PyObject>,
107
    has_context: bool,
108
109
110
111
112
113
114
115
}

impl PythonServerStreamingEngine {
    pub fn new(
        cancel_token: CancellationToken,
        generator: Arc<PyObject>,
        event_loop: Arc<PyObject>,
    ) -> Self {
116
        let has_context = Python::with_gil(|py| {
117
118
119
120
            let callable = generator.bind(py);
            callable_accepts_kwarg(py, callable, "context").unwrap_or(false)
        });

121
122
123
124
        PythonServerStreamingEngine {
            _cancel_token: cancel_token,
            generator,
            event_loop,
125
            has_context,
126
127
128
129
130
131
132
133
134
        }
    }
}

#[derive(Debug, thiserror::Error)]
enum ResponseProcessingError {
    #[error("python exception: {0}")]
    PythonException(String),

135
136
137
    #[error("python generator exit: {0}")]
    PyGeneratorExit(String),

138
139
140
141
142
143
144
    #[error("deserialize error: {0}")]
    DeserializeError(String),

    #[error("gil offload error: {0}")]
    OffloadError(String),
}

145
#[async_trait::async_trait]
146
147
148
149
150
151
152
153
154
155
156
157
158
159
impl<Req, Resp> AsyncEngine<SingleIn<Req>, ManyOut<Annotated<Resp>>, Error>
    for PythonServerStreamingEngine
where
    Req: Data + Serialize,
    Resp: Data + for<'de> Deserialize<'de>,
{
    async fn generate(&self, request: SingleIn<Req>) -> Result<ManyOut<Annotated<Resp>>, Error> {
        // Create a context
        let (request, context) = request.transfer(());
        let ctx = context.context();

        let id = context.id().to_string();
        tracing::trace!("processing request: {}", id);

160
161
162
        // Capture current trace context
        let current_trace_context = get_distributed_tracing_context();

163
164
165
166
167
168
169
        // Clone the PyObject to move into the thread

        // Create a channel to communicate between the Python thread and the Rust async context
        let (tx, rx) = mpsc::channel::<Annotated<Resp>>(128);

        let generator = self.generator.clone();
        let event_loop = self.event_loop.clone();
170
        let ctx_python = ctx.clone();
171
        let has_context = self.has_context;
172
173
174
175
176
177
178
179
180
181
182
183
184
185

        // Acquiring the GIL is similar to acquiring a standard lock/mutex
        // Performing this in an tokio async task could block the thread for an undefined amount of time
        // To avoid this, we spawn a blocking task to acquire the GIL and perform the operations needed
        // while holding the GIL.
        //
        // Under low GIL contention, we wouldn't need to do this.
        // However, under high GIL contention, this can lead to significant performance degradation.
        //
        // Since we cannot predict the GIL contention, we will always use the blocking task and pay the
        // cost. The Python GIL is the gift that keeps on giving -- performance hits...
        let stream = tokio::task::spawn_blocking(move || {
            Python::with_gil(|py| {
                let py_request = pythonize(py, &request)?;
186
187
188

                // Create context with trace information
                let py_ctx = Py::new(py, Context::new(ctx_python.clone(), current_trace_context))?;
189

190
                let gen_result = if has_context {
191
192
193
194
195
196
197
198
199
                    // Pass context as a kwarg
                    let kwarg = PyDict::new(py);
                    kwarg.set_item("context", &py_ctx)?;
                    generator.call(py, (py_request,), Some(&kwarg))
                } else {
                    // Legacy: No `context` arg
                    generator.call1(py, (py_request,))
                }?;

200
                let locals = TaskLocals::new(event_loop.bind(py).clone());
201
202
203
204
                pyo3_async_runtimes::tokio::into_stream_with_locals_v1(
                    locals,
                    gen_result.into_bound(py),
                )
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
            })
        })
        .await??;

        let stream = Box::pin(stream);

        // process the stream
        // any error thrown in the stream will be caught and complete the processing task
        // errors are captured by a task that is watching the processing task
        // the error will be emitted as an annotated error
        let request_id = id.clone();

        tokio::spawn(async move {
            tracing::debug!(
                request_id,
                "starting task to process python async generator stream"
            );

            let mut stream = stream;
            let mut count = 0;

            while let Some(item) = stream.next().await {
                count += 1;
                tracing::trace!(
                    request_id,
                    "processing the {}th item from python async generator",
                    count
                );

                let mut done = false;

                let response = match process_item::<Resp>(item).await {
                    Ok(response) => response,
                    Err(e) => {
                        done = true;

241
                        match e {
242
243
244
245
246
                            ResponseProcessingError::DeserializeError(e) => {
                                // tell the python async generator to stop generating
                                // right now, this is impossible as we are not passing the context to the python async generator
                                // todo: add task-local context to the python async generator
                                ctx.stop_generating();
247
                                Annotated::from_error(format!(
248
249
                                    "critical error: invalid response object from python async generator; application-logic-mismatch: {}",
                                    e
250
                                ))
251
                            }
252
253
254
255
256
257
                            ResponseProcessingError::PyGeneratorExit(_) => Annotated::from_err(
                                DynamoError::builder()
                                    .error_type(ErrorType::Backend(BackendError::EngineShutdown))
                                    .message("engine shutting down")
                                    .build(),
                            ),
258
                            ResponseProcessingError::PythonException(e) => {
259
                                Annotated::from_error(format!(
260
261
                                    "a python exception was caught while processing the async generator: {}",
                                    e
262
                                ))
263
264
                            }
                            ResponseProcessingError::OffloadError(e) => {
265
                                Annotated::from_error(format!(
266
267
                                    "critical error: failed to offload the python async generator to a new thread: {}",
                                    e
268
                                ))
269
                            }
270
                        }
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
                    }
                };

                if tx.send(response).await.is_err() {
                    tracing::trace!(
                        request_id,
                        "error forwarding annotated response to channel; channel is closed"
                    );
                    break;
                }

                if done {
                    tracing::debug!(
                        request_id,
                        "early termination of python async generator stream task"
                    );
                    break;
                }
            }

            tracing::debug!(
                request_id,
                "finished processing python async generator stream"
            );
        });

        let stream = ReceiverStream::new(rx);

        Ok(ResponseStream::new(Box::pin(stream), context.context()))
    }
}

async fn process_item<Resp>(
    item: Result<Py<PyAny>, PyErr>,
) -> Result<Annotated<Resp>, ResponseProcessingError>
where
    Resp: Data + for<'de> Deserialize<'de>,
{
    let item = item.map_err(|e| {
        println!();
311
312
313
314
315
316
317
318
319
320
        let mut is_py_generator_exit = false;
        Python::with_gil(|py| {
            e.display(py);
            is_py_generator_exit = e.is_instance_of::<pyo3::exceptions::PyGeneratorExit>(py);
        });
        if is_py_generator_exit {
            ResponseProcessingError::PyGeneratorExit(e.to_string())
        } else {
            ResponseProcessingError::PythonException(e.to_string())
        }
321
322
323
324
325
326
327
328
329
330
331
332
    })?;
    let response = tokio::task::spawn_blocking(move || {
        Python::with_gil(|py| depythonize::<Resp>(&item.into_bound(py)))
    })
    .await
    .map_err(|e| ResponseProcessingError::OffloadError(e.to_string()))?
    .map_err(|e| ResponseProcessingError::DeserializeError(e.to_string()))?;

    let response = Annotated::from_data(response);

    Ok(response)
}