queue.rs 17.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};
8
use tokio::sync::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
18
    pub response_tx: flume::Sender<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
33
    queue_sender: flume::Sender<QueueCommand>,
34
35
36
}

impl Queue {
37
    pub(crate) fn new(requires_padding: bool, block_size: u32, window_size: Option<u32>) -> Self {
38
        // Create channel
39
        let (queue_sender, queue_receiver) = flume::unbounded();
40
41

        // Launch background queue task
42
43
44
45
46
47
        tokio::spawn(queue_task(
            requires_padding,
            block_size,
            window_size,
            queue_receiver,
        ));
48
49
50
51
52

        Self { queue_sender }
    }

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

    // Get the next batch
63
    #[instrument(skip(self))]
64
65
66
    pub(crate) async fn next_batch(
        &self,
        min_size: Option<usize>,
67
        prefill_token_budget: u32,
68
        token_budget: u32,
69
70
71
72
73
74
75
76
    ) -> 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,
77
                prefill_token_budget,
78
                token_budget,
79
                response_sender,
80
                span: Span::current(),
81
82
83
84
85
86
87
88
89
            })
            .unwrap();
        // Await on response channel
        // Unwrap is safe here
        response_receiver.await.unwrap()
    }
}

// Background task responsible of the queue state
90
91
92
async fn queue_task(
    requires_padding: bool,
    block_size: u32,
93
    window_size: Option<u32>,
94
95
    receiver: flume::Receiver<QueueCommand>,
) {
96
    let mut state = State::new(requires_padding, block_size, window_size);
97

98
    while let Ok(cmd) = receiver.recv_async().await {
99
        match cmd {
100
            QueueCommand::Append(entry, span) => {
101
                span.in_scope(|| state.append(*entry));
102
103
                metrics::increment_gauge!("tgi_queue_size", 1.0);
            }
104
105
            QueueCommand::NextBatch {
                min_size,
106
                prefill_token_budget,
107
                token_budget,
108
                response_sender,
109
110
                span,
            } => span.in_scope(|| {
111
                let next_batch = state.next_batch(min_size, prefill_token_budget, token_budget);
112
                response_sender.send(next_batch).unwrap();
113
                metrics::gauge!("tgi_queue_size", state.entries.len() as f64);
114
            }),
115
116
117
118
119
120
121
122
        }
    }
}

/// Queue State
#[derive(Debug)]
struct State {
    /// Queue entries organized in a Vec
123
    entries: VecDeque<(u64, Entry)>,
124
125
126
127
128
129

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

    /// Id of the next batch
    next_batch_id: u64,
130
131
132

    /// Whether the model is using padding
    requires_padding: bool,
133
134
135

    /// Paged Attention block size
    block_size: u32,
136
137
138

    /// Sliding window
    window_size: Option<u32>,
139
140
141
}

impl State {
142
    fn new(requires_padding: bool, block_size: u32, window_size: Option<u32>) -> Self {
143
        Self {
144
            entries: VecDeque::with_capacity(128),
145
146
            next_id: 0,
            next_batch_id: 0,
147
            requires_padding,
148
            block_size,
149
            window_size,
150
151
152
153
        }
    }

    /// Append an entry to the queue
154
155
156
157
158
159
    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
160
        self.entries.push_back((self.next_id, entry));
161
162
163
164
        self.next_id += 1;
    }

    // Get the next batch
165
166
167
168
169
170
    fn next_batch(
        &mut self,
        min_size: Option<usize>,
        prefill_token_budget: u32,
        token_budget: u32,
    ) -> Option<NextBatch> {
171
172
173
174
175
176
177
178
179
180
181
        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;
            }
        }

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

186
        let mut batch_requests = Vec::with_capacity(self.entries.len());
187
        let mut batch_entries =
188
            IntMap::with_capacity_and_hasher(self.entries.len(), BuildNoHashHasher::default());
189

190
191
192
193
194
        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
195
196
197
198
199
200
201
202
        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)
            if entry.response_tx.is_disconnected() {
                metrics::increment_counter!("tgi_request_failure", "err" => "dropped");
                continue;
            }

