queue.rs 18.2 KB
Newer Older
1
2
3
4
use crate::infer::InferError;
use crate::infer::InferStreamResponse;
use crate::validation::ValidGenerateRequest;
use nohash_hasher::{BuildNoHashHasher, IntMap};
5
use std::cmp::min;
6
use std::collections::VecDeque;
7
use text_generation_client::{Batch, Request};
OlivierDehaene's avatar
OlivierDehaene committed
8
use tokio::sync::{mpsc, oneshot};
9
use tokio::time::Instant;
10
use tracing::{info_span, instrument, Span};
11
12
13
14
15
16
17

/// Queue entry
#[derive(Debug)]
pub(crate) struct Entry {
    /// Request
    pub request: ValidGenerateRequest,
    /// Response sender to communicate between the Infer struct and the batching_task
OlivierDehaene's avatar
OlivierDehaene committed
18
    pub response_tx: mpsc::UnboundedSender<Result<InferStreamResponse, InferError>>,
19
20
21
22
23
24
    /// Span that will live as long as entry
    pub span: Span,
    /// Temporary span used as a guard when logging inference, wait times...
    pub temp_span: Option<Span>,
    /// Instant when this entry was queued
    pub queue_time: Instant,
25
26
27
28
29
30
31
32
    /// Instant when this entry was added to a batch
    pub batch_time: Option<Instant>,
}

/// Request Queue
#[derive(Debug, Clone)]
pub(crate) struct Queue {
    /// Channel to communicate with the background queue task
OlivierDehaene's avatar
OlivierDehaene committed
33
    queue_sender: mpsc::UnboundedSender<QueueCommand>,
34
35
36
}

impl Queue {
Nicolas Patry's avatar
Nicolas Patry committed
37
38
39
40
41
42
    pub(crate) fn new(
        requires_padding: bool,
        block_size: u32,
        window_size: Option<u32>,
        speculate: u32,
    ) -> Self {
43
        // Create channel
OlivierDehaene's avatar
OlivierDehaene committed
44
        let (queue_sender, queue_receiver) = mpsc::unbounded_channel();
45
46

        // Launch background queue task
47
48
49
50
        tokio::spawn(queue_task(
            requires_padding,
            block_size,
            window_size,
Nicolas Patry's avatar
Nicolas Patry committed
51
            speculate,
52
53
            queue_receiver,
        ));
54
55
56
57
58

        Self { queue_sender }
    }

    /// Append an entry to the queue
59
    #[instrument(skip_all)]
60
61
62
    pub(crate) fn append(&self, entry: Entry) {
        // Send append command to the background task managing the state
        // Unwrap is safe here
63
        self.queue_sender
64
            .send(QueueCommand::Append(Box::new(entry), Span::current()))
65
            .unwrap();
66
67
68
    }

    // Get the next batch
69
    #[instrument(skip(self))]
70
71
72
    pub(crate) async fn next_batch(
        &self,
        min_size: Option<usize>,
73
        prefill_token_budget: u32,
74
        token_budget: u32,
75
76
77
78
79
80
81
82
    ) -> Option<NextBatch> {
        // Create response channel
        let (response_sender, response_receiver) = oneshot::channel();
        // Send next batch command to the background task managing the state
        // Unwrap is safe here
        self.queue_sender
            .send(QueueCommand::NextBatch {
                min_size,
83
                prefill_token_budget,
84
                token_budget,
85
                response_sender,
86
                span: Span::current(),
87
88
89
90
91
92
93
94
95
            })
            .unwrap();
        // Await on response channel
        // Unwrap is safe here
        response_receiver.await.unwrap()
    }
}

// Background task responsible of the queue state
96
97
98
async fn queue_task(
    requires_padding: bool,
    block_size: u32,
99
    window_size: Option<u32>,
Nicolas Patry's avatar
Nicolas Patry committed
100
    speculate: u32,
OlivierDehaene's avatar
OlivierDehaene committed
101
    mut receiver: mpsc::UnboundedReceiver<QueueCommand>,
102
) {
Nicolas Patry's avatar
Nicolas Patry committed
103
    let mut state = State::new(requires_padding, block_size, window_size, speculate);
104

OlivierDehaene's avatar
OlivierDehaene committed
105
    while let Some(cmd) = receiver.recv().await {
106
        match cmd {
107
            QueueCommand::Append(entry, span) => {
108
                span.in_scope(|| state.append(*entry));
109
110
                metrics::increment_gauge!("tgi_queue_size", 1.0);
            }
111
112
            QueueCommand::NextBatch {
                min_size,
113
                prefill_token_budget,
114
                token_budget,
115
                response_sender,
116
117
                span,
            } => span.in_scope(|| {
118
                let next_batch = state.next_batch(min_size, prefill_token_budget, token_budget);
119
                response_sender.send(next_batch).unwrap();
120
                metrics::gauge!("tgi_queue_size", state.entries.len() as f64);
121
            }),
122
123
124
125
126
127
128
129
        }
    }
}

