engine.rs 18.9 KB
Newer Older
1
// SPDX-FileCopyrightText: Copyright (c) 2024-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
3
4
5
6
7
8
// SPDX-License-Identifier: Apache-2.0

//! MockSchedulerEngine - AsyncEngine wrapper around the Scheduler
//!
//! This module provides an AsyncEngine implementation that wraps the Scheduler
//! to provide streaming token generation with realistic timing simulation.

9
10
11
12
13
14
15
16
17
use std::collections::HashMap;
use std::sync::Arc;
use std::time::Duration;

use anyhow::Result;
use futures::StreamExt;
use rand::Rng;
use tokio::sync::{Mutex, OnceCell, mpsc};
use tokio_stream::wrappers::UnboundedReceiverStream;
18
use tokio_util::sync::CancellationToken;
19
use uuid::Uuid;
20

21
22
use dynamo_runtime::DistributedRuntime;
use dynamo_runtime::protocols::annotated::Annotated;
23
24
25
use dynamo_runtime::{
    component::Component,
    engine::AsyncEngineContextProvider,
26
    pipeline::{AsyncEngine, Error, ManyOut, ResponseStream, SingleIn, async_trait},
27
28
    traits::DistributedRuntimeProvider,
};
29
30

use crate::kv_router::publisher::WorkerMetricsPublisher;
31
use crate::mocker::bootstrap::{BootstrapServer, connect_to_prefill};
32
33
34
35
36
use crate::mocker::protocols::DirectRequest;
use crate::mocker::protocols::{MockEngineArgs, OutputSignal, WorkerType};
use crate::mocker::scheduler::Scheduler;
use crate::protocols::TokenIdType;
use crate::protocols::common::llm_backend::{LLMEngineOutput, PreprocessedRequest};
37
38
39
40
41

pub const MOCKER_COMPONENT: &str = "mocker";

fn generate_random_token() -> TokenIdType {
    let mut rng = rand::rng();
Yan Ru Pei's avatar
Yan Ru Pei committed
42
    rng.random_range(1000..2000)
43
44
45
46
47
48
49
50
}

/// AsyncEngine wrapper around the Scheduler that generates random character tokens
#[derive(Clone)]
pub struct MockVllmEngine {
    active_requests: Arc<Mutex<HashMap<Uuid, mpsc::UnboundedSender<OutputSignal>>>>,
    request_senders: Arc<OnceCell<Vec<mpsc::UnboundedSender<DirectRequest>>>>,
    engine_args: MockEngineArgs,
51
52
    /// Bootstrap server for prefill workers in disaggregated mode
    bootstrap_server: Arc<OnceCell<Arc<BootstrapServer>>>,
53
54
55
56
57
58
59
60
61
}

impl MockVllmEngine {
    /// Create a new MockVllmEngine with the given parameters
    pub fn new(args: MockEngineArgs) -> Self {
        Self {
            active_requests: Arc::new(Mutex::new(HashMap::new())),
            request_senders: Arc::new(OnceCell::new()),
            engine_args: args,
62
            bootstrap_server: Arc::new(OnceCell::new()),
63
64
65
66
        }
    }