203
204
205
206
207
208
            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 {
209
210
211
212
                // pad to block size
                prefill_tokens += ((entry.request.input_length + self.block_size - 1)
                    / self.block_size)
                    * self.block_size;
213
214
            }

215
216
217
            if self.requires_padding {
                decode_tokens += entry.request.stopping_parameters.max_new_tokens;
            } else {
218
219
220
221
222
223
224
225
                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,
                    ),
                };

226
227
                // pad to block size
                decode_tokens +=
228
                    ((max_new_tokens + self.block_size - 1) / self.block_size) * self.block_size;
229
            }
230

231
232
233
            if prefill_tokens > prefill_token_budget
                || (prefill_tokens + decode_tokens) > token_budget
            {
234
235
236
237
238
239
                // Entry is over budget
                // Add it back to the front
                self.entries.push_front((id, entry));
                break;
            }

240
241
242
243
244
245
246
247
248
249
            // 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,
250
                prefill_logprobs: entry.request.decoder_input_details,
251
252
253
254
                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
255
                top_n_tokens: entry.request.top_n_tokens,
256
            });
257
258
259
260
261
262
            // Set batch_time
            entry.batch_time = Some(Instant::now());
            // Insert in batch_entries IntMap
            batch_entries.insert(id, entry);
        }

263
        // Empty batch
264
265
266
267
        if batch_requests.is_empty() {
            return None;
        }

268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
        // 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
284
285
        let size = batch_requests.len() as u32;
        next_batch_span.record("batch_size", size);
286
287
288
289

        let batch = Batch {
            id: self.next_batch_id,
            requests: batch_requests,
290
            size,
291
            max_tokens: (prefill_tokens + decode_tokens),
292
293
294
295
        };
        // Increment batch id
        self.next_batch_id += 1;

296
        metrics::histogram!("tgi_batch_next_size", batch.size as f64);
297

298
        Some((batch_entries, batch, next_batch_span))
299
300
301
    }
}

302
type NextBatch = (IntMap<u64, Entry>, Batch, Span);
303
304
305

#[derive(Debug)]
enum QueueCommand {
306
    Append(Box<Entry>, Span),
307
308
    NextBatch {
        min_size: Option<usize>,
309
        prefill_token_budget: u32,
310
        token_budget: u32,
311
        response_sender: oneshot::Sender<Option<NextBatch>>,
312
        span: Span,
313
314
315
316
317
318
319
    },
}

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

322
323
324
325
326
    fn default_entry() -> (
        Entry,
        flume::Receiver<Result<InferStreamResponse, InferError>>,
    ) {
        let (response_tx, receiver_tx) = flume::unbounded();
327

328
        let entry = Entry {
329
330
            request: ValidGenerateRequest {
                inputs: "".to_string(),
331
                input_length: 0,
332
                truncate: 0,
333
                decoder_input_details: false,
334
335
336
337
                parameters: NextTokenChooserParameters {
                    temperature: 0.0,
                    top_k: 0,
                    top_p: 0.0,
338
                    typical_p: 0.0,
339
340
341
                    do_sample: false,
                    seed: 0,
                    repetition_penalty: 0.0,
342
                    watermark: false,
343
344
                },
                stopping_parameters: StoppingCriteriaParameters {
345
                    ignore_eos_token: false,
346
                    max_new_tokens: 1,
347
348
                    stop_sequences: vec![],
                },
Nicolas Patry's avatar
Nicolas Patry committed
349
                top_n_tokens: 0,
350
351
            },
            response_tx,
352
353
354
            span: info_span!("entry"),
            temp_span: None,
            queue_time: Instant::now(),
355
            batch_time: None,
356
357
        };
        (entry, receiver_tx)
358
359
360
361
    }

    #[test]
    fn test_append() {
362
        let mut state = State::new(false, 1, None);
363
        let (entry, _guard) = default_entry();
364
365
366
367
368
369
370
371

        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);
372
        let (id, _) = state.entries.remove(0).unwrap();