/// Queue State
#[derive(Debug)]
struct State {
    /// Queue entries organized in a Vec
130
    entries: VecDeque<(u64, Entry)>,
131
132
133
134
135
136

    /// Id of the next entry
    next_id: u64,

    /// Id of the next batch
    next_batch_id: u64,
137
138
139

    /// Whether the model is using padding
    requires_padding: bool,
140
141
142

    /// Paged Attention block size
    block_size: u32,
143
144
145

    /// Sliding window
    window_size: Option<u32>,
Nicolas Patry's avatar
Nicolas Patry committed
146
147
148

    /// Speculation amount
    speculate: u32,
149
150
151
}

impl State {
Nicolas Patry's avatar
Nicolas Patry committed
152
153
154
155
156
157
    fn new(
        requires_padding: bool,
        block_size: u32,
        window_size: Option<u32>,
        speculate: u32,
    ) -> Self {
158
        Self {
159
            entries: VecDeque::with_capacity(128),
160
161
            next_id: 0,
            next_batch_id: 0,
162
            requires_padding,
163
            block_size,
164
            window_size,
Nicolas Patry's avatar
Nicolas Patry committed
165
            speculate,
166
167
168
169
        }
    }

    /// Append an entry to the queue
170
171
172
173
174
175
    fn append(&mut self, mut entry: Entry) {
        // Create a span that will live as long as the entry is in the queue waiting to be batched
        let queue_span = info_span!(parent: &entry.span, "queued");
        entry.temp_span = Some(queue_span);

        // Push entry in the queue
176
        self.entries.push_back((self.next_id, entry));
177
178
179
180
        self.next_id += 1;
    }