    pub async fn start(&self, component: Component) -> Result<()> {
67
68
69
70
71
        // Use primary_token() instead of child_token() so the mocker continues running
        // during graceful shutdown (Phase 1/2) and only stops in Phase 3.
        // child_token() is a child of endpoint_shutdown_token which is cancelled in Phase 1.
        // primary_token() is only cancelled in Phase 3, after waiting for inflight requests.
        let cancel_token = component.drt().primary_token();
72

73
74
75
76
77
78
79
        // Simulate engine startup time if configured
        if let Some(startup_time_secs) = self.engine_args.startup_time {
            tracing::info!("Simulating engine startup time: {:.2}s", startup_time_secs);
            tokio::time::sleep(Duration::from_secs_f64(startup_time_secs)).await;
            tracing::info!("Engine startup simulation completed");
        }

80
81
82
83
84
85
86
87
88
        // Start bootstrap server for prefill workers in disaggregated mode
        if self.engine_args.worker_type == WorkerType::Prefill
            && let Some(port) = self.engine_args.bootstrap_port
        {
            let server = BootstrapServer::start(port, cancel_token.clone()).await?;
            let _ = self.bootstrap_server.set(server);
            tracing::info!(port = port, "Bootstrap server started for prefill worker");
        }

Yan Ru Pei's avatar
Yan Ru Pei committed
89
90
91
92
93
94
95
96
97
98
        // Pass component to schedulers only if prefix caching is enabled and not a decode worker
        let scheduler_component = if self.engine_args.enable_prefix_caching
            && self.engine_args.worker_type != WorkerType::Decode
        {
            Some(component.clone())
        } else {
            None
        };

        let schedulers = self.start_schedulers(
99
100
            self.engine_args.clone(),
            self.active_requests.clone(),
Yan Ru Pei's avatar
Yan Ru Pei committed
101
            scheduler_component,
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
            cancel_token.clone(),
        );

        Self::start_metrics_publishing(&schedulers, Some(component.clone()), cancel_token.clone())
            .await?;

        Ok(())
    }

    pub fn direct(&self, request: DirectRequest, dp_rank: usize) {
        let senders = self.request_senders.get().expect("Not initialized");
        let _ = senders[dp_rank].send(request);
    }

    /// Create schedulers and spawn their background tasks for distributing token notifications
    fn start_schedulers(
        &self,
        args: MockEngineArgs,
        active_requests: Arc<Mutex<HashMap<Uuid, mpsc::UnboundedSender<OutputSignal>>>>,
Yan Ru Pei's avatar
Yan Ru Pei committed
121
        component: Option<Component>,
122
        cancel_token: CancellationToken,
Yan Ru Pei's avatar
Yan Ru Pei committed
123
    ) -> Vec<Scheduler> {
124
125
126
127
128
129
130
131
132
133
        let mut schedulers = Vec::<Scheduler>::new();
        let mut senders = Vec::with_capacity(args.dp_size as usize);

        // Create multiple schedulers and their background tasks
        for dp_rank in 0..args.dp_size {
            // Create a shared output channel that this scheduler will use
            let (output_tx, mut output_rx) = mpsc::unbounded_channel::<OutputSignal>();

            let scheduler = Scheduler::new(
                args.clone(),
Yan Ru Pei's avatar
Yan Ru Pei committed
134
                dp_rank,
135
                Some(output_tx),
Yan Ru Pei's avatar
Yan Ru Pei committed
136
                component.clone(),
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
                Some(cancel_token.clone()),
            );

            senders.push(scheduler.request_sender());
            schedulers.push(scheduler);

            // Spawn a background task for this scheduler to distribute token notifications to active requests
            // let output_rx = Arc::new(Mutex::new(output_rx));
            let active_requests_clone = active_requests.clone();
            let cancel_token_cloned = cancel_token.clone();

            tokio::spawn(async move {
                loop {
                    tokio::select! {
                        signal_result = output_rx.recv() => {
                            let Some(signal) = signal_result else {
                                break; // Channel closed
                            };

                            // Notify the specific request that a token was generated
                            let active = active_requests_clone.lock().await;
                            if let Some(request_tx) = active.get(&signal.uuid) {
                                let _ = request_tx.send(signal);
                            }
                        }
                        _ = cancel_token_cloned.cancelled() => {
163
164
165
166
167
                            tracing::info!("Scheduler output task cancelled, clearing active requests");
                            // Clear all active requests to unblock waiting request handlers
                            // This will cause their request_rx.recv() to return None
                            let mut active = active_requests_clone.lock().await;
                            active.clear();
168
169
170
171
172
173
174
175
176
177
178
179
                            break;
                        }
                    }
                }
            });
        }

        // Set the senders once
        self.request_senders
            .set(senders)
            .expect("Already initialized");

Yan Ru Pei's avatar
Yan Ru Pei committed
180
        schedulers
181
182
    }

183
    /// Start background tasks to publish metrics on change
184
185
186
187
188
    async fn start_metrics_publishing(
        schedulers: &[Scheduler],
        component: Option<Component>,
        cancel_token: CancellationToken,
    ) -> Result<()> {
189
        tracing::debug!("Creating metrics publisher");
190
        let metrics_publisher = Arc::new(WorkerMetricsPublisher::new()?);
191
        tracing::debug!("Metrics publisher created");
192
193

        if let Some(comp) = component {
194
            tracing::debug!("Creating metrics endpoint");
195
196
197
            tokio::spawn({
                let publisher = metrics_publisher.clone();
                async move {
198
                    if let Err(e) = publisher.create_endpoint(comp.clone()).await {
199
200
201
202
203
204
205
                        tracing::error!("Metrics endpoint failed: {e}");
                    }
                }
            });

            // Give it a moment to start
            tokio::time::sleep(Duration::from_millis(100)).await;
206
            tracing::debug!("Metrics endpoint started (background)");
207
208
        }

209
        tracing::debug!("Starting metrics background tasks");
210
        for scheduler in schedulers.iter() {
211
            let mut metrics_rx = scheduler.metrics_receiver();
212
213
214
215
216
217
            let publisher = metrics_publisher.clone();
            let cancel_token = cancel_token.clone();

            tokio::spawn(async move {
                loop {
                    tokio::select! {
218
219
220
221
                        // Watch for metrics changes
                        Ok(_) = metrics_rx.changed() => {
                            // Get the latest metrics
                            let metrics = metrics_rx.borrow().clone();
222

223
224
225
                            // Publish metrics using flat API
                            if let Err(e) = publisher.publish(Some(metrics.dp_rank), metrics.active_decode_blocks) {
                                tracing::warn!("Failed to publish metrics for DP rank {}: {e}", metrics.dp_rank);
226
                            } else {
227
                                tracing::trace!("Published metrics for DP rank {}", metrics.dp_rank);
228
229
230
                            }
                        }
                        _ = cancel_token.cancelled() => {
231
                            tracing::debug!("Metrics publishing cancelled");
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
                            break;
                        }
                    }
                }
            });
        }
        tracing::info!("Metrics background tasks started");
        Ok(())
    }
}

