"vscode:/vscode.git/clone" did not exist on "4a292f670db863fbdea906ad41aec2c631eedbdb"
validation.rs 6.83 KB
Newer Older
Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
1
/// Payload validation logic
2
use crate::{GenerateParameters, GenerateRequest};
3
4
use rand::rngs::ThreadRng;
use rand::Rng;
5
use text_generation_client::{NextTokenChooserParameters, StoppingCriteriaParameters};
Olivier Dehaene's avatar
Olivier Dehaene committed
6
use thiserror::Error;
Olivier Dehaene's avatar
Olivier Dehaene committed
7
8
9
use tokenizers::tokenizer::Tokenizer;
use tokio::sync::{mpsc, oneshot};

10
11
12
const MAX_MAX_NEW_TOKENS: u32 = 512;
const MAX_STOP_SEQUENCES: usize = 4;

Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
13
/// Validation
Olivier Dehaene's avatar
Olivier Dehaene committed
14
#[derive(Debug, Clone)]
Olivier Dehaene's avatar
Olivier Dehaene committed
15
pub struct Validation {
Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
16
    /// Channel to communicate with the background validation task
Olivier Dehaene's avatar
Olivier Dehaene committed
17
18
19
20
    sender: mpsc::Sender<ValidationRequest>,
}

impl Validation {
Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
21
    pub(crate) fn new(workers: usize, tokenizer: Tokenizer, max_input_length: usize) -> Self {
22
        // Create channel
Olivier Dehaene's avatar
Olivier Dehaene committed
23
24
        let (validation_sender, validation_receiver) = mpsc::channel(128);

Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
25
26
27
28
29
30
31
        // Launch background validation task
        tokio::spawn(validation_task(
            workers,
            tokenizer,
            max_input_length,
            validation_receiver,
        ));
Olivier Dehaene's avatar
Olivier Dehaene committed
32
33
34
35
36
37

        Self {
            sender: validation_sender,
        }
    }

Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
38
    /// Validate a payload and get the number of tokens in the input
Olivier Dehaene's avatar
Olivier Dehaene committed
39
40
41
    pub(crate) async fn validate(
        &self,
        request: GenerateRequest,
42
    ) -> Result<ValidGenerateRequest, ValidationError> {
Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
43
        // Create response channel
Olivier Dehaene's avatar
Olivier Dehaene committed
44
        let (sender, receiver) = oneshot::channel();
Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
45
46
        // Send request to the background validation task
        // Unwrap is safe here
Olivier Dehaene's avatar
Olivier Dehaene committed
47
        self.sender.send((request, sender)).await.unwrap();
Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
48
49
        // Await on response channel
        // Unwrap is safe here
Olivier Dehaene's avatar
Olivier Dehaene committed
50
51
52
53
        receiver.await.unwrap()
    }
}

Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
54
55
56
57
58
59
60
61
62
63
64
65
/// Validation task
/// Load balance the validation requests between multiple validation workers
async fn validation_task(
    workers: usize,
    tokenizer: Tokenizer,
    max_input_length: usize,
    mut receiver: mpsc::Receiver<ValidationRequest>,
) {
    let mut workers_senders = Vec::with_capacity(workers);

    // Create workers
    for _ in 0..workers {
66
        let tokenizer_clone: Tokenizer = tokenizer.clone().into();
Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
        // Create channel to communicate with worker
        let (worker_sender, worker_receiver) = mpsc::channel(workers);
        workers_senders.push(worker_sender);

        // Spawn worker
        tokio::task::spawn_blocking(move || {
            validation_worker(tokenizer_clone, max_input_length, worker_receiver)
        });
    }

    loop {
        // Load balance requests between workers
        for sender in workers_senders.iter() {
            if let Some(validation_request) = receiver.recv().await {
                sender.send(validation_request).await.unwrap();
            } else {
                return;
            }
        }
    }
}

/// Check the parameters inside the payload and get the number of tokens inside the input using
/// the tokenizer
fn validation_worker(
92
    tokenizer: Tokenizer,
Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
93
94
95
    max_input_length: usize,
    mut receiver: mpsc::Receiver<ValidationRequest>,
) {
96
97
98
    // Seed rng
    let mut rng = rand::thread_rng();

Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
99
100
    // Loop over requests
    while let Some((request, response_tx)) = receiver.blocking_recv() {
101
        response_tx
102
            .send(validate(request, &tokenizer, max_input_length, &mut rng))
103
            .unwrap_or(())
104
105
    }
}
Olivier Dehaene's avatar
Olivier Dehaene committed
106