    // Get the next batch
181
182
183
184
185
186
    fn next_batch(
        &mut self,
        min_size: Option<usize>,
        prefill_token_budget: u32,
        token_budget: u32,
    ) -> Option<NextBatch> {
187
188
189
190
191
192
193
194
195
196
197
        if self.entries.is_empty() {
            return None;
        }

        // Check if we have enough entries
        if let Some(min_size) = min_size {
            if self.entries.len() < min_size {
                return None;
            }
        }

198
        // Create span for this batch to add context to inference calls
199
        let next_batch_span = info_span!(parent: None, "batch", batch_size = tracing::field::Empty);
200
201
        next_batch_span.follows_from(&Span::current());

202
        let mut batch_requests = Vec::with_capacity(self.entries.len());
203
        let mut batch_entries =
204
            IntMap::with_capacity_and_hasher(self.entries.len(), BuildNoHashHasher::default());
205

206
207
208
209
210
        let mut max_input_length = 0;
        let mut prefill_tokens: u32 = 0;
        let mut decode_tokens: u32 = 0;

        // Pop entries starting from the front of the queue
211
212
213
        while let Some((id, mut entry)) = self.entries.pop_front() {
            // Filter entries where the response receiver was dropped (== entries where the request
            // was dropped by the client)
OlivierDehaene's avatar
OlivierDehaene committed
214
            if entry.response_tx.is_closed() {
215
216
217
218
                metrics::increment_counter!("tgi_request_failure", "err" => "dropped");
                continue;
            }

219
220
221
222
223
224
            if self.requires_padding {
                // We pad to max input length in the Python shards
                // We need to take these padding tokens into the equation
                max_input_length = max_input_length.max(entry.request.input_length);
                prefill_tokens = (batch_requests.len() + 1) as u32 * max_input_length
            } else {
225
226
227
228
                // pad to block size
                prefill_tokens += ((entry.request.input_length + self.block_size - 1)
                    / self.block_size)
                    * self.block_size;
229
230
            }

231
232
233
            if self.requires_padding {
                decode_tokens += entry.request.stopping_parameters.max_new_tokens;
            } else {
234
235
236
237
238
239
240
241
                let max_new_tokens = match self.window_size {
                    None => entry.request.stopping_parameters.max_new_tokens,
                    Some(window_size) => min(
                        window_size.saturating_sub(entry.request.input_length),
                        entry.request.stopping_parameters.max_new_tokens,
                    ),
                };

242
243
                // pad to block size
                decode_tokens +=
244
                    ((max_new_tokens + self.block_size - 1) / self.block_size) * self.block_size;
245
            }
246

247
            if prefill_tokens > prefill_token_budget
Nicolas Patry's avatar
Nicolas Patry committed
248
                || (prefill_tokens + decode_tokens + self.speculate) > token_budget
249
            {
250
251
252
253
254
255
                // Entry is over budget
                // Add it back to the front
                self.entries.push_front((id, entry));
                break;
            }

256
257
258
259
260
261
262
263
264
265
            // Create a new span to link the batch back to this entry
            let entry_batch_span = info_span!(parent: &entry.span, "infer");
            // Add relationships
            next_batch_span.follows_from(&entry_batch_span);
            entry_batch_span.follows_from(&next_batch_span);
            // Update entry
            entry.temp_span = Some(entry_batch_span);

            batch_requests.push(Request {
                id,
266
                prefill_logprobs: entry.request.decoder_input_details,
267
268
269
270
                inputs: entry.request.inputs.clone(),
                truncate: entry.request.truncate,
                parameters: Some(entry.request.parameters.clone()),
                stopping_parameters: Some(entry.request.stopping_parameters.clone()),
Nicolas Patry's avatar
Nicolas Patry committed
271
                top_n_tokens: entry.request.top_n_tokens,
272
            });
273
274
275
276
277
278
            // Set batch_time
            entry.batch_time = Some(Instant::now());
            // Insert in batch_entries IntMap
            batch_entries.insert(id, entry);
        }

279
        // Empty batch
280
281
282
283
        if batch_requests.is_empty() {
            return None;
        }

284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
        // Check if our batch is big enough
        if let Some(min_size) = min_size {
            // Batch is too small
            if batch_requests.len() < min_size {
                // Add back entries to the queue in the correct order
                for r in batch_requests.into_iter().rev() {
                    let id = r.id;
                    let entry = batch_entries.remove(&id).unwrap();
                    self.entries.push_front((id, entry));
                }

                return None;
            }
        }

        // Final batch size
300
301
        let size = batch_requests.len() as u32;
        next_batch_span.record("batch_size", size);
302
303
304
305

        let batch = Batch {
            id: self.next_batch_id,
            requests: batch_requests,
306
            size,
307
            max_tokens: (prefill_tokens + decode_tokens),
308
309
310
311
        };
        // Increment batch id
        self.next_batch_id += 1;

312
        metrics::histogram!("tgi_batch_next_size", batch.size as f64);
313

314
        Some((batch_entries, batch, next_batch_span))
315
316
317
    }
}

318
type NextBatch = (IntMap<u64, Entry>, Batch, Span);
319
320
321

#[derive(Debug)]
enum QueueCommand {
322
    Append(Box<Entry>, Span),
323
324
    NextBatch {
        min_size: Option<usize>,
325
        prefill_token_budget: u32,
326
        token_budget: u32,
327
        response_sender: oneshot::Sender<Option<NextBatch>>,
328
        span: Span,
329
330
331
332
333
334
335
    },
}

#[cfg(test)]
mod tests {
    use super::*;
    use text_generation_client::{NextTokenChooserParameters, StoppingCriteriaParameters};
336
    use tracing::info_span;
337

338
339
    fn default_entry() -> (
        Entry,
OlivierDehaene's avatar
OlivierDehaene committed
340
        mpsc::UnboundedReceiver<Result<InferStreamResponse, InferError>>,
341
    ) {
OlivierDehaene's avatar
OlivierDehaene committed
342
        let (response_tx, receiver_tx) = mpsc::unbounded_channel();
343

344
        let entry = Entry {
345
346
            request: ValidGenerateRequest {
                inputs: "".to_string(),
347
                input_length: 0,
348
                truncate: 0,
349
                decoder_input_details: false,
350
351
352
353
                parameters: NextTokenChooserParameters {
                    temperature: 0.0,
                    top_k: 0,
                    top_p: 0.0,
354
                    typical_p: 0.0,
355
356
357
                    do_sample: false,
                    seed: 0,
                    repetition_penalty: 0.0,
358
                    frequency_penalty: 0.0,
359
                    watermark: false,
360
361
                },
                stopping_parameters: StoppingCriteriaParameters {
362
                    ignore_eos_token: false,
363
                    max_new_tokens: 1,
364
365
                    stop_sequences: vec![],
                },
Nicolas Patry's avatar
Nicolas Patry committed
366
                top_n_tokens: 0,
367
368
            },
            response_tx,
369
370
371
            span: info_span!("entry"),
            temp_span: None,
            queue_time: Instant::now(),
372
            batch_time: None,
373
374
        };
        (entry, receiver_tx)
375
376
377
378
    }

