infer.rs 25.1 KB
Newer Older
1
2
/// Batching and inference logic
use crate::validation::{Validation, ValidationError};
3
use crate::{Entry, Queue, Token};
4
use crate::{GenerateRequest, PrefillToken};
5
use futures::future::try_join_all;
6
use nohash_hasher::IntMap;
7
8
9
10
use std::sync::{
    atomic::{AtomicBool, Ordering},
    Arc,
};
11
use text_generation_client::{
Nicolas Patry's avatar
Nicolas Patry committed
12
    Batch, CachedBatch, ClientError, GeneratedText, Generation, ShardedClient, Tokens,
13
14
};
use thiserror::Error;
OlivierDehaene's avatar
OlivierDehaene committed
15
16
use tokio::sync::mpsc::error::SendError;
use tokio::sync::{mpsc, Notify, OwnedSemaphorePermit, Semaphore, TryAcquireError};
17
use tokio::time::Instant;
OlivierDehaene's avatar
OlivierDehaene committed
18
19
use tokio_stream::wrappers::UnboundedReceiverStream;
use tokio_stream::StreamExt;
20
use tracing::{info_span, instrument, Instrument, Span};
21
22
23
24
25
26

/// Inference struct
#[derive(Clone)]
pub struct Infer {
    /// Validation
    validation: Validation,
27
28
    /// Request queue
    queue: Queue,
29
30
31
32
33
34
35
36
37
38
39
40
41
    /// Shared state
    shared: Arc<Shared>,
    /// Inference limit
    limit_concurrent_requests: Arc<Semaphore>,
}

/// Infer shared state
struct Shared {
    /// Batching background Tokio task notifier
    batching_task: Notify,
}