107
fn validate(
108
    request: GenerateRequest,
109
110
    tokenizer: &Tokenizer,
    max_input_length: usize,
111
    rng: &mut ThreadRng,
112
) -> Result<ValidGenerateRequest, ValidationError> {
113
114
115
116
117
118
119
120
121
122
123
124
125
126
    let GenerateParameters {
        temperature,
        repetition_penalty,
        top_k,
        top_p,
        do_sample,
        max_new_tokens,
        stop: stop_sequences,
        seed,
        ..
    } = request.parameters;

    let temperature = temperature.unwrap_or(1.0);
    if temperature <= 0.0 {
127
128
        return Err(ValidationError::Temperature);
    }
129
130
131

    let repetition_penalty = repetition_penalty.unwrap_or(1.0);
    if repetition_penalty <= 0.0 {
132
133
        return Err(ValidationError::RepetitionPenalty);
    }
134
135
136

    let top_p = top_p.unwrap_or(1.0);
    if top_p <= 0.0 || top_p > 1.0 {
137
138
        return Err(ValidationError::TopP);
    }
139
140
141
142
143
144
145
146
147
148
149
150
151
152

    // Different because the proto default value is 0 while it is not a valid value
    // for the user
    let top_k: u32 = match top_k {
        None => Ok(0),
        Some(top_k) => {
            if top_k <= 0 {
                return Err(ValidationError::TopK);
            }
            Ok(top_k as u32)
        }
    }?;

    if max_new_tokens == 0 || max_new_tokens > MAX_MAX_NEW_TOKENS {
153
154
        return Err(ValidationError::MaxNewTokens(MAX_MAX_NEW_TOKENS));
    }
155
156

    if stop_sequences.len() > MAX_STOP_SEQUENCES {
157
        return Err(ValidationError::StopSequence(
158
            MAX_STOP_SEQUENCES,
159
            stop_sequences.len(),
160
        ));
161
162
    }

163
    // If seed is None, assign a random one
164
    let seed = match seed {
165
166
167
        None => rng.gen(),
        Some(seed) => seed,
    };
168

169
170
    // Get the number of tokens in the input
    match tokenizer.encode(request.inputs.clone(), true) {
171
172
        Ok(encoding) => {
            let input_length = encoding.len();
173
174

            if input_length > max_input_length {
175
                Err(ValidationError::InputLength(input_length, max_input_length))
176
            } else {
177
178
179
                // Return ValidGenerateRequest
                let parameters = NextTokenChooserParameters {
                    temperature,
180
                    repetition_penalty,
181
                    top_k,
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
                    top_p,
                    do_sample,
                    seed,
                };
                let stopping_parameters = StoppingCriteriaParameters {
                    max_new_tokens,
                    stop_sequences,
                };

                Ok(ValidGenerateRequest {
                    inputs: request.inputs,
                    input_length: input_length as u32,
                    parameters,
                    stopping_parameters,
                })
197
            }
198
        }
199
        Err(err) => Err(ValidationError::Tokenizer(err.to_string())),
Olivier Dehaene's avatar
Olivier Dehaene committed
200
201
    }
}
Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
202
203
204

type ValidationRequest = (
    GenerateRequest,
205
    oneshot::Sender<Result<ValidGenerateRequest, ValidationError>>,
Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
206
207
);

208
209
210
211
212
213
214
215
#[derive(Debug)]
pub(crate) struct ValidGenerateRequest {
    pub inputs: String,
    pub input_length: u32,
    pub parameters: NextTokenChooserParameters,
    pub stopping_parameters: StoppingCriteriaParameters,
}

Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
216
217
#[derive(Error, Debug)]
pub enum ValidationError {
218
    #[error("temperature must be strictly positive")]
Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
219
    Temperature,
220
221
    #[error("repetition_penalty must be strictly positive")]
    RepetitionPenalty,
222
    #[error("top_p must be > 0.0 and <= 1.0")]
Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
223
    TopP,
224
    #[error("top_k must be strictly positive")]
Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
225
    TopK,
226
    #[error("max_new_tokens must be strictly positive and <= {0}")]
227
    MaxNewTokens(u32),
228
    #[error("inputs must have less than {1} tokens. Given: {0}")]
229
    InputLength(usize, usize),
230
231
    #[error("stop supports up to {0} stop sequences. Given: {1}")]
    StopSequence(usize, usize),
232
233
    #[error("tokenizer error {0}")]
    Tokenizer(String),
Olivier Dehaene's avatar
v0.1.0  
Olivier Dehaene committed
234
}