    #[test]
    fn test_append() {
Nicolas Patry's avatar
Nicolas Patry committed
379
        let mut state = State::new(false, 1, None, 0);
380
        let (entry, _guard) = default_entry();
381
382
383
384
385
386
387
388

        assert_eq!(state.next_id, 0);
        assert_eq!(state.entries.len(), 0);

        state.append(entry);

        assert_eq!(state.next_id, 1);
        assert_eq!(state.entries.len(), 1);
389
        let (id, _) = state.entries.remove(0).unwrap();
390
391
392
393
394
        assert_eq!(id, 0);
    }

    #[test]
    fn test_next_batch_empty() {
Nicolas Patry's avatar
Nicolas Patry committed
395
        let mut state = State::new(false, 1, None, 0);
396

397
398
        assert!(state.next_batch(None, 1, 1).is_none());
        assert!(state.next_batch(Some(1), 1, 1).is_none());
399
400
401
402
    }

    #[test]
    fn test_next_batch_min_size() {
Nicolas Patry's avatar
Nicolas Patry committed
403
        let mut state = State::new(false, 1, None, 0);
404
405
406
407
        let (entry1, _guard1) = default_entry();
        let (entry2, _guard2) = default_entry();
        state.append(entry1);
        state.append(entry2);
408

409
        let (entries, batch, _) = state.next_batch(None, 2, 2).unwrap();
410
411
412
413
414
415
416
417
418
419
420
421
        assert_eq!(entries.len(), 2);
        assert!(entries.contains_key(&0));
        assert!(entries.contains_key(&1));
        assert!(entries.get(&0).unwrap().batch_time.is_some());
        assert!(entries.get(&1).unwrap().batch_time.is_some());
        assert_eq!(batch.id, 0);
        assert_eq!(batch.size, 2);

        assert_eq!(state.next_id, 2);
        assert_eq!(state.entries.len(), 0);
        assert_eq!(state.next_batch_id, 1);

422
423
        let (entry3, _guard3) = default_entry();
        state.append(entry3);
424

425
        assert!(state.next_batch(Some(2), 2, 2).is_none());
426
427
428

        assert_eq!(state.next_id, 3);
        assert_eq!(state.entries.len(), 1);
429
        let (id, _) = state.entries.remove(0).unwrap();
430
431
432
433
        assert_eq!(id, 2);
    }

    #[test]
434
    fn test_next_batch_token_budget() {
Nicolas Patry's avatar
Nicolas Patry committed
435
        let mut state = State::new(false, 1, None, 0);
436
437
438
439
        let (entry1, _guard1) = default_entry();
        let (entry2, _guard2) = default_entry();
        state.append(entry1);
        state.append(entry2);
440

441
        let (entries, batch, _) = state.next_batch(None, 1, 1).unwrap();
442
443
444
445
446
447
448
449
450
        assert_eq!(entries.len(), 1);
        assert!(entries.contains_key(&0));
        assert_eq!(batch.id, 0);
        assert_eq!(batch.size, 1);

        assert_eq!(state.next_id, 2);
        assert_eq!(state.entries.len(), 1);
        assert_eq!(state.next_batch_id, 1);

451
452
        let (entry3, _guard3) = default_entry();
        state.append(entry3);
453

454
        let (entries, batch, _) = state.next_batch(None, 3, 3).unwrap();
455
456
457
458
459
460
461
462
463
464
465
466
467
        assert_eq!(entries.len(), 2);
        assert!(entries.contains_key(&1));
        assert!(entries.contains_key(&2));
        assert_eq!(batch.id, 1);
        assert_eq!(batch.size, 2);

        assert_eq!(state.next_id, 3);
        assert_eq!(state.entries.len(), 0);
        assert_eq!(state.next_batch_id, 2);
    }