373
374
375
376
377
        assert_eq!(id, 0);
    }

    #[test]
    fn test_next_batch_empty() {
378
        let mut state = State::new(false, 1, None);
379

380
381
        assert!(state.next_batch(None, 1, 1).is_none());
        assert!(state.next_batch(Some(1), 1, 1).is_none());
382
383
384
385
    }

    #[test]
    fn test_next_batch_min_size() {
386
        let mut state = State::new(false, 1, None);
387
388
389
390
        let (entry1, _guard1) = default_entry();
        let (entry2, _guard2) = default_entry();
        state.append(entry1);
        state.append(entry2);
391

392
        let (entries, batch, _) = state.next_batch(None, 2, 2).unwrap();
393
394
395
396
397
398
399
400
401
402
403
404
        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);

405
406
        let (entry3, _guard3) = default_entry();
        state.append(entry3);
407

408
        assert!(state.next_batch(Some(2), 2, 2).is_none());
409
410
411

        assert_eq!(state.next_id, 3);
        assert_eq!(state.entries.len(), 1);
412
        let (id, _) = state.entries.remove(0).unwrap();
413
414
415
416
        assert_eq!(id, 2);
    }

    #[test]
417
    fn test_next_batch_token_budget() {
418
        let mut state = State::new(false, 1, None);
419
420
421
422
        let (entry1, _guard1) = default_entry();
        let (entry2, _guard2) = default_entry();
        state.append(entry1);
        state.append(entry2);
423

424
        let (entries, batch, _) = state.next_batch(None, 1, 1).unwrap();
425
426
427
428
429
430
431
432
433
        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);

434
435
        let (entry3, _guard3) = default_entry();
        state.append(entry3);
436

437
        let (entries, batch, _) = state.next_batch(None, 3, 3).unwrap();
438
439
440
441
442
443
444
445
446
447
448
449
450
        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() {
451
        let queue = Queue::new(false, 1, None);
452
453
        let (entry, _guard) = default_entry();
        queue.append(entry);
454
455
456
457
    }

    #[tokio::test]
    async fn test_queue_next_batch_empty() {
458
        let queue = Queue::new(false, 1, None);
459

460
461
        assert!(queue.next_batch(None, 1, 1).await.is_none());
        assert!(queue.next_batch(Some(1), 1, 1).await.is_none());
462
463
464
465
    }

    #[tokio::test]
    async fn test_queue_next_batch_min_size() {
466
        let queue = Queue::new(false, 1, None);
467
468
469
470
        let (entry1, _guard1) = default_entry();
        let (entry2, _guard2) = default_entry();
        queue.append(entry1);
        queue.append(entry2);
471

472
        let (entries, batch, _) = queue.next_batch(None, 2, 2).await.unwrap();
473
474
475
476
477
478
479
480
        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);

481
482
        let (entry3, _guard3) = default_entry();
        queue.append(entry3);
483

484
        // Not enough requests pending
485
        assert!(queue.next_batch(Some(2), 2, 2).await.is_none());
486
        // Not enough token budget
487
        assert!(queue.next_batch(Some(1), 0, 0).await.is_none());
488
        // Ok
489
        let (entries2, batch2, _) = queue.next_batch(Some(1), 2, 2).await.unwrap();
490
491
492
493
494
        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);
495
496
497
    }

    #[tokio::test]
498
    async fn test_queue_next_batch_token_budget() {
499
        let queue = Queue::new(false, 1, None);
500
501
502
503
        let (entry1, _guard1) = default_entry();
        let (entry2, _guard2) = default_entry();
        queue.append(entry1);
        queue.append(entry2);
504

505
        let (entries, batch, _) = queue.next_batch(None, 1, 1).await.unwrap();
506
507
508
509
510
        assert_eq!(entries.len(), 1);
        assert!(entries.contains_key(&0));
        assert_eq!(batch.id, 0);
        assert_eq!(batch.size, 1);

511
512
        let (entry3, _guard3) = default_entry();
        queue.append(entry3);
513

514
        let (entries, batch, _) = queue.next_batch(None, 3, 3).await.unwrap();
515
516
517
518
519
520
        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);
    }
521
522
523

    #[tokio::test]
    async fn test_queue_next_batch_dropped_receiver() {
524
        let queue = Queue::new(false, 1, None);
525
526
527
        let (entry, _) = default_entry();
        queue.append(entry);

528
        assert!(queue.next_batch(None, 1, 1).await.is_none());
529
    }
530
}