impl Infer {
42
    #[allow(clippy::too_many_arguments)]
43
44
45
    pub(crate) fn new(
        client: ShardedClient,
        validation: Validation,
46
        waiting_served_ratio: f32,
47
        max_batch_prefill_tokens: u32,
48
        max_batch_total_tokens: u32,
49
50
        max_waiting_tokens: usize,
        max_concurrent_requests: usize,
51
        requires_padding: bool,
52
        window_size: Option<u32>,
Nicolas Patry's avatar
Nicolas Patry committed
53
        speculate: u32,
54
        generation_health: Arc<AtomicBool>,
55
56
    ) -> Self {
        // Infer shared state
Nicolas Patry's avatar
Nicolas Patry committed
57
        let queue = Queue::new(requires_padding, 16, window_size, speculate);
58
59
60
61
62
63
64
        let shared = Arc::new(Shared {
            batching_task: Notify::new(),
        });

        // Spawn batching background task that contains all the inference logic
        tokio::spawn(batching_task(
            client,
65
            waiting_served_ratio,
66
            max_batch_prefill_tokens,
67
            max_batch_total_tokens,
68
            max_waiting_tokens,
69
            queue.clone(),
70
            shared.clone(),
71
            generation_health,
72
73
74
75
76
77
78
        ));

        // Inference limit with a semaphore
        let semaphore = Arc::new(Semaphore::new(max_concurrent_requests));

        Self {
            validation,
79
            queue,
80
81
82
83
84
            shared,
            limit_concurrent_requests: semaphore,
        }
    }

85
    /// Add a new request to the queue and return a stream of InferStreamResponse
86
    #[instrument(skip_all)]
87
88
89
    pub(crate) async fn generate_stream(
        &self,
        request: GenerateRequest,
90
91
92
    ) -> Result<
        (
            OwnedSemaphorePermit,
93
            u32,
OlivierDehaene's avatar
OlivierDehaene committed
94
            UnboundedReceiverStream<Result<InferStreamResponse, InferError>>,
95
96
97
        ),
        InferError,
    > {
98
        // Limit concurrent requests by acquiring a permit from the semaphore
99
100
101
102
103
        let permit = self
            .clone()
            .limit_concurrent_requests
            .try_acquire_owned()
            .map_err(|err| {
104
                metrics::increment_counter!("tgi_request_failure", "err" => "overloaded");
105
106
107
                tracing::error!("{err}");
                err
            })?;
108
109

        // Validate request
110
111
112
113
114
        let valid_request = self.validation.validate(request).await.map_err(|err| {
            metrics::increment_counter!("tgi_request_failure", "err" => "validation");
            tracing::error!("{err}");
            err
        })?;
115
116

        // MPSC channel to communicate with the background batching task
OlivierDehaene's avatar
OlivierDehaene committed
117
        let (response_tx, response_rx) = mpsc::unbounded_channel();
118
        let input_length = valid_request.input_length;
119

120
121
        // Append the request to the queue
        self.queue.append(Entry {
122
123
            request: valid_request,
            response_tx,
124
125
126
            span: Span::current(),
            temp_span: None,
            queue_time: Instant::now(),
127
128
129
            batch_time: None,
        });

130
        // Notify the background task that we have a new entry in the queue that needs
131
132
133
134
        // to be batched
        self.shared.batching_task.notify_one();

        // Return stream
135
136
137
138
139
        Ok((
            permit,
            input_length,
            UnboundedReceiverStream::new(response_rx),
        ))
140
141
    }

142
    /// Add a new request to the queue and return a InferResponse
143
    #[instrument(skip_all)]
144
145
146
147
    pub(crate) async fn generate(
        &self,
        request: GenerateRequest,
    ) -> Result<InferResponse, InferError> {
Nicolas Patry's avatar
Nicolas Patry committed
148
149
        let use_top_tokens = request.parameters.top_n_tokens.is_some_and(|x| x > 0);

150
        // Create stream and keep semaphore permit as long as generate lives
151
        let (_permit, _input_length, mut stream) = self.generate_stream(request).await?;
152
153
154
155

        // Return values
        let mut result_prefill = Vec::new();
        let mut result_tokens = Vec::new();
Nicolas Patry's avatar
Nicolas Patry committed
156
        let mut result_top_tokens = Vec::new();
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
        let mut result_generated_text = None;
        let mut result_start = None;
        let mut result_queued = None;

        // Iterate on stream
        while let Some(response) = stream.next().await {
            match response? {
                // Add prefill tokens
                InferStreamResponse::Prefill(tokens) => {
                    // Create Token objects
                    // We do that here instead of in the Python code as Rust for loops are faster
                    result_prefill = tokens
                        .ids
                        .into_iter()
                        .zip(tokens.logprobs.into_iter())
                        .zip(tokens.texts.into_iter())
173
                        .map(|((id, logprob), text)| PrefillToken { id, text, logprob })
174
175
176
                        .collect();
                }
                // Push last token
Nicolas Patry's avatar
Nicolas Patry committed
177
178
179
180
                InferStreamResponse::Intermediate { token, top_tokens } => {
                    result_tokens.push(token);
                    result_top_tokens.push(top_tokens);
                }
181
182
183
184
185
186
187
                // Final message
                // Set return values
                InferStreamResponse::End {
                    token,
                    generated_text,
                    start,
                    queued,
Nicolas Patry's avatar
Nicolas Patry committed
188
                    top_tokens,
189
190
                } => {
                    result_tokens.push(token);
Nicolas Patry's avatar
Nicolas Patry committed
191
                    result_top_tokens.push(top_tokens);
192
193
194
195
196
197
198
199
200
201
202
203
204
                    result_generated_text = Some(generated_text);
                    result_start = Some(start);
                    result_queued = Some(queued)
                }
            }
        }

        // Check that we received a `InferStreamResponse::End` message
        if let (Some(generated_text), Some(queued), Some(start)) =
            (result_generated_text, result_queued, result_start)
        {
            Ok(InferResponse {
                prefill: result_prefill,
205
                _input_length,
206
207
208
209
                tokens: result_tokens,
                generated_text,
                queued,
                start,
Nicolas Patry's avatar
Nicolas Patry committed
210
211
212
213
214
                top_tokens: if use_top_tokens {
                    result_top_tokens
                } else {
                    Vec::new()
                },
215
216
            })
        } else {
217
            let err = InferError::IncompleteGeneration;
218
            metrics::increment_counter!("tgi_request_failure", "err" => "incomplete");
219
220
            tracing::error!("{err}");
            Err(err)
221
222
        }
    }
223
224
    /// Add best_of new requests to the queue and return a InferResponse of the sequence with
    /// the highest log probability per token
225
    #[instrument(skip(self, request))]
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
    pub(crate) async fn generate_best_of(
        &self,
        request: GenerateRequest,
        best_of: usize,
    ) -> Result<(InferResponse, Vec<InferResponse>), InferError> {
        // validate  best_of parameter separately
        let best_of = self.validation.validate_best_of(best_of)?;

        // create multiple generate requests
        let mut infer_responses: Vec<InferResponse> =
            try_join_all((0..best_of).map(|_| self.generate(request.clone()))).await?;

        // get the sequence with the highest log probability per token
        let mut max_index = 0;
        let mut max_logprob: f32 = f32::MIN;

        for (i, response) in infer_responses.iter().enumerate() {
            // mean logprobs of the generated tokens
            let sequence_logprob = response
                .tokens
                .iter()
                .map(|token| token.logprob)
                .sum::<f32>()
                / response.tokens.len() as f32;

            // set best sequence
            if sequence_logprob > max_logprob {
                max_index = i;
                max_logprob = sequence_logprob;
            }
        }
        let best_response = infer_responses.remove(max_index);
        Ok((best_response, infer_responses))
    }
260
261
262
263
264
265
}

/// Batching logic
/// Will be launched in a background Tokio task
///
/// Batches requests and sends them to the inference server
266
#[allow(clippy::too_many_arguments)]
267
268
async fn batching_task(
    mut client: ShardedClient,
269
    waiting_served_ratio: f32,
270
    max_batch_prefill_tokens: u32,
271
    max_batch_total_tokens: u32,
272
    max_waiting_tokens: usize,
273
    queue: Queue,
274
    shared: Arc<Shared>,
275
    generation_health: Arc<AtomicBool>,
276
277
278
279
280
281
) {
    // Infinite loop
    loop {
        // Wait for a notification from the Infer struct
        shared.batching_task.notified().await;

282
        // Get the next batch from the queue
283
        // This batch might be smaller than the maximum batch size if there are not enough requests
284
        // waiting in the queue
285
286
287
        while let Some((mut entries, batch, span)) = queue
            .next_batch(None, max_batch_prefill_tokens, max_batch_total_tokens)
            .await
288
        {
289
            let mut cached_batch = prefill(&mut client, batch, &mut entries, &generation_health)
290
291
                .instrument(span)
                .await;
292
293
294
295
296
297
298
            let mut waiting_tokens = 1;

            // We loop until we do not receive any cached batch from the inference server (== until
            // all requests have met their stopping criteria)
            while let Some(batch) = cached_batch {
                // Get current batch info
                let batch_size = batch.size;
299
                let batch_max_tokens = batch.max_tokens;
300
                let mut batches = vec![batch];
301
                metrics::gauge!("tgi_batch_current_size", batch_size as f64);
302
303
304
305
306
307
308
309
310
311
312
                metrics::gauge!("tgi_batch_current_max_tokens", batch_max_tokens as f64);

                let min_size = if waiting_tokens >= max_waiting_tokens {
                    // If we didn't onboard any new requests since >= max_waiting_tokens, we try
                    // to add a new batch even though its size might be small
                    None
                } else {
                    // Minimum batch size
                    Some((batch_size as f32 * waiting_served_ratio).floor() as usize)
                };

313
                let token_budget = max_batch_total_tokens.saturating_sub(batch_max_tokens);
314
315

                // Try to get a new batch
316
317
318
                if let Some((mut new_entries, new_batch, span)) = queue
                    .next_batch(min_size, max_batch_prefill_tokens, token_budget)
                    .await
319
320
321
322
323
324
325
                {
                    // Tracking metrics
                    if min_size.is_some() {
                        metrics::increment_counter!("tgi_batch_concat", "reason" => "backpressure");
                    } else {
                        metrics::increment_counter!("tgi_batch_concat", "reason" => "wait_exceeded");
                    }
326

327
328
329
330
331
332
333
334
335
336
337
338
                    entries.iter_mut().for_each(|(_, entry)| {
                        // Create a new span to add the info that this entry is waiting
                        // because a new batch is being computed
                        let entry_waiting_span = info_span!(parent: &entry.span, "waiting");
                        // Add relationships
                        span.follows_from(&entry_waiting_span);
                        entry_waiting_span.follows_from(&span);
                        // Update entry
                        entry.temp_span = Some(entry_waiting_span);
                    });

                    // Generate one token for this new batch to have the attention past in cache
339
340
341
342
                    let new_cached_batch =
                        prefill(&mut client, new_batch, &mut new_entries, &generation_health)
                            .instrument(span)
                            .await;
343
344
345
346
347
348
                    // Reset waiting counter
                    waiting_tokens = 1;
                    // Extend current batch with the new batch
                    if let Some(new_cached_batch) = new_cached_batch {
                        entries.extend(new_entries);
                        batches.push(new_cached_batch);
349
350
                    }
                }
351

352
353
354
355
356
357
                // Create span for this batch to add context to inference calls
                let next_batch_size = entries.len();
                let next_batch_span =
                    info_span!(parent: None, "batch", batch_size = next_batch_size);
                entries.iter_mut().for_each(|(_, entry)| {
                    // Create a new span to link the batch back to this entry
358
                    let entry_batch_span = info_span!(parent: &entry.span, "infer");
359
360
                    // Add relationships
                    next_batch_span.follows_from(&entry_batch_span);
361
362
363
364
                    entry_batch_span.follows_from(&next_batch_span);
                    // Update entry
                    entry.temp_span = Some(entry_batch_span);
                });
365

366
                cached_batch = decode(&mut client, batches, &mut entries, &generation_health)
367
368
                    .instrument(next_batch_span)
                    .await;
369
370
                waiting_tokens += 1;
            }
371
            metrics::gauge!("tgi_batch_current_size", 0.0);
372
            metrics::gauge!("tgi_batch_current_max_tokens", 0.0);
373
374
375
376
        }
    }
}

377
#[instrument(skip_all)]
378
379
380
async fn prefill(
    client: &mut ShardedClient,
    batch: Batch,
381
    entries: &mut IntMap<u64, Entry>,
382
    generation_health: &Arc<AtomicBool>,
383
) -> Option<CachedBatch> {
384
    let start_time = Instant::now();
385
    let batch_id = batch.id;
386
    metrics::increment_counter!("tgi_batch_inference_count", "method" => "prefill");
387
388

    match client.prefill(batch).await {
389
        Ok((generations, next_batch, timings)) => {
390
391
            // Update health
            generation_health.store(true, Ordering::SeqCst);
392
393

            let start_filtering_time = Instant::now();
394
            // Send generated tokens and filter stopped entries
395
396
397
            filter_send_generations(generations, entries);

            // Filter next batch and remove requests that were stopped
398
            let next_batch = filter_batch(client, next_batch, entries).await;
399

400
401
402
            metrics::histogram!("tgi_batch_forward_duration", timings.forward.as_secs_f64(), "method" => "prefill");
            metrics::histogram!("tgi_batch_decode_duration", timings.decode.as_secs_f64(), "method" => "prefill");
            metrics::histogram!("tgi_batch_filter_duration", start_filtering_time.elapsed().as_secs_f64(), "method" => "prefill");
403
            metrics::histogram!("tgi_batch_inference_duration", start_time.elapsed().as_secs_f64(), "method" => "prefill");
404
405
406
407
408
            metrics::increment_counter!("tgi_batch_inference_success", "method" => "prefill");
            next_batch
        }
        // If we have an error, we discard the whole batch
        Err(err) => {
409
410
            // Update health
            generation_health.store(false, Ordering::SeqCst);
411
            let _ = client.clear_cache(Some(batch_id)).await;
412
413
414
415
416
417
418
419
420
421
            send_errors(err, entries);
            metrics::increment_counter!("tgi_batch_inference_failure", "method" => "prefill");
            None
        }
    }
}

#[instrument(skip_all)]
async fn decode(
    client: &mut ShardedClient,
422
    batches: Vec<CachedBatch>,
423
    entries: &mut IntMap<u64, Entry>,
424
    generation_health: &Arc<AtomicBool>,
425
) -> Option<CachedBatch> {
426
    let start_time = Instant::now();
427
    let batch_ids: Vec<u64> = batches.iter().map(|b| b.id).collect();
428
    metrics::increment_counter!("tgi_batch_inference_count", "method" => "decode");
429
430

    match client.decode(batches).await {
431
        Ok((generations, next_batch, timings)) => {
432
433
            // Update health
            generation_health.store(true, Ordering::SeqCst);
434
435

            let start_filtering_time = Instant::now();
436
            // Send generated tokens and filter stopped entries
437
438
439
            filter_send_generations(generations, entries);

            // Filter next batch and remove requests that were stopped
440
            let next_batch = filter_batch(client, next_batch, entries).await;
441

442
443
444
445
446
447
            if let Some(concat_duration) = timings.concat {
                metrics::histogram!("tgi_batch_concat_duration", concat_duration.as_secs_f64(), "method" => "decode");
            }
            metrics::histogram!("tgi_batch_forward_duration", timings.forward.as_secs_f64(), "method" => "decode");
            metrics::histogram!("tgi_batch_decode_duration", timings.decode.as_secs_f64(), "method" => "decode");
            metrics::histogram!("tgi_batch_filter_duration", start_filtering_time.elapsed().as_secs_f64(), "method" => "decode");
448
            metrics::histogram!("tgi_batch_inference_duration", start_time.elapsed().as_secs_f64(), "method" => "decode");
449
            metrics::increment_counter!("tgi_batch_inference_success", "method" => "decode");
450
451
452
453
            next_batch
        }
        // If we have an error, we discard the whole batch
        Err(err) => {
454
            generation_health.store(false, Ordering::SeqCst);
455
456
457
            for id in batch_ids {
                let _ = client.clear_cache(Some(id)).await;
            }
458
            send_errors(err, entries);
459
            metrics::increment_counter!("tgi_batch_inference_failure", "method" => "decode");
460
461
462
463
464
            None
        }
    }
}

465
466
/// Filter a `batch` and remove all requests not present in `entries`
#[instrument(skip_all)]
467
468
async fn filter_batch(
    client: &mut ShardedClient,
469
    next_batch: Option<CachedBatch>,
470
    entries: &IntMap<u64, Entry>,
471
) -> Option<CachedBatch> {
472
473
474
475
476
477
478
479
480
481
    let mut batch = next_batch?;

    // No need to filter
    if batch.size as usize == entries.len() {
        return Some(batch);
    }

    let id = batch.id;

    // Retain only requests that are still in entries
482
    batch.request_ids.retain(|id| entries.contains_key(id));
483

484
    if batch.request_ids.is_empty() {
485
486
487
488
489
490
491
492
493
        // All requests have been filtered out
        // Next batch is now empty
        // Clear it from the Python shards cache
        // We unwrap here as we need to panic since we cannot recover if this method fails
        client.clear_cache(Some(id)).await.unwrap();
        None
    } else {
        // Filter Python shard cache
        // We unwrap here as we need to panic since we cannot recover if this method fails
494
        client.filter_batch(id, batch.request_ids).await.unwrap()
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
    }
}

/// Send one or multiple `InferStreamResponse` to Infer for all `entries`
/// and filter entries
#[instrument(skip_all)]
fn filter_send_generations(generations: Vec<Generation>, entries: &mut IntMap<u64, Entry>) {
    generations.into_iter().for_each(|generation| {
        let id = generation.request_id;
        // Get entry
        // We can `expect` here as the request id should always be in the entries
        let entry = entries
            .get(&id)
            .expect("ID not found in entries. This is a bug.");

        // Create and enter a span to link this function back to the entry
        let _span = info_span!(parent: entry.temp_span.as_ref().expect("batch_span is None. This is a bug."), "send_generation", generation = ?generation).entered();
        // Send generation responses back to the infer task
        // If the receive an error from the Flume channel, it means that the client dropped the
        // request and we need to stop generating hence why we unwrap_or(true)
        let stopped = send_responses(generation, entry).map_err(|err| {
OlivierDehaene's avatar
OlivierDehaene committed
516
            tracing::error!("Entry response channel error.");
517
518
519
520
521
522
523
524
525
526
527
528
529
            metrics::increment_counter!("tgi_request_failure", "err" => "dropped");
            err
        }).unwrap_or(true);
        if stopped {
            entries.remove(&id).expect("ID not found in entries. This is a bug.");
        }
    });
}

/// Send responses through the `entry` response channel
fn send_responses(
    generation: Generation,
    entry: &Entry,
OlivierDehaene's avatar
OlivierDehaene committed
530
) -> Result<bool, Box<SendError<Result<InferStreamResponse, InferError>>>> {
531
    // Return directly if the channel is disconnected
OlivierDehaene's avatar
OlivierDehaene committed
532
533
    if entry.response_tx.is_closed() {
        metrics::increment_counter!("tgi_request_failure", "err" => "dropped");
534
535
536
        return Ok(true);
    }

537
538
539
540
    let mut stopped = false;

    if let Some(prefill_tokens) = generation.prefill_tokens {
        // Send message
OlivierDehaene's avatar
OlivierDehaene committed
541
542
543
        entry
            .response_tx
            .send(Ok(InferStreamResponse::Prefill(prefill_tokens)))?;
544
545
546
    }

    // Create last Token
Nicolas Patry's avatar
Nicolas Patry committed
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
    let tokens_ = generation.tokens.expect("Non empty tokens in generation");
    let n = tokens_.ids.len();
    metrics::histogram!("tgi_request_skipped_tokens", (n - 1) as f64);
    let mut iterator = tokens_
        .ids
        .into_iter()
        .zip(tokens_.logprobs.into_iter())
        .zip(tokens_.texts.into_iter())
        .zip(tokens_.is_special.into_iter())
        .enumerate()
        .peekable();
    while let Some((i, (((id, logprob), text), special))) = iterator.next() {
        let token = Token {
            id,
            text,
            logprob,
            special,
        };
        let top_tokens = if let Some(top_tokens_) = generation.top_tokens.get(i) {
Nicolas Patry's avatar
Nicolas Patry committed
566
567
            top_tokens_
                .ids
Nicolas Patry's avatar
Nicolas Patry committed
568
569
570
571
572
                .iter()
                .zip(top_tokens_.logprobs.iter())
                .zip(top_tokens_.texts.iter())
                .zip(top_tokens_.is_special.iter())
                .map(|(((&id, &logprob), text), &special)| Token {
Nicolas Patry's avatar
Nicolas Patry committed
573
                    id,
Nicolas Patry's avatar
Nicolas Patry committed
574
                    text: text.to_string(),
Nicolas Patry's avatar
Nicolas Patry committed
575
576
                    logprob,
                    special,
Nicolas Patry's avatar
Nicolas Patry committed
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
                })
                .collect()
        } else {
            vec![]
        };
        match (&generation.generated_text, iterator.peek()) {
            (Some(generated_text), None) => {
                // Generation has ended
                stopped = true;
                // Send message
                entry.response_tx.send(Ok(InferStreamResponse::End {
                    token,
                    top_tokens,
                    generated_text: generated_text.clone(),
                    queued: entry.queue_time,
                    start: entry.batch_time.unwrap(),
                }))?;
            }
            _ => {
                // Send message
                entry
                    .response_tx
                    .send(Ok(InferStreamResponse::Intermediate { token, top_tokens }))?;
            }
        }
Nicolas Patry's avatar
Nicolas Patry committed
602
603
    }

604
605
606
    Ok(stopped)
}