#[async_trait]
impl AsyncEngine<SingleIn<PreprocessedRequest>, ManyOut<LLMEngineOutput>, Error>
    for MockVllmEngine
{
    async fn generate(
        &self,
        input: SingleIn<PreprocessedRequest>,
    ) -> Result<ManyOut<LLMEngineOutput>, Error> {
        let (request, ctx) = input.into_parts();

253
254
255
256
257
258
        // Extract dp_rank from routing hints (defaults to 0 if not set)
        let dp_rank = request
            .routing
            .as_ref()
            .and_then(|r| r.dp_rank)
            .unwrap_or(0);
259
260
261
262
263
264
265
266
267

        // Validate dp_rank
        if dp_rank >= self.engine_args.dp_size {
            return Err(Error::msg(format!(
                "dp_rank {} is out of bounds for dp_size {}",
                dp_rank, self.engine_args.dp_size
            )));
        }

268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
        // Bootstrap rendezvous for disaggregated serving
        // - Decode: connect to prefill's server, block until prefill completes
        // - Prefill: complete_room() is called after first token (see below)
        let bootstrap_room = request.bootstrap_info.as_ref().map(|b| b.bootstrap_room);
        if let Some(bootstrap_info) = &request.bootstrap_info
            && self.engine_args.worker_type == WorkerType::Decode
        {
            connect_to_prefill(
                &bootstrap_info.bootstrap_host,
                bootstrap_info.bootstrap_port,
                bootstrap_info.bootstrap_room,
            )
            .await
            .map_err(|e| Error::msg(format!("Bootstrap connection failed: {e}")))?;
        }

284
285
        let request_uuid = ctx.id().parse().unwrap_or(Uuid::new_v4());

Yan Ru Pei's avatar
Yan Ru Pei committed
286
287
288
289
290
291
292
293
294
295
296
        // For prefill workers, override max_tokens to 1
        let is_prefill = self.engine_args.worker_type == WorkerType::Prefill;
        let max_output_tokens = if is_prefill {
            1
        } else {
            request
                .stop_conditions
                .max_tokens
                .expect("max_output_tokens must be specified for mocker") as usize
        };

297
298
299
        // Convert PreprocessedRequest to DirectRequest for scheduler
        let direct_request = DirectRequest {
            tokens: request.token_ids.clone(),
Yan Ru Pei's avatar
Yan Ru Pei committed
300
            max_output_tokens,
301
            uuid: Some(request_uuid),
Yan Ru Pei's avatar
Yan Ru Pei committed
302
            dp_rank,
303
304
305
306
307
308
309
310
311
312
313
314
        };

        let (request_tx, mut request_rx) = mpsc::unbounded_channel::<OutputSignal>();
        {
            let mut active = self.active_requests.lock().await;
            active.insert(request_uuid, request_tx);
        }

        // Send the request to the appropriate scheduler based on dp_rank
        self.direct(direct_request, dp_rank as usize);

        // Create a simple channel for the stream
315
        let (stream_tx, stream_rx) = mpsc::unbounded_channel::<LLMEngineOutput>();
316
317
318

        let active_requests = self.active_requests.clone();
        let async_context = ctx.context();
319
        let bootstrap_server = self.bootstrap_server.clone();
320
321
322
323
324
325
326
327
328

        // Spawn a task to handle the complex async logic
        tokio::spawn(async move {
            let mut token_count = 0;

            loop {
                tokio::select! {
                    maybe_signal = request_rx.recv() => {
                        let Some(signal) = maybe_signal else {
329
                            let _ = stream_tx.send(LLMEngineOutput::error("All output transmitters closed".to_string()));
330
331
332
333
334
335
336
337
338
339
340
341
342
                            break;
                        };

                        // Generate a new token
                        let token_id = generate_random_token();
                        token_count += 1;

                        let output = LLMEngineOutput {
                            token_ids: vec![token_id],
                            tokens: None,  // Let backend handle detokenization
                            text: None,
                            cum_log_probs: None,
                            log_probs: None,
Greg Clark's avatar
Greg Clark committed
343
                            top_logprobs: None,
344
                            finish_reason: None,
345
                            stop_reason: None,
346
                            index: None,
Yan Ru Pei's avatar
Yan Ru Pei committed
347
348
349
350
351
352
                            // Add dummy disaggregated_params for prefill workers
                            disaggregated_params: if is_prefill {
                                Some(serde_json::json!("dummy"))
                            } else {
                                None
                            },
353
                            extra_args: None,
354
                            completion_usage: None,
355
356
                        };

357
358
359
360
361
362
363
364
                        // Prefill: after first token, mark room complete (unblocks decode)
                        if is_prefill
                            && token_count == 1
                            && let (Some(server), Some(room_id)) = (bootstrap_server.get(), bootstrap_room)
                        {
                            server.complete_room(room_id);
                        }

Yan Ru Pei's avatar
Yan Ru Pei committed
365
                        if signal.completed && token_count < max_output_tokens {
366
367
368
369
370
371
372
373
374
375
376
377
                            let _ = stream_tx.send(LLMEngineOutput::error("Completion signal received before max tokens reached".to_string()));
                            break;
                        }

                        if signal.completed {
                            let _ = stream_tx.send(output);
                            let _ = stream_tx.send(LLMEngineOutput::length());
                            break;
                        }

                        if stream_tx.send(output).is_err() {
                            tracing::error!("Output stream receiver closed.");
378
379
380
381
382
                            break;
                        }
                    }

                    _ = async_context.stopped() => {
383
                        let _ = stream_tx.send(LLMEngineOutput::cancelled());
384
385
386
387
388
389
390
391
392
393
                        break;
                    }
                }
            }

            // Clean up: remove this request from active requests
            let mut active = active_requests.lock().await;
            active.remove(&request_uuid);
        });

394
395
        // Create a simple UnboundedReceiverStream which is naturally Send + Sync
        let stream = UnboundedReceiverStream::new(stream_rx);
396
397
398
399
400
401
402
403
404
405
406
407
        Ok(ResponseStream::new(Box::pin(stream), ctx.context()))
    }
}