    #[tokio::test]
    async fn test_queue_append() {
Nicolas Patry's avatar
Nicolas Patry committed
468
        let queue = Queue::new(false, 1, None, 0);
469
470
        let (entry, _guard) = default_entry();
        queue.append(entry);
471
472
473
474
    }

    #[tokio::test]
    async fn test_queue_next_batch_empty() {
Nicolas Patry's avatar
Nicolas Patry committed
475
        let queue = Queue::new(false, 1, None, 0);
476

477
478
        assert!(queue.next_batch(None, 1, 1).await.is_none());
        assert!(queue.next_batch(Some(1), 1, 1).await.is_none());
479
480
481
482
    }

    #[tokio::test]
    async fn test_queue_next_batch_min_size() {
Nicolas Patry's avatar
Nicolas Patry committed
483
        let queue = Queue::new(false, 1, None, 0);
484
485
486
487
        let (entry1, _guard1) = default_entry();
        let (entry2, _guard2) = default_entry();
        queue.append(entry1);
        queue.append(entry2);
488

489
        let (entries, batch, _) = queue.next_batch(None, 2, 2).await.unwrap();
490
491
492
493
494
495
496
497
        assert_eq!(entries.len(), 2);
        assert!(entries.contains_key(&0));
        assert!(entries.contains_key(&1));
        assert!(entries.get(&0).unwrap().batch_time.is_some());
        assert!(entries.get(&1).unwrap().batch_time.is_some());
        assert_eq!(batch.id, 0);
        assert_eq!(batch.size, 2);

498
499
        let (entry3, _guard3) = default_entry();
        queue.append(entry3);
500

501
        // Not enough requests pending
502
        assert!(queue.next_batch(Some(2), 2, 2).await.is_none());
503
        // Not enough token budget
504
        assert!(queue.next_batch(Some(1), 0, 0).await.is_none());
505
        // Ok
506
        let (entries2, batch2, _) = queue.next_batch(Some(1), 2, 2).await.unwrap();
507
508
509
510
511
        assert_eq!(entries2.len(), 1);
        assert!(entries2.contains_key(&2));
        assert!(entries2.get(&2).unwrap().batch_time.is_some());
        assert_eq!(batch2.id, 1);
        assert_eq!(batch2.size, 1);
512
513
514
    }

    #[tokio::test]
515
    async fn test_queue_next_batch_token_budget() {
Nicolas Patry's avatar
Nicolas Patry committed
516
        let queue = Queue::new(false, 1, None, 0);
517
518
519
520
        let (entry1, _guard1) = default_entry();
        let (entry2, _guard2) = default_entry();
        queue.append(entry1);
        queue.append(entry2);
521

522
        let (entries, batch, _) = queue.next_batch(None, 1, 1).await.unwrap();
523
524
525
526
527
        assert_eq!(entries.len(), 1);
        assert!(entries.contains_key(&0));
        assert_eq!(batch.id, 0);
        assert_eq!(batch.size, 1);

528
529
        let (entry3, _guard3) = default_entry();
        queue.append(entry3);
530

531
        let (entries, batch, _) = queue.next_batch(None, 3, 3).await.unwrap();
532
533
534
535
536
537
        assert_eq!(entries.len(), 2);
        assert!(entries.contains_key(&1));
        assert!(entries.contains_key(&2));
        assert_eq!(batch.id, 1);
        assert_eq!(batch.size, 2);
    }
538

Nicolas Patry's avatar
Nicolas Patry committed
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
    #[tokio::test]
    async fn test_queue_next_batch_token_speculate() {
        let queue = Queue::new(false, 1, None, 2);
        let (entry1, _guard1) = default_entry();
        let (entry2, _guard2) = default_entry();
        queue.append(entry1);
        queue.append(entry2);

        // Budget of 1 is not enough
        assert!(queue.next_batch(None, 1, 1).await.is_none());

        let (entries, batch, _) = queue.next_batch(None, 6, 6).await.unwrap();
        assert_eq!(entries.len(), 2);
        assert!(entries.contains_key(&0));
        assert!(entries.contains_key(&1));
        assert_eq!(batch.id, 0);
        assert_eq!(batch.size, 2);
    }

558
559
    #[tokio::test]
    async fn test_queue_next_batch_dropped_receiver() {
Nicolas Patry's avatar
Nicolas Patry committed
560
        let queue = Queue::new(false, 1, None, 0);
561
562
563
        let (entry, _) = default_entry();
        queue.append(entry);

564
        assert!(queue.next_batch(None, 1, 1).await.is_none());
565
    }
566
}