lib.rs 16 KB
Newer Older
1
mod health;
2
/// Text Generation Inference Webserver
3
mod infer;
4
mod queue;
Olivier Dehaene's avatar
Olivier Dehaene committed
5
pub mod server;
Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
6
mod validation;
Olivier Dehaene's avatar
Olivier Dehaene committed
7

8
use infer::{Infer, InferError, InferStreamResponse};
9
use queue::{Entry, Queue};
Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
10
use serde::{Deserialize, Serialize};
11
12
use tokio::sync::OwnedSemaphorePermit;
use tokio_stream::wrappers::UnboundedReceiverStream;
13
use utoipa::ToSchema;
Olivier Dehaene's avatar
Olivier Dehaene committed
14
use validation::Validation;
Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
15

16
17
18
19
20
21
22
/// Type alias for generation responses
pub(crate) type GenerateStreamResponse = (
    OwnedSemaphorePermit,
    u32, // input_length
    UnboundedReceiverStream<Result<InferStreamResponse, InferError>>,
);

23
24
/// Hub type
#[derive(Clone, Debug, Deserialize)]
25
pub struct HubModelInfo {
26
27
28
29
30
31
    #[serde(rename(deserialize = "id"))]
    pub model_id: String,
    pub sha: Option<String>,
    pub pipeline_tag: Option<String>,
}

32
33
34
35
36
37
38
39
40
41
42
43
44
#[derive(Clone, Deserialize, Default)]
pub struct HubTokenizerConfig {
    #[serde(default)]
    pub chat_template: Option<String>,
}

impl HubTokenizerConfig {
    pub fn from_file(filename: &str) -> Self {
        let content = std::fs::read_to_string(filename).unwrap();
        serde_json::from_str(&content).unwrap_or_default()
    }
}

45
46
#[derive(Clone, Debug, Serialize, ToSchema)]
pub struct Info {
47
    /// Model info
48
49
50
51
    #[schema(example = "bigscience/blomm-560m")]
    pub model_id: String,
    #[schema(nullable = true, example = "e985a63cdc139290c5f700ff1929f0b5942cced2")]
    pub model_sha: Option<String>,
52
53
54
55
    #[schema(example = "torch.float16")]
    pub model_dtype: String,
    #[schema(example = "cuda")]
    pub model_device_type: String,
56
57
    #[schema(nullable = true, example = "text-generation")]
    pub model_pipeline_tag: Option<String>,
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
    /// Router Parameters
    #[schema(example = "128")]
    pub max_concurrent_requests: usize,
    #[schema(example = "2")]
    pub max_best_of: usize,
    #[schema(example = "4")]
    pub max_stop_sequences: usize,
    #[schema(example = "1024")]
    pub max_input_length: usize,
    #[schema(example = "2048")]
    pub max_total_tokens: usize,
    #[schema(example = "1.2")]
    pub waiting_served_ratio: f32,
    #[schema(example = "32000")]
    pub max_batch_total_tokens: u32,
    #[schema(example = "20")]
    pub max_waiting_tokens: usize,
    #[schema(example = "2")]
    pub validation_workers: usize,
    /// Router Info
78
79
80
81
    #[schema(example = "0.5.0")]
    pub version: &'static str,
    #[schema(nullable = true, example = "null")]
    pub sha: Option<&'static str>,
82
83
    #[schema(nullable = true, example = "null")]
    pub docker_label: Option<&'static str>,
84
85
}