pub struct AnnotatedMockEngine {
    inner: Arc<MockVllmEngine>,
}

impl AnnotatedMockEngine {
    pub fn new(
        inner: MockVllmEngine,
        distributed_runtime: DistributedRuntime,
408
        endpoint_id: dynamo_runtime::protocols::EndpointId,
409
410
411
412
413
414
415
416
    ) -> Self {
        let inner = Arc::new(inner);
        let inner_clone = inner.clone();

        // Start background task to wait for component service and start the engine
        tokio::spawn(async move {
            loop {
                // Try to create component
417
                let Ok(namespace) = distributed_runtime.namespace(&endpoint_id.namespace) else {
418
419
420
421
422
                    tracing::debug!("Namespace not available yet, retrying...");
                    tokio::time::sleep(Duration::from_millis(100)).await;
                    continue;
                };

423
                let Ok(component) = namespace.component(&endpoint_id.component) else {
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
                    tracing::debug!("Component not available yet, retrying...");
                    tokio::time::sleep(Duration::from_millis(100)).await;
                    continue;
                };

                // Check if service is available by trying to list instances
                let Ok(instances) = component.list_instances().await else {
                    tracing::debug!("Cannot list instances yet, retrying...");
                    tokio::time::sleep(Duration::from_millis(100)).await;
                    continue;
                };

                if instances.is_empty() {
                    tracing::debug!("No instances available yet, retrying...");
                    tokio::time::sleep(Duration::from_millis(100)).await;
                    continue;
                }

442
                tracing::debug!("Component service is now available, starting mocker engine");
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476

                // Start the engine with the component
                if let Err(e) = inner_clone.start(component).await {
                    tracing::error!("Failed to start mocker engine: {e}");
                }
                break;
            }
        });

        Self { inner }
    }
}