607
/// Send errors to Infer for all `entries`
608
609
#[instrument(skip_all)]
fn send_errors(error: ClientError, entries: &mut IntMap<u64, Entry>) {
610
    entries.drain().for_each(|(_, entry)| {
611
612
613
        // Create and enter a span to link this function back to the entry
        let _send_error_span = info_span!(parent: entry.temp_span.as_ref().expect("batch_span is None. This is a bug."), "send_error").entered();
        let err = InferError::GenerationError(error.to_string());
614
        metrics::increment_counter!("tgi_request_failure", "err" => "generation");
615
616
        tracing::error!("{err}");

617
618
619
        // unwrap_or is valid here as we don't care if the receiver is gone.
        entry
            .response_tx
OlivierDehaene's avatar
OlivierDehaene committed
620
            .send(Err(err))
621
622
623
624
625
626
627
            .unwrap_or(());
    });
}

#[derive(Debug)]
pub(crate) enum InferStreamResponse {
    // Optional first message
Nicolas Patry's avatar
Nicolas Patry committed
628
    Prefill(Tokens),
629
    // Intermediate messages
Nicolas Patry's avatar
Nicolas Patry committed
630
631
632
633
    Intermediate {
        token: Token,
        top_tokens: Vec<Token>,
    },
634
635
636
    // Last message
    End {
        token: Token,
Nicolas Patry's avatar
Nicolas Patry committed
637
        top_tokens: Vec<Token>,
638
639
640
641
642
643
644
645
        generated_text: GeneratedText,
        start: Instant,
        queued: Instant,
    },
}

#[derive(Debug)]
pub(crate) struct InferResponse {
646
647
648
649
    /// input_length is the input as perceived by the rust tokenizer in the
    /// validation pathway. It is redundant with prefill.len() but prefill
    /// has data only if the user asked for it. This will always be filled.
    pub(crate) _input_length: u32,
650
    pub(crate) prefill: Vec<PrefillToken>,
651
652
653
654
    pub(crate) tokens: Vec<Token>,
    pub(crate) generated_text: GeneratedText,
    pub(crate) queued: Instant,
    pub(crate) start: Instant,
Nicolas Patry's avatar
Nicolas Patry committed
655
    pub(crate) top_tokens: Vec<Vec<Token>>,
656
657
658
659
660
661
662
663
664
665
666
667
668
}

#[derive(Debug, Error)]
pub enum InferError {
    #[error("Request failed during generation: {0}")]
    GenerationError(String),
    #[error("Model is overloaded")]
    Overloaded(#[from] TryAcquireError),
    #[error("Input validation error: {0}")]
    ValidationError(#[from] ValidationError),
    #[error("Incomplete generation")]
    IncompleteGeneration,
}
669
670
671
672
673
674
675
676
677
678
679

impl InferError {
    pub(crate) fn error_type(&self) -> &str {
        match self {
            InferError::GenerationError(_) => "generation",
            InferError::Overloaded(_) => "overloaded",
            InferError::ValidationError(_) => "validation",
            InferError::IncompleteGeneration => "incomplete_generation",
        }
    }
}