86
#[derive(Clone, Debug, Deserialize, ToSchema)]
Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
87
pub(crate) struct GenerateParameters {
88
89
90
    #[serde(default)]
    #[schema(exclusive_minimum = 0, nullable = true, default = "null", example = 1)]
    pub best_of: Option<usize>,
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
    #[serde(default)]
    #[schema(
        exclusive_minimum = 0.0,
        nullable = true,
        default = "null",
        example = 0.5
    )]
    pub temperature: Option<f32>,
    #[serde(default)]
    #[schema(
        exclusive_minimum = 0.0,
        nullable = true,
        default = "null",
        example = 1.03
    )]
    pub repetition_penalty: Option<f32>,
    #[serde(default)]
    #[schema(exclusive_minimum = 0, nullable = true, default = "null", example = 10)]
    pub top_k: Option<i32>,
    #[serde(default)]
    #[schema(
        exclusive_minimum = 0.0,
        maximum = 1.0,
        nullable = true,
        default = "null",
        example = 0.95
    )]
    pub top_p: Option<f32>,
119
    #[serde(default)]
120
121
122
123
124
125
126
127
128
    #[schema(
        exclusive_minimum = 0.0,
        maximum = 1.0,
        nullable = true,
        default = "null",
        example = 0.95
    )]
    pub typical_p: Option<f32>,
    #[serde(default)]
129
    #[schema(default = "false", example = true)]
Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
130
131
    pub do_sample: bool,
    #[serde(default = "default_max_new_tokens")]
132
    #[schema(nullable = true, default = "100", example = "20")]
133
    pub max_new_tokens: Option<u32>,
OlivierDehaene's avatar
OlivierDehaene committed
134
    #[serde(default)]
135
    #[schema(nullable = true, default = "null", example = false)]
136
137
    pub return_full_text: Option<bool>,
    #[serde(default)]
138
    #[schema(inline, max_items = 4, example = json ! (["photographer"]))]
139
    pub stop: Vec<String>,
OlivierDehaene's avatar
OlivierDehaene committed
140
    #[serde(default)]
141
    #[schema(nullable = true, default = "null", example = "null")]
142
143
    pub truncate: Option<usize>,
    #[serde(default)]
144
145
146
    #[schema(default = "false", example = true)]
    pub watermark: bool,
    #[serde(default)]
147
    #[schema(default = "true")]
OlivierDehaene's avatar
OlivierDehaene committed
148
    pub details: bool,
149
    #[serde(default)]
150
151
152
    #[schema(default = "true")]
    pub decoder_input_details: bool,
    #[serde(default)]
153
154
155
156
157
158
    #[schema(
        exclusive_minimum = 0,
        nullable = true,
        default = "null",
        example = "null"
    )]
159
    pub seed: Option<u64>,
Nicolas Patry's avatar
Nicolas Patry committed
160
161
162
    #[serde(default)]
    #[schema(exclusive_minimum = 0, nullable = true, default = "null", example = 5)]
    pub top_n_tokens: Option<u32>,
Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
163
164
}

165
fn default_max_new_tokens() -> Option<u32> {
166
    Some(100)
Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
167
168
169
170
}

fn default_parameters() -> GenerateParameters {
    GenerateParameters {
171
        best_of: None,
172
173
174
175
        temperature: None,
        repetition_penalty: None,
        top_k: None,
        top_p: None,
176
        typical_p: None,
177
        do_sample: true,
Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
178
        max_new_tokens: default_max_new_tokens(),
179
        return_full_text: None,
180
        stop: Vec::new(),
181
        truncate: None,
182
        watermark: false,
OlivierDehaene's avatar
OlivierDehaene committed
183
        details: false,
184
        decoder_input_details: false,
185
        seed: None,
Nicolas Patry's avatar
Nicolas Patry committed
186
        top_n_tokens: None,
Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
187
188
189
    }
}

190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
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
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
#[derive(Clone, Deserialize, Serialize)]
pub(crate) struct ChatCompletion {
    pub id: String,
    pub object: String,
    pub created: u64,
    pub model: String,
    pub system_fingerprint: String,
    pub choices: Vec<ChatCompletionComplete>,
    pub usage: Usage,
}

#[derive(Clone, Deserialize, Serialize)]
pub(crate) struct ChatCompletionComplete {
    pub index: u32,
    pub message: Message,
    pub logprobs: Option<Vec<f32>>,
    pub finish_reason: String,
}