#[async_trait]
impl AsyncEngine<SingleIn<PreprocessedRequest>, ManyOut<Annotated<LLMEngineOutput>>, Error>
    for AnnotatedMockEngine
{
    async fn generate(
        &self,
        input: SingleIn<PreprocessedRequest>,
    ) -> Result<ManyOut<Annotated<LLMEngineOutput>>, Error> {
        let stream = self.inner.generate(input).await?;
        let context = stream.context();

        // Convert stream of LLMEngineOutput to Annotated<LLMEngineOutput>
        let annotated_stream = stream.map(Annotated::from_data);

        Ok(ResponseStream::new(Box::pin(annotated_stream), context))
    }
}

/// Create a mocker engine as ExecutionContext
pub async fn make_mocker_engine(
    distributed_runtime: DistributedRuntime,
477
    endpoint_id: dynamo_runtime::protocols::EndpointId,
478
479
480
    args: MockEngineArgs,
) -> Result<crate::backend::ExecutionContext, Error> {
    // Create the mocker engine
Yan Ru Pei's avatar
Yan Ru Pei committed
481
    tracing::info!("Creating mocker engine with config: {args:?}");
482
    let annotated_engine =
483
        AnnotatedMockEngine::new(MockVllmEngine::new(args), distributed_runtime, endpoint_id);
484
485
486

    Ok(Arc::new(annotated_engine))
}