queue.rs 13.4 KB
Newer Older
1
2
3
4
5
use crate::infer::InferError;
use crate::infer::InferStreamResponse;
use crate::validation::ValidGenerateRequest;
use nohash_hasher::{BuildNoHashHasher, IntMap};
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
37
38
}

impl Queue {
    pub(crate) fn new() -> Self {
        // Create channel
39
        let (queue_sender, queue_receiver) = flume::unbounded();
40
41
42
43
44
45
46
47

        // Launch background queue task
        tokio::spawn(queue_task(queue_receiver));

        Self { queue_sender }
    }

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

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

// Background task responsible of the queue state
83
async fn queue_task(receiver: flume::Receiver<QueueCommand>) {
84
85
    let mut state = State::new();

86
    while let Ok(cmd) = receiver.recv_async().await {
87
        match cmd {
88
            QueueCommand::Append(entry, span) => span.in_scope(|| state.append(entry)),
89
90
91
92
            QueueCommand::NextBatch {
                min_size,
                max_size,
                response_sender,
93
94
                span,
            } => span.in_scope(|| {
95
96
                let next_batch = state.next_batch(min_size, max_size);
                response_sender.send(next_batch).unwrap_or(());
97
            }),
98
99
100
101
102
103
104
105
        }
    }
}

/// Queue State
#[derive(Debug)]
struct State {
    /// Queue entries organized in a Vec
106
    entries: VecDeque<(u64, Entry)>,
107
108
109
110
111
112
113
114
115
116
117

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

    /// Id of the next batch
    next_batch_id: u64,
}

impl State {
    fn new() -> Self {
        Self {
118
            entries: VecDeque::with_capacity(128),
119
120
121
122
123
124
            next_id: 0,
            next_batch_id: 0,
        }
    }

    /// Append an entry to the queue
125
126
127
128
129
130
    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
131
        self.entries.push_back((self.next_id, entry));
132
        self.next_id += 1;
133
        metrics::increment_gauge!("tgi_queue_size", 1.0);
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
    }

    // Get the next batch
    fn next_batch(&mut self, min_size: Option<usize>, max_size: usize) -> Option<NextBatch> {
        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;
            }
        }

149
        let max_batch_size = min(self.entries.len(), max_size);
150

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

155
        let mut batch_requests = Vec::with_capacity(max_batch_size);
156
        let mut batch_entries =
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
            IntMap::with_capacity_and_hasher(max_batch_size, BuildNoHashHasher::default());

        // Iterate on buffer
        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;
            }

            // 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,
                inputs: entry.request.inputs.clone(),
                truncate: entry.request.truncate,
                parameters: Some(entry.request.parameters.clone()),
                stopping_parameters: Some(entry.request.stopping_parameters.clone()),
182
            });
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
            // Set batch_time
            entry.batch_time = Some(Instant::now());
            // Insert in batch_entries IntMap
            batch_entries.insert(id, entry);

            if batch_requests.len() == max_batch_size {
                // We have enough requests in the batch
                break;
            }
        }

        metrics::gauge!("tgi_queue_size", self.entries.len() as f64);

        // Maybe all entries were dropped because their channel were closed
        if batch_requests.is_empty() {
            return None;
        }

        // Final batch size once we dropped entries
        let size = batch_requests.len() as u32;
        next_batch_span.record("batch_size", size);
204
205
206
207

        let batch = Batch {
            id: self.next_batch_id,
            requests: batch_requests,
208
            size,
209
210
211
212
        };
        // Increment batch id
        self.next_batch_id += 1;

213
        metrics::histogram!("tgi_batch_next_size", batch.size as f64);
214
        Some((batch_entries, batch, next_batch_span))
215
216
217
    }
}

218
type NextBatch = (IntMap<u64, Entry>, Batch, Span);
219
220
221

#[derive(Debug)]
enum QueueCommand {
222
    Append(Entry, Span),
223
224
225
226
    NextBatch {
        min_size: Option<usize>,
        max_size: usize,
        response_sender: oneshot::Sender<Option<NextBatch>>,
227
        span: Span,
228
229
230
231
232
233
234
    },
}

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

237
238
239
240
241
    fn default_entry() -> (
        Entry,
        flume::Receiver<Result<InferStreamResponse, InferError>>,
    ) {
        let (response_tx, receiver_tx) = flume::unbounded();
242

243
        let entry = Entry {
244
245
            request: ValidGenerateRequest {
                inputs: "".to_string(),
246
                truncate: 0,
247
248
249
250
                parameters: NextTokenChooserParameters {
                    temperature: 0.0,
                    top_k: 0,
                    top_p: 0.0,
251
                    typical_p: 0.0,
252
253
254
                    do_sample: false,
                    seed: 0,
                    repetition_penalty: 0.0,
255
                    watermark: false,
256
257
                },
                stopping_parameters: StoppingCriteriaParameters {
258
                    ignore_eos_token: false,
259
260
261
262
263
                    max_new_tokens: 0,
                    stop_sequences: vec![],
                },
            },
            response_tx,
264
265
266
            span: info_span!("entry"),
            temp_span: None,
            queue_time: Instant::now(),
267
            batch_time: None,
268
269
        };
        (entry, receiver_tx)
270
271
272
273
274
    }

    #[test]
    fn test_append() {
        let mut state = State::new();
275
        let (entry, _guard) = default_entry();
276
277
278
279
280
281
282
283

        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);
284
        let (id, _) = state.entries.remove(0).unwrap();
285
286
287
288
289
290
291
292
293
294
295
296
297
298
        assert_eq!(id, 0);
    }

    #[test]
    fn test_next_batch_empty() {
        let mut state = State::new();

        assert!(state.next_batch(None, 1).is_none());
        assert!(state.next_batch(Some(1), 1).is_none());
    }

    #[test]
    fn test_next_batch_min_size() {
        let mut state = State::new();
299
300
301
302
        let (entry1, _guard1) = default_entry();
        let (entry2, _guard2) = default_entry();
        state.append(entry1);
        state.append(entry2);
303

304
        let (entries, batch, _) = state.next_batch(None, 2).unwrap();
305
306
307
308
309
310
311
312
313
314
315
316
        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);

317
318
        let (entry3, _guard3) = default_entry();
        state.append(entry3);
319
320
321
322
323

        assert!(state.next_batch(Some(2), 2).is_none());

        assert_eq!(state.next_id, 3);
        assert_eq!(state.entries.len(), 1);
324
        let (id, _) = state.entries.remove(0).unwrap();
325
326
327
328
329
330
        assert_eq!(id, 2);
    }

    #[test]
    fn test_next_batch_max_size() {
        let mut state = State::new();
331
332
333
334
        let (entry1, _guard1) = default_entry();
        let (entry2, _guard2) = default_entry();
        state.append(entry1);
        state.append(entry2);
335

336
        let (entries, batch, _) = state.next_batch(None, 1).unwrap();
337
338
339
340
341
342
343
344
345
        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);

346
347
        let (entry3, _guard3) = default_entry();
        state.append(entry3);
348

349
        let (entries, batch, _) = state.next_batch(None, 3).unwrap();
350
351
352
353
354
355
356
357
358
359
360
361
362
363
        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() {
        let queue = Queue::new();
364
365
        let (entry, _guard) = default_entry();
        queue.append(entry);
366
367
368
369
370
371
372
373
374
375
376
377
378
    }

    #[tokio::test]
    async fn test_queue_next_batch_empty() {
        let queue = Queue::new();

        assert!(queue.next_batch(None, 1).await.is_none());
        assert!(queue.next_batch(Some(1), 1).await.is_none());
    }

    #[tokio::test]
    async fn test_queue_next_batch_min_size() {
        let queue = Queue::new();
379
380
381
382
        let (entry1, _guard1) = default_entry();
        let (entry2, _guard2) = default_entry();
        queue.append(entry1);
        queue.append(entry2);
383

384
        let (entries, batch, _) = queue.next_batch(None, 2).await.unwrap();
385
386
387
388
389
390
391
392
        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);

393
394
        let (entry3, _guard3) = default_entry();
        queue.append(entry3);
395
396
397
398
399
400
401

        assert!(queue.next_batch(Some(2), 2).await.is_none());
    }

    #[tokio::test]
    async fn test_queue_next_batch_max_size() {
        let queue = Queue::new();
402
403
404
405
        let (entry1, _guard1) = default_entry();
        let (entry2, _guard2) = default_entry();
        queue.append(entry1);
        queue.append(entry2);
406

407
        let (entries, batch, _) = queue.next_batch(None, 1).await.unwrap();
408
409
410
411
412
        assert_eq!(entries.len(), 1);
        assert!(entries.contains_key(&0));
        assert_eq!(batch.id, 0);
        assert_eq!(batch.size, 1);

413
414
        let (entry3, _guard3) = default_entry();
        queue.append(entry3);
415

416
        let (entries, batch, _) = queue.next_batch(None, 3).await.unwrap();
417
418
419
420
421
422
        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);
    }
423
424
425
426
427
428
429
430
431

    #[tokio::test]
    async fn test_queue_next_batch_dropped_receiver() {
        let queue = Queue::new();
        let (entry, _) = default_entry();
        queue.append(entry);

        assert!(queue.next_batch(None, 1).await.is_none());
    }
432
}