#[derive(Clone, Deserialize, Serialize)]
pub(crate) struct Usage {
    pub prompt_tokens: u32,
    pub completion_tokens: u32,
    pub total_tokens: u32,
}

impl ChatCompletion {
    pub(crate) fn new(
        model: String,
        system_fingerprint: String,
        output: String,
        created: u64,
        details: Details,
        return_logprobs: bool,
    ) -> Self {
        Self {
            id: String::new(),
            object: "text_completion".into(),
            created,
            model,
            system_fingerprint,
            choices: vec![ChatCompletionComplete {
                index: 0,
                message: Message {
                    role: "assistant".into(),
                    content: output,
                },
                logprobs: return_logprobs
                    .then(|| details.tokens.iter().map(|t| t.logprob).collect()),
                finish_reason: details.finish_reason.to_string(),
            }],
            usage: Usage {
                prompt_tokens: details.prefill.len() as u32,
                completion_tokens: details.generated_tokens,
                total_tokens: details.prefill.len() as u32 + details.generated_tokens,
            },
        }
    }
}

#[derive(Clone, Deserialize, Serialize)]
pub(crate) struct ChatCompletionChunk {
    pub id: String,
    pub object: String,
    pub created: u64,
    pub model: String,
    pub system_fingerprint: String,
    pub choices: Vec<ChatCompletionChoice>,
}

#[derive(Clone, Deserialize, Serialize)]
pub(crate) struct ChatCompletionChoice {
    pub index: u32,
    pub delta: ChatCompletionDelta,
    pub logprobs: Option<f32>,
    pub finish_reason: Option<String>,
}

#[derive(Clone, Debug, Deserialize, Serialize)]
pub(crate) struct ChatCompletionDelta {
    pub role: String,
    pub content: String,
}

impl ChatCompletionChunk {
    pub(crate) fn new(
        model: String,
        system_fingerprint: String,
        delta: String,
        created: u64,
        index: u32,
        logprobs: Option<f32>,
        finish_reason: Option<String>,
    ) -> Self {
        Self {
            id: String::new(),
            object: "text_completion".to_string(),
            created,
            model,
            system_fingerprint,
            choices: vec![ChatCompletionChoice {
                index,
                delta: ChatCompletionDelta {
                    role: "assistant".to_string(),
                    content: delta,
                },
                logprobs,
                finish_reason,
            }],
        }
    }
}

fn default_request_messages() -> Vec<Message> {
    vec![Message {
        role: "user".to_string(),
        content: "My name is David and I".to_string(),
    }]
}

#[derive(Clone, Deserialize, ToSchema, Serialize)]
pub(crate) struct ChatRequest {
    /// UNUSED
    #[schema(example = "bigscience/blomm-560m")]
    /// ID of the model to use. See the model endpoint compatibility table for details on which models work with the Chat API.
    pub model: String, /* NOTE: UNUSED */

    /// A list of messages comprising the conversation so far.
    #[serde(default = "default_request_messages")]
    pub messages: Vec<Message>,

    /// Number between -2.0 and 2.0. Positive values penalize new tokens based on their existing frequency in the text so far,
    /// decreasing the model's likelihood to repeat the same line verbatim.
    #[serde(default)]
    pub frequency_penalty: Option<f32>,

    /// UNUSED
    /// Modify the likelihood of specified tokens appearing in the completion. Accepts a JSON object that maps tokens
    /// (specified by their token ID in the tokenizer) to an associated bias value from -100 to 100. Mathematically,
    /// the bias is added to the logits generated by the model prior to sampling. The exact effect will vary per model,
    /// but values between -1 and 1 should decrease or increase likelihood of selection; values like -100 or 100 should
    /// result in a ban or exclusive selection of the relevant token.
    #[serde(default)]
    pub logit_bias: Option<Vec<f32>>,

    /// Whether to return log probabilities of the output tokens or not. If true, returns the log probabilities of each
    /// output token returned in the content of message.
    #[serde(default)]
    pub logprobs: Option<bool>,

    /// UNUSED
    /// An integer between 0 and 5 specifying the number of most likely tokens to return at each token position, each with
    /// an associated log probability. logprobs must be set to true if this parameter is used.
    #[serde(default)]
    pub top_logprobs: Option<u32>,

    /// The maximum number of tokens that can be generated in the chat completion.
    #[serde(default)]
    pub max_tokens: Option<u32>,

    /// UNUSED
    /// How many chat completion choices to generate for each input message. Note that you will be charged based on the
    /// number of generated tokens across all of the choices. Keep n as 1 to minimize costs.
    #[serde(default)]
    pub n: Option<u32>,

    /// UNUSED
    /// Number between -2.0 and 2.0. Positive values penalize new tokens based on whether they appear in the text so far,
    /// increasing the model's likelihood to talk about new topics
    #[serde(default)]
    pub presence_penalty: Option<f32>,

    #[serde(default = "bool::default")]
    pub stream: bool,

    #[schema(nullable = true, example = 42)]
    pub seed: Option<u64>,
}

#[derive(Clone, Deserialize, ToSchema, Serialize)]
pub(crate) struct Message {
    #[schema(example = "user")]
    pub role: String,
    #[schema(example = "My name is David and I")]
    pub content: String,
}

377
#[derive(Clone, Debug, Deserialize, ToSchema)]
Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
378
pub(crate) struct GenerateRequest {
379
    #[schema(example = "My name is Olivier and I")]
Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
380
381
382
383
384
    pub inputs: String,
    #[serde(default = "default_parameters")]
    pub parameters: GenerateParameters,
}

385
386
387
388
389
390
391
#[derive(Clone, Debug, Deserialize, ToSchema)]
pub(crate) struct CompatGenerateRequest {
    #[schema(example = "My name is Olivier and I")]
    pub inputs: String,
    #[serde(default = "default_parameters")]
    pub parameters: GenerateParameters,
    #[serde(default)]
OlivierDehaene's avatar
OlivierDehaene committed
392
    #[schema(default = "false")]
393
394
395
396
397
398
399
400
401
402
403
404
    pub stream: bool,
}

impl From<CompatGenerateRequest> for GenerateRequest {
    fn from(req: CompatGenerateRequest) -> Self {
        Self {
            inputs: req.inputs,
            parameters: req.parameters,
        }
    }
}

405
406
407
408
409
410
#[derive(Debug, Serialize, ToSchema)]
pub struct PrefillToken {
    #[schema(example = 0)]
    id: u32,
    #[schema(example = "test")]
    text: String,
411
    #[schema(nullable = true, example = - 0.34)]
412
413
414
    logprob: f32,
}

415
416
417
418
419
420
#[derive(Debug, Serialize, ToSchema)]
pub struct Token {
    #[schema(example = 0)]
    id: u32,
    #[schema(example = "test")]
    text: String,
421
    #[schema(nullable = true, example = - 0.34)]
422
    logprob: f32,
423
424
    #[schema(example = "false")]
    special: bool,
425
426
427
428
429
430
431
432
433
434
435
436
437
}

#[derive(Serialize, ToSchema)]
#[serde(rename_all(serialize = "snake_case"))]
pub(crate) enum FinishReason {
    #[schema(rename = "length")]
    Length,
    #[serde(rename = "eos_token")]
    #[schema(rename = "eos_token")]
    EndOfSequenceToken,
    #[schema(rename = "stop_sequence")]
    StopSequence,
}
438

439
440
441
442
443
444
445
446
447
448
impl std::fmt::Display for FinishReason {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            FinishReason::Length => write!(f, "length"),
            FinishReason::EndOfSequenceToken => write!(f, "eos_token"),
            FinishReason::StopSequence => write!(f, "stop_sequence"),
        }
    }
}

449
450
451
452
453
454
455
456
457
458
459
460
#[derive(Serialize, ToSchema)]
pub(crate) struct BestOfSequence {
    #[schema(example = "test")]
    pub generated_text: String,
    #[schema(example = "length")]
    pub finish_reason: FinishReason,
    #[schema(example = 1)]
    pub generated_tokens: u32,
    #[schema(nullable = true, example = 42)]
    pub seed: Option<u64>,
    pub prefill: Vec<PrefillToken>,
    pub tokens: Vec<Token>,
Nicolas Patry's avatar
Nicolas Patry committed
461
462
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub top_tokens: Vec<Vec<Token>>,
463
464
}

465
#[derive(Serialize, ToSchema)]
OlivierDehaene's avatar
OlivierDehaene committed
466
pub(crate) struct Details {
467
468
469
    #[schema(example = "length")]
    pub finish_reason: FinishReason,
    #[schema(example = 1)]
OlivierDehaene's avatar
OlivierDehaene committed
470
    pub generated_tokens: u32,
471
    #[schema(nullable = true, example = 42)]
472
    pub seed: Option<u64>,
473
474
    pub prefill: Vec<PrefillToken>,
    pub tokens: Vec<Token>,
475
476
    #[serde(skip_serializing_if = "Option::is_none")]
    pub best_of_sequences: Option<Vec<BestOfSequence>>,
Nicolas Patry's avatar
Nicolas Patry committed
477
478
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub top_tokens: Vec<Vec<Token>>,
OlivierDehaene's avatar
OlivierDehaene committed
479
480
}

481
#[derive(Serialize, ToSchema)]
482
pub(crate) struct GenerateResponse {
483
    #[schema(example = "test")]
Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
484
    pub generated_text: String,
OlivierDehaene's avatar
OlivierDehaene committed
485
486
    #[serde(skip_serializing_if = "Option::is_none")]
    pub details: Option<Details>,
Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
487
}
488

489
490
491
492
493
494
#[derive(Serialize, ToSchema)]
pub(crate) struct StreamDetails {
    #[schema(example = "length")]
    pub finish_reason: FinishReason,
    #[schema(example = 1)]
    pub generated_tokens: u32,
495
    #[schema(nullable = true, example = 42)]
496
497
498
499
    pub seed: Option<u64>,
}

#[derive(Serialize, ToSchema)]
500
pub(crate) struct StreamResponse {
501
    pub index: u32,
502
    pub token: Token,
Nicolas Patry's avatar
Nicolas Patry committed
503
504
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub top_tokens: Vec<Token>,
505
    #[schema(nullable = true, default = "null", example = "test")]
506
    pub generated_text: Option<String>,
507
508
    #[schema(nullable = true, default = "null")]
    pub details: Option<StreamDetails>,
509
510
}

511
#[derive(Serialize, ToSchema)]
512
513
pub(crate) struct ErrorResponse {
    pub error: String,
514
    pub error_type: String,
515
}
516
517

#[cfg(test)]
518
mod tests {
519
520
521
    use std::io::Write;
    use tokenizers::Tokenizer;

522
    pub(crate) async fn get_tokenizer() -> Tokenizer {
523
524
        let filename = std::path::Path::new("tokenizer.json");
        if !filename.exists() {
525
526
527
528
529
530
            let content = reqwest::get("https://huggingface.co/gpt2/raw/main/tokenizer.json")
                .await
                .unwrap()
                .bytes()
                .await
                .unwrap();
531
532
            let tmp_filename = "tokenizer.json.temp";
            let mut file = std::fs::File::create(tmp_filename).unwrap();
533
            file.write_all(&content).unwrap();
534
535
536
537
            // Re-check if another process has written this file maybe.
            if !filename.exists() {
                std::fs::rename(tmp_filename, filename).unwrap()
            }
538
539
540
541
        }
        Tokenizer::from_file("tokenizer.json").unwrap()
    }
}