scheduler.rs 60.5 KB
Newer Older
1
/// Batching and inference logic
OlivierDehaene's avatar
OlivierDehaene committed
2
3
4
use crate::infer::v3::queue::{Entry, Queue};
use crate::infer::{
    GenerateStreamResponse, GeneratedText, InferError, InferStreamResponse, Scheduler,
5
};
OlivierDehaene's avatar
OlivierDehaene committed
6
7
use crate::validation::ValidGenerateRequest;
use crate::{FinishReason, PrefillToken, Token};
8
use nohash_hasher::IntMap;
9
10
11
12
use std::sync::{
    atomic::{AtomicBool, Ordering},
    Arc,
};
OlivierDehaene's avatar
OlivierDehaene committed
13
14
use text_generation_client::v3::{Batch, CachedBatch, Generation, ShardedClient};
use text_generation_client::ClientError;
OlivierDehaene's avatar
OlivierDehaene committed
15
use tokio::sync::mpsc::error::SendError;
OlivierDehaene's avatar
OlivierDehaene committed
16
use tokio::sync::{mpsc, Notify, OwnedSemaphorePermit};
17
use tokio::time::Instant;
OlivierDehaene's avatar
OlivierDehaene committed
18
use tokio_stream::wrappers::UnboundedReceiverStream;
19
use tracing::{info_span, instrument, Instrument, Span};
20

OlivierDehaene's avatar
OlivierDehaene committed
21
pub(crate) struct SchedulerV3 {
22
23
    /// Request queue
    queue: Queue,
OlivierDehaene's avatar
OlivierDehaene committed
24
25
    /// Notify batcher on queue appends
    batching_task_notifier: Arc<Notify>,
26
27
}

OlivierDehaene's avatar
OlivierDehaene committed
28
impl SchedulerV3 {
29
    #[allow(clippy::too_many_arguments)]
30
31
    pub(crate) fn new(
        client: ShardedClient,
32
        waiting_served_ratio: f32,
33
        max_batch_prefill_tokens: u32,
34
        max_batch_total_tokens: u32,
35
        max_waiting_tokens: usize,
36
        max_batch_size: Option<usize>,
37
        requires_padding: bool,
38
        window_size: Option<u32>,
Nicolas Patry's avatar
Nicolas Patry committed
39
        speculate: u32,
40
        generation_health: Arc<AtomicBool>,
41
    ) -> Self {
Nicolas Patry's avatar
Nicolas Patry committed
42
        let queue = Queue::new(requires_padding, 16, window_size, speculate);
OlivierDehaene's avatar
OlivierDehaene committed
43
        let batching_task_notifier = Arc::new(Notify::new());
44
45
46
47

        // Spawn batching background task that contains all the inference logic
        tokio::spawn(batching_task(
            client,
48
            waiting_served_ratio,
49
            max_batch_prefill_tokens,
50
            max_batch_total_tokens,
51
            max_waiting_tokens,
52
            max_batch_size,
53
            queue.clone(),
OlivierDehaene's avatar
OlivierDehaene committed
54
            batching_task_notifier.clone(),
55
            generation_health,
56
57
58
        ));

        Self {
59
            queue,
OlivierDehaene's avatar
OlivierDehaene committed
60
            batching_task_notifier,
61
62
        }
    }
OlivierDehaene's avatar
OlivierDehaene committed
63
}
64

OlivierDehaene's avatar
OlivierDehaene committed
65
impl Scheduler for SchedulerV3 {
66
    #[instrument(skip_all)]
OlivierDehaene's avatar
OlivierDehaene committed
67
    fn schedule(
68
        &self,
OlivierDehaene's avatar
OlivierDehaene committed
69
70
        request: ValidGenerateRequest,
        permit: OwnedSemaphorePermit,
71
    ) -> Result<GenerateStreamResponse, InferError> {
72
        // MPSC channel to communicate with the background batching task
OlivierDehaene's avatar
OlivierDehaene committed
73
        let (response_tx, response_rx) = mpsc::unbounded_channel();
OlivierDehaene's avatar
OlivierDehaene committed
74
        let input_length = request.input_length;
75

76
77
        // Append the request to the queue
        self.queue.append(Entry {
OlivierDehaene's avatar
OlivierDehaene committed
78
            request,
79
            response_tx,
80
81
82
            span: Span::current(),
            temp_span: None,
            queue_time: Instant::now(),
83
84
85
            batch_time: None,
        });

86
        // Notify the background task that we have a new entry in the queue that needs
87
        // to be batched
OlivierDehaene's avatar
OlivierDehaene committed
88
        self.batching_task_notifier.notify_one();
89
90

        // Return stream
91
92
93
94
95
        Ok((
            permit,
            input_length,
            UnboundedReceiverStream::new(response_rx),
        ))
96
    }
97
98
}

99
100
101
102
/// Batching logic
/// Will be launched in a background Tokio task
///
/// Batches requests and sends them to the inference server
103
#[allow(clippy::too_many_arguments)]
OlivierDehaene's avatar
OlivierDehaene committed
104
pub(crate) async fn batching_task(
105
    mut client: ShardedClient,
106
    waiting_served_ratio: f32,
107
    max_batch_prefill_tokens: u32,
108
    max_batch_total_tokens: u32,
109
    max_waiting_tokens: usize,
110
    max_batch_size: Option<usize>,
111
    queue: Queue,
OlivierDehaene's avatar
OlivierDehaene committed
112
    notifier: Arc<Notify>,
113
    generation_health: Arc<AtomicBool>,
114
115
116
117
) {
    // Infinite loop
    loop {
        // Wait for a notification from the Infer struct
OlivierDehaene's avatar
OlivierDehaene committed
118
        notifier.notified().await;
119

120
        // Get the next batch from the queue
121
        // This batch might be smaller than the maximum batch size if there are not enough requests
122
        // waiting in the queue
123
        while let Some((mut entries, batch, span)) = queue
124
125
126
127
128
129
            .next_batch(
                None,
                max_batch_size,
                max_batch_prefill_tokens,
                max_batch_total_tokens,
            )
130
            .await
131
        {
132
            let mut cached_batch = prefill(&mut client, batch, &mut entries, &generation_health)
133
134
                .instrument(span)
                .await;
135
136
137
138
139
140
141
            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;
142
                let batch_max_tokens = batch.max_tokens;
143
                let mut batches = vec![batch];
144
                metrics::gauge!("tgi_batch_current_size", batch_size as f64);
145
146
147
148
149
150
151
152
153
154
155
                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)
                };

156
                let token_budget = max_batch_total_tokens.saturating_sub(batch_max_tokens);
157
                let max_size = max_batch_size.map(|max_size| max_size - batch_size as usize);
158
159

                // Try to get a new batch
160
                if let Some((mut new_entries, new_batch, span)) = queue
161
                    .next_batch(min_size, max_size, max_batch_prefill_tokens, token_budget)
162
                    .await
163
164
165
166
167
168
169
                {
                    // 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");
                    }
170

171
172
173
174
175
176
177
178
179
180
181
182
                    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
183
184
185
186
                    let new_cached_batch =
                        prefill(&mut client, new_batch, &mut new_entries, &generation_health)
                            .instrument(span)
                            .await;
187
188
189
190
191
192
                    // 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);
193
194
                    }
                }
195

196
197
198
199
200
201
                // 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
202
                    let entry_batch_span = info_span!(parent: &entry.span, "infer");
203
204
                    // Add relationships
                    next_batch_span.follows_from(&entry_batch_span);
205
206
207
208
                    entry_batch_span.follows_from(&next_batch_span);
                    // Update entry
                    entry.temp_span = Some(entry_batch_span);
                });
209

210
                cached_batch = decode(&mut client, batches, &mut entries, &generation_health)
211
212
                    .instrument(next_batch_span)
                    .await;
213
214
                waiting_tokens += 1;
            }
215
            metrics::gauge!("tgi_batch_current_size", 0.0);
216
            metrics::gauge!("tgi_batch_current_max_tokens", 0.0);
217
218
219
220
        }
    }
}

221
#[instrument(skip_all)]
222
223
224
async fn prefill(
    client: &mut ShardedClient,
    batch: Batch,
225
    entries: &mut IntMap<u64, Entry>,
226
    generation_health: &Arc<AtomicBool>,
227
) -> Option<CachedBatch> {
228
    let start_time = Instant::now();
229
    let batch_id = batch.id;
230
    metrics::increment_counter!("tgi_batch_inference_count", "method" => "prefill");
231
232

    match client.prefill(batch).await {
233
        Ok((generations, next_batch, timings)) => {
234
235
            // Update health
            generation_health.store(true, Ordering::SeqCst);
236
237

            let start_filtering_time = Instant::now();
238
            // Send generated tokens and filter stopped entries
239
240
241
            filter_send_generations(generations, entries);

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

244
245
246
            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");
247
            metrics::histogram!("tgi_batch_inference_duration", start_time.elapsed().as_secs_f64(), "method" => "prefill");
248
249
250
251
252
            metrics::increment_counter!("tgi_batch_inference_success", "method" => "prefill");
            next_batch
        }
        // If we have an error, we discard the whole batch
        Err(err) => {
253
254
            // Update health
            generation_health.store(false, Ordering::SeqCst);
255
            let _ = client.clear_cache(Some(batch_id)).await;
256
257
258
259
260
261
262
263
264
265
            send_errors(err, entries);
            metrics::increment_counter!("tgi_batch_inference_failure", "method" => "prefill");
            None
        }
    }
}

#[instrument(skip_all)]
async fn decode(
    client: &mut ShardedClient,
266
    batches: Vec<CachedBatch>,
267
    entries: &mut IntMap<u64, Entry>,
268
    generation_health: &Arc<AtomicBool>,
269
) -> Option<CachedBatch> {
270
    let start_time = Instant::now();
271
    let batch_ids: Vec<u64> = batches.iter().map(|b| b.id).collect();
272
    metrics::increment_counter!("tgi_batch_inference_count", "method" => "decode");
273
274

    match client.decode(batches).await {
275
        Ok((generations, next_batch, timings)) => {
276
277
            // Update health
            generation_health.store(true, Ordering::SeqCst);
278
279

            let start_filtering_time = Instant::now();
280
            // Send generated tokens and filter stopped entries
281
282
283
            filter_send_generations(generations, entries);

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

286
287
288
289
290
291
            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");
292
            metrics::histogram!("tgi_batch_inference_duration", start_time.elapsed().as_secs_f64(), "method" => "decode");
293
            metrics::increment_counter!("tgi_batch_inference_success", "method" => "decode");
294
295
296
297
            next_batch
        }
        // If we have an error, we discard the whole batch
        Err(err) => {
298
            generation_health.store(false, Ordering::SeqCst);
299
300
301
            for id in batch_ids {
                let _ = client.clear_cache(Some(id)).await;
            }
302
            send_errors(err, entries);
303
            metrics::increment_counter!("tgi_batch_inference_failure", "method" => "decode");
304
305
306
307
308
            None
        }
    }
}

309
310
/// Filter a `batch` and remove all requests not present in `entries`
#[instrument(skip_all)]
311
312
async fn filter_batch(
    client: &mut ShardedClient,
313
    next_batch: Option<CachedBatch>,
314
    entries: &IntMap<u64, Entry>,
315
) -> Option<CachedBatch> {
316
317
318
319
320
321
322
323
324
325
    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
326
    batch.request_ids.retain(|id| entries.contains_key(id));
327

328
    if batch.request_ids.is_empty() {
329
330
331
332
333
334
335
336
337
        // 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
338
        client.filter_batch(id, batch.request_ids).await.unwrap()
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
    }
}

/// 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
360
            tracing::error!("Entry response channel error.");
361
362
363
364
365
366
367
368
369
370
371
372
373
            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
374
) -> Result<bool, Box<SendError<Result<InferStreamResponse, InferError>>>> {
375
    // Return directly if the channel is disconnected
OlivierDehaene's avatar
OlivierDehaene committed
376
377
    if entry.response_tx.is_closed() {
        metrics::increment_counter!("tgi_request_failure", "err" => "dropped");
378
379
380
        return Ok(true);
    }

381
382
383
    let mut stopped = false;

    if let Some(prefill_tokens) = generation.prefill_tokens {
OlivierDehaene's avatar
OlivierDehaene committed
384
385
386
387
388
389
390
391
392
393
        // Create Token objects
        // We do that here instead of in the Python code as Rust for loops are faster
        let prefill_tokens = prefill_tokens
            .ids
            .into_iter()
            .zip(prefill_tokens.logprobs)
            .zip(prefill_tokens.texts)
            .map(|((id, logprob), text)| PrefillToken { id, text, logprob })
            .collect();

394
        // Send message
OlivierDehaene's avatar
OlivierDehaene committed
395
396
397
        entry
            .response_tx
            .send(Ok(InferStreamResponse::Prefill(prefill_tokens)))?;
398
399
400
    }

    // Create last Token
Nicolas Patry's avatar
Nicolas Patry committed
401
402
403
404
405
406
    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()
407
408
409
        .zip(tokens_.logprobs)
        .zip(tokens_.texts)
        .zip(tokens_.is_special)
Nicolas Patry's avatar
Nicolas Patry committed
410
411
412
413
414
415
416
417
418
419
        .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
420
421
            top_tokens_
                .ids
Nicolas Patry's avatar
Nicolas Patry committed
422
423
424
425
426
                .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
427
                    id,
Nicolas Patry's avatar
Nicolas Patry committed
428
                    text: text.to_string(),
Nicolas Patry's avatar
Nicolas Patry committed
429
430
                    logprob,
                    special,
Nicolas Patry's avatar
Nicolas Patry committed
431
432
433
434
435
436
437
438
439
440
441
442
443
                })
                .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,
OlivierDehaene's avatar
OlivierDehaene committed
444
                    generated_text: GeneratedText::from(generated_text.clone()),
Nicolas Patry's avatar
Nicolas Patry committed
445
446
447
448
449
450
451
452
453
454
455
                    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
456
457
    }

458
459
460
    Ok(stopped)
}

461
/// Send errors to Infer for all `entries`
462
463
#[instrument(skip_all)]
fn send_errors(error: ClientError, entries: &mut IntMap<u64, Entry>) {
464
    entries.drain().for_each(|(_, entry)| {
465
466
467
        // 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());
468
        metrics::increment_counter!("tgi_request_failure", "err" => "generation");
469
470
        tracing::error!("{err}");

471
472
473
        // unwrap_or is valid here as we don't care if the receiver is gone.
        entry
            .response_tx
OlivierDehaene's avatar
OlivierDehaene committed
474
            .send(Err(err))
475
476
477
478
            .unwrap_or(());
    });
}

OlivierDehaene's avatar
OlivierDehaene committed
479
480
481
482
483
484
485
486
487
impl From<text_generation_client::v3::GeneratedText> for GeneratedText {
    fn from(value: text_generation_client::v3::GeneratedText) -> Self {
        let v3_finish_reason =
            text_generation_client::v3::FinishReason::try_from(value.finish_reason).unwrap();
        let finish_reason = match v3_finish_reason {
            text_generation_client::v3::FinishReason::Length => FinishReason::Length,
            text_generation_client::v3::FinishReason::EosToken => FinishReason::EndOfSequenceToken,
            text_generation_client::v3::FinishReason::StopSequence => FinishReason::StopSequence,
        };
488

OlivierDehaene's avatar
OlivierDehaene committed
489
490
491
492
493
        Self {
            text: value.text,
            generated_tokens: value.generated_tokens,
            finish_reason,
            seed: value.seed,
494
495
496
        }
    }
}
497
498
499
500
501

// tests
#[cfg(test)]
mod tests {
    use crate::infer::raise_exception;
Nicolas Patry's avatar
Nicolas Patry committed
502
    use crate::{ChatTemplateInputs, TextMessage};
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
    use minijinja::Environment;

    #[test]
    fn test_chat_template() {
        let env = Environment::new();

        let source = r#"
        {% for message in messages %}
            {% if message['role'] == 'system' %}
                {% if message['content']%}
                    {{'### System:\n' + message['content']+'\n\n'}}
                {% endif %}
            {% elif message['role'] == 'user' %}
                {{'### User:\n' + message['content']+'\n\n'}}
            {% elif message['role'] == 'assistant' %}
                {{'### Assistant:\n'  + message['content']}}
            {% endif %}
            {% if loop.last and add_generation_prompt %}
                {{ '### Assistant:\n' }}
            {% endif %}
        {% endfor %}"#;

        // trim all the whitespace
        let source = source
            .lines()
            .map(|line| line.trim())
            .collect::<Vec<&str>>()
            .join("");

        let tmpl = env.template_from_str(&source);

        let chat_template_inputs = ChatTemplateInputs {
            messages: vec![
Nicolas Patry's avatar
Nicolas Patry committed
536
                TextMessage {
537
                    role: "user".to_string(),
Nicolas Patry's avatar
Nicolas Patry committed
538
                    content: "Hi!".to_string(),
539
                },
Nicolas Patry's avatar
Nicolas Patry committed
540
                TextMessage {
541
                    role: "assistant".to_string(),
Nicolas Patry's avatar
Nicolas Patry committed
542
                    content: "Hello how can I help?".to_string(),
543
                },
Nicolas Patry's avatar
Nicolas Patry committed
544
                TextMessage {
545
                    role: "user".to_string(),
Nicolas Patry's avatar
Nicolas Patry committed
546
                    content: "What is Deep Learning?".to_string(),
547
                },
Nicolas Patry's avatar
Nicolas Patry committed
548
                TextMessage {
549
                    role: "assistant".to_string(),
Nicolas Patry's avatar
Nicolas Patry committed
550
                    content: "magic!".to_string(),
551
552
553
554
                },
            ],
            bos_token: Some("[BOS]"),
            eos_token: Some("[EOS]"),
555
            add_generation_prompt: true,
556
            ..Default::default()
557
558
559
560
561
562
        };

        let result = tmpl.unwrap().render(chat_template_inputs).unwrap();

        assert_eq!(
            result,
563
            "### User:\nHi!\n\n### Assistant:\nHello how can I help?### User:\nWhat is Deep Learning?\n\n### Assistant:\nmagic!### Assistant:\n"
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
        );
    }

    #[test]
    fn test_chat_template_invalid_with_raise() {
        let mut env = Environment::new();
        env.add_function("raise_exception", raise_exception);

        let source = r#"
        {{ bos_token }}
        {% for message in messages %}
        {% if (message['role'] == 'user') != (loop.index0 % 2 == 0) %}
        {{ raise_exception('Conversation roles must alternate user/assistant/user/assistant/...') }}
        {% endif %}
        {% if message['role'] == 'user' %}
        {{ '[INST] ' + message['content'] + ' [/INST]' }}
        {% elif message['role'] == 'assistant' %}
        {{ message['content'] + eos_token}}
        {% else %}
        {{ raise_exception('Only user and assistant roles are supported!') }}
        {% endif %}
        {% endfor %}"#;

        // trim all the whitespace
        let source = source
            .lines()
            .map(|line| line.trim())
            .collect::<Vec<&str>>()
            .join("");

        let tmpl = env.template_from_str(&source);

        let chat_template_inputs = ChatTemplateInputs {
            messages: vec![
Nicolas Patry's avatar
Nicolas Patry committed
598
                TextMessage {
599
                    role: "user".to_string(),
Nicolas Patry's avatar
Nicolas Patry committed
600
                    content: "Hi!".to_string(),
601
                },
Nicolas Patry's avatar
Nicolas Patry committed
602
                TextMessage {
603
                    role: "user".to_string(),
Nicolas Patry's avatar
Nicolas Patry committed
604
                    content: "Hi again!".to_string(),
605
                },
Nicolas Patry's avatar
Nicolas Patry committed
606
                TextMessage {
607
                    role: "assistant".to_string(),
Nicolas Patry's avatar
Nicolas Patry committed
608
                    content: "Hello how can I help?".to_string(),
609
                },
Nicolas Patry's avatar
Nicolas Patry committed
610
                TextMessage {
611
                    role: "user".to_string(),
Nicolas Patry's avatar
Nicolas Patry committed
612
                    content: "What is Deep Learning?".to_string(),
613
                },
Nicolas Patry's avatar
Nicolas Patry committed
614
                TextMessage {
615
                    role: "assistant".to_string(),
Nicolas Patry's avatar
Nicolas Patry committed
616
                    content: "magic!".to_string(),
617
618
619
620
                },
            ],
            bos_token: Some("[BOS]"),
            eos_token: Some("[EOS]"),
621
            add_generation_prompt: true,
622
            ..Default::default()
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
        };

        let result = tmpl.unwrap().render(chat_template_inputs); //.err().unwrap();

        match result {
            Ok(_) => panic!("Should have failed"),
            Err(e) => {
                assert_eq!(
                    e.detail().unwrap(),
                    "Conversation roles must alternate user/assistant/user/assistant/..."
                );
            }
        }
    }

    #[test]
    fn test_chat_template_valid_with_raise() {
        let mut env = Environment::new();
        env.add_function("raise_exception", raise_exception);

        let source = r#"
        {{ bos_token }}
        {% for message in messages %}
        {% if (message['role'] == 'user') != (loop.index0 % 2 == 0) %}
        {{ raise_exception('Conversation roles must alternate user/assistant/user/assistant/...') }}
        {% endif %}
        {% if message['role'] == 'user' %}
        {{ '[INST] ' + message['content'] + ' [/INST]' }}
        {% elif message['role'] == 'assistant' %}
        {{ message['content'] + eos_token}}
        {% else %}
        {{ raise_exception('Only user and assistant roles are supported!') }}
        {% endif %}
        {% endfor %}"#;

        // trim all the whitespace
        let source = source
            .lines()
            .map(|line| line.trim())
            .collect::<Vec<&str>>()
            .join("");

        let tmpl = env.template_from_str(&source);

        let chat_template_inputs = ChatTemplateInputs {
            messages: vec![
Nicolas Patry's avatar
Nicolas Patry committed
669
                TextMessage {
670
                    role: "user".to_string(),
Nicolas Patry's avatar
Nicolas Patry committed
671
                    content: "Hi!".to_string(),
672
                },
Nicolas Patry's avatar
Nicolas Patry committed
673
                TextMessage {
674
                    role: "assistant".to_string(),
Nicolas Patry's avatar
Nicolas Patry committed
675
                    content: "Hello how can I help?".to_string(),
676
                },
Nicolas Patry's avatar
Nicolas Patry committed
677
                TextMessage {
678
                    role: "user".to_string(),
Nicolas Patry's avatar
Nicolas Patry committed
679
                    content: "What is Deep Learning?".to_string(),
680
                },
Nicolas Patry's avatar
Nicolas Patry committed
681
                TextMessage {
682
                    role: "assistant".to_string(),
Nicolas Patry's avatar
Nicolas Patry committed
683
                    content: "magic!".to_string(),
684
685
686
687
                },
            ],
            bos_token: Some("[BOS]"),
            eos_token: Some("[EOS]"),
688
            add_generation_prompt: true,
689
            ..Default::default()
690
691
692
693
694
        };

        let result = tmpl.unwrap().render(chat_template_inputs).unwrap();
        assert_eq!(result, "[BOS][INST] Hi! [/INST]Hello how can I help?[EOS][INST] What is Deep Learning? [/INST]magic![EOS]");
    }
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719

    #[test]
    fn test_chat_template_valid_with_add_generation_prompt() {
        let mut env = Environment::new();
        env.add_function("raise_exception", raise_exception);

        let source = r#"
        {% for message in messages %}
        {{'<|im_start|>' + message['role'] + '\n' + message['content'] + '<|im_end|>' + '\n'}}
        {% endfor %}
        {% if add_generation_prompt %}
            {{ '<|im_start|>assistant\n' }}
        {% endif %}"#;

        // trim all the whitespace
        let source = source
            .lines()
            .map(|line| line.trim())
            .collect::<Vec<&str>>()
            .join("");

        let tmpl = env.template_from_str(&source);

        let chat_template_inputs = ChatTemplateInputs {
            messages: vec![
Nicolas Patry's avatar
Nicolas Patry committed
720
                TextMessage {
721
                    role: "user".to_string(),
Nicolas Patry's avatar
Nicolas Patry committed
722
                    content: "Hi!".to_string(),
723
                },
Nicolas Patry's avatar
Nicolas Patry committed
724
                TextMessage {
725
                    role: "assistant".to_string(),
Nicolas Patry's avatar
Nicolas Patry committed
726
                    content: "Hello how can I help?".to_string(),
727
                },
Nicolas Patry's avatar
Nicolas Patry committed
728
                TextMessage {
729
                    role: "user".to_string(),
Nicolas Patry's avatar
Nicolas Patry committed
730
                    content: "What is Deep Learning?".to_string(),
731
                },
Nicolas Patry's avatar
Nicolas Patry committed
732
                TextMessage {
733
                    role: "assistant".to_string(),
Nicolas Patry's avatar
Nicolas Patry committed
734
                    content: "magic!".to_string(),
735
736
737
738
739
                },
            ],
            bos_token: Some("[BOS]"),
            eos_token: Some("[EOS]"),
            add_generation_prompt: true,
740
            ..Default::default()
741
742
743
744
745
        };

        let result = tmpl.unwrap().render(chat_template_inputs).unwrap();
        assert_eq!(result, "<|im_start|>user\nHi!<|im_end|>\n<|im_start|>assistant\nHello how can I help?<|im_end|>\n<|im_start|>user\nWhat is Deep Learning?<|im_end|>\n<|im_start|>assistant\nmagic!<|im_end|>\n<|im_start|>assistant\n");
    }
746
747
748
749
750
751
752
753
754
755
756

    struct ChatTemplateTestItem {
        name: &'static str,
        chat_template: &'static str,
        input: ChatTemplateInputs<'static>,
        target: &'static str,
    }

    #[test]
    fn test_many_chat_templates() {
        let example_chat = vec![
Nicolas Patry's avatar
Nicolas Patry committed
757
            TextMessage {
758
                role: "user".to_string(),
Nicolas Patry's avatar
Nicolas Patry committed
759
                content: "Hello, how are you?".to_string(),
760
            },
Nicolas Patry's avatar
Nicolas Patry committed
761
            TextMessage {
762
                role: "assistant".to_string(),
Nicolas Patry's avatar
Nicolas Patry committed
763
                content: "I'm doing great. How can I help you today?".to_string(),
764
            },
Nicolas Patry's avatar
Nicolas Patry committed
765
            TextMessage {
766
                role: "user".to_string(),
Nicolas Patry's avatar
Nicolas Patry committed
767
                content: "I'd like to show off how chat templating works!".to_string(),
768
769
770
            },
        ];

Nicolas Patry's avatar
Nicolas Patry committed
771
        let example_chat_with_system = [TextMessage {
772
            role: "system".to_string(),
Nicolas Patry's avatar
Nicolas Patry committed
773
774
            content: "You are a friendly chatbot who always responds in the style of a pirate"
                .to_string(),
775
776
777
778
779
780
781
782
783
784
        }]
        .iter()
        .chain(&example_chat)
        .cloned()
        .collect::<Vec<_>>();

        let test_default_templates = vec![
            ChatTemplateTestItem {
                name: "_base",
                chat_template: "{% for message in messages %}{{'<|im_start|>' + message['role'] + '\\n' + message['content'] + '<|im_end|>' + '\\n'}}{% endfor %}{% if add_generation_prompt %}{{ '<|im_start|>assistant\\n' }}{% endif %}",
785
                input: ChatTemplateInputs {
786
787
788
789
                    messages: example_chat.clone(),
                    add_generation_prompt: false,
                    bos_token: Some(""),
                    eos_token: Some(""),
790
                    ..Default::default()
791
792
793
794
795
796
                },
                target: "<|im_start|>user\nHello, how are you?<|im_end|>\n<|im_start|>assistant\nI'm doing great. How can I help you today?<|im_end|>\n<|im_start|>user\nI'd like to show off how chat templating works!<|im_end|>\n",
            },
            ChatTemplateTestItem {
                name: "blenderbot",
                chat_template: "{% for message in messages %}{% if message['role'] == 'user' %}{{ ' ' }}{% endif %}{{ message['content'] }}{% if not loop.last %}{{ '  ' }}{% endif %}{% endfor %}{{ eos_token }}",
797
                input: ChatTemplateInputs {
798
799
800
801
                    messages: example_chat.clone(),
                    add_generation_prompt: false,
                    bos_token: Some(""),
                    eos_token: Some("</s>"),
802
                    ..Default::default()
803
804
805
806
807
808
                },
                target: " Hello, how are you?  I'm doing great. How can I help you today?   I'd like to show off how chat templating works!</s>",
            },
            ChatTemplateTestItem {
                name: "blenderbot_small",
                chat_template: "{% for message in messages %}{% if message['role'] == 'user' %}{{ ' ' }}{% endif %}{{ message['content'] }}{% if not loop.last %}{{ '  ' }}{% endif %}{% endfor %}{{ eos_token }}",
809
                input: ChatTemplateInputs {
810
811
812
813
                    messages: example_chat.clone(),
                    add_generation_prompt: false,
                    bos_token: Some(""),
                    eos_token: Some("</s>"),
814
                    ..Default::default()
815
816
817
818
819
820
                },
                target: " Hello, how are you?  I'm doing great. How can I help you today?   I'd like to show off how chat templating works!</s>",
            },
            ChatTemplateTestItem {
                name: "bloom",
                chat_template: "{% for message in messages %}{{ message.content }}{{ eos_token }}{% endfor %}",
821
                input: ChatTemplateInputs {
822
823
824
825
                    messages: example_chat.clone(),
                    add_generation_prompt: false,
                    bos_token: Some(""),
                    eos_token: Some("</s>"),
826
                    ..Default::default()
827
828
829
830
831
832
                },
                target: "Hello, how are you?</s>I'm doing great. How can I help you today?</s>I'd like to show off how chat templating works!</s>",
            },
            ChatTemplateTestItem {
                name: "gpt_neox",
                chat_template: "{% for message in messages %}{{ message.content }}{{ eos_token }}{% endfor %}",
833
                input: ChatTemplateInputs {
834
835
836
837
                    messages: example_chat.clone(),
                    add_generation_prompt: false,
                    bos_token: Some(""),
                    eos_token: Some("<|endoftext|>"),
838
                    ..Default::default()
839
840
841
842
843
844
                },
                target: "Hello, how are you?<|endoftext|>I'm doing great. How can I help you today?<|endoftext|>I'd like to show off how chat templating works!<|endoftext|>",
            },
            ChatTemplateTestItem {
                name: "gpt2",
                chat_template: "{% for message in messages %}{{ message.content }}{{ eos_token }}{% endfor %}",
845
846
847
848
849
                input: ChatTemplateInputs {
                    messages: example_chat.clone(),
                    add_generation_prompt: false,
                    bos_token: Some(""),
                    eos_token: Some("<|endoftext|>"),
850
                    ..Default::default()
851
                },
852
                target: "Hello, how are you?<|endoftext|>I'm doing great. How can I help you today?<|endoftext|>I'd like to show off how chat templating works!<|endoftext|>",
853
854
855
856
857
            },
            ChatTemplateTestItem {
                name: "llama",
                // NOTE: the `.strip()` has been replaced with `| trim` in the following template
                chat_template: "{% if messages[0]['role'] == 'system' %}{% set loop_messages = messages[1:] %}{% set system_message = messages[0]['content'] %}{% elif USE_DEFAULT_PROMPT == true and not '<<SYS>>' in messages[0]['content'] %}{% set loop_messages = messages %}{% set system_message = 'DEFAULT_SYSTEM_MESSAGE' %}{% else %}{% set loop_messages = messages %}{% set system_message = false %}{% endif %}{% for message in loop_messages %}{% if (message['role'] == 'user') != (loop.index0 % 2 == 0) %}{{ raise_exception('Conversation roles must alternate user/assistant/user/assistant/...') }}{% endif %}{% if loop.index0 == 0 and system_message != false %}{% set content = '<<SYS>>\\n' + system_message + '\\n<</SYS>>\\n\\n' + message['content'] %}{% else %}{% set content = message['content'] %}{% endif %}{% if message['role'] == 'user' %}{{ bos_token +'[INST] ' + content | trim + ' [/INST]' }}{% elif message['role'] == 'system' %}{{ '<<SYS>>\\n' + content | trim + '\\n<</SYS>>\\n\\n' }}{% elif message['role'] == 'assistant' %}{{ ' ' + content | trim + ' ' + eos_token }}{% endif %}{% endfor %}",
858
859
860
861
862
                input: ChatTemplateInputs {
                    messages: example_chat_with_system.clone(),
                    add_generation_prompt: true,
                    bos_token: Some("<s>"),
                    eos_token: Some("</s>"),
863
                    ..Default::default()
864
                },
865
                target: "<s>[INST] <<SYS>>\nYou are a friendly chatbot who always responds in the style of a pirate\n<</SYS>>\n\nHello, how are you? [/INST] I'm doing great. How can I help you today? </s><s>[INST] I'd like to show off how chat templating works! [/INST]",
866
867
868
869
            },
            ChatTemplateTestItem {
                name: "whisper",
                chat_template: "{% for message in messages %}{{ message.content }}{{ eos_token }}{% endfor %}",
870
871
872
873
874
                input: ChatTemplateInputs {
                    messages: example_chat.clone(),
                    add_generation_prompt: true,
                    bos_token: Some(""),
                    eos_token: Some("<|endoftext|>"),
875
                    ..Default::default()
876
                },
877
878
                target: "Hello, how are you?<|endoftext|>I'm doing great. How can I help you today?<|endoftext|>I'd like to show off how chat templating works!<|endoftext|>",
            },
879
880
881
882
883
884
885
886
887
888
889
890
        ];

        #[allow(unused_variables)] // name is unused
        for ChatTemplateTestItem {
            name,
            chat_template,
            input,
            target,
        } in test_default_templates
        {
            let mut env = Environment::new();
            env.add_function("raise_exception", raise_exception);
891
            let tmpl = env.template_from_str(chat_template);
892
893
894
895
896
897
898
899
900
901
902
903
            let result = tmpl.unwrap().render(input).unwrap();
            assert_eq!(result, target);
        }

        let test_custom_templates = vec![
            ChatTemplateTestItem {
                name: "HuggingFaceH4/zephyr-7b-beta (add_generation_prompt=false)",
                chat_template: "{% for message in messages %}\n{% if message['role'] == 'user' %}\n{{ '<|user|>\\n' + message['content'] + eos_token }}\n{% elif message['role'] == 'system' %}\n{{ '<|system|>\\n' + message['content'] + eos_token }}\n{% elif message['role'] == 'assistant' %}\n{{ '<|assistant|>\\n'  + message['content'] + eos_token }}\n{% endif %}\n{% if loop.last and add_generation_prompt %}\n{{ '<|assistant|>' }}\n{% endif %}\n{% endfor %}",
                input: ChatTemplateInputs {
                    messages: example_chat_with_system.clone(),
                    add_generation_prompt: false,
                    bos_token: Some(""),
904
                    eos_token: Some("</s>"),
905
                    ..Default::default()
906
907
908
909
910
911
912
913
                },
                target: "<|system|>\nYou are a friendly chatbot who always responds in the style of a pirate</s><|user|>\nHello, how are you?</s><|assistant|>\nI'm doing great. How can I help you today?</s><|user|>\nI'd like to show off how chat templating works!</s>",
            },
            ChatTemplateTestItem {
                name: "HuggingFaceH4/zephyr-7b-beta (add_generation_prompt=true)",
                chat_template: "{% for message in messages %}\n{% if message['role'] == 'user' %}\n{{ '<|user|>\\n' + message['content'] + eos_token }}\n{% elif message['role'] == 'system' %}\n{{ '<|system|>\\n' + message['content'] + eos_token }}\n{% elif message['role'] == 'assistant' %}\n{{ '<|assistant|>\\n'  + message['content'] + eos_token }}\n{% endif %}\n{% if loop.last and add_generation_prompt %}\n{{ '<|assistant|>' }}\n{% endif %}\n{% endfor %}",
                input: ChatTemplateInputs {
                    messages: vec![
OlivierDehaene's avatar
OlivierDehaene committed
914
                        TextMessage {
915
                            role: "system".to_string(),
Nicolas Patry's avatar
Nicolas Patry committed
916
                            content: "You are a friendly chatbot who always responds in the style of a pirate".to_string(),
917
                        },
OlivierDehaene's avatar
OlivierDehaene committed
918
                        TextMessage {
919
                            role: "user".to_string(),
Nicolas Patry's avatar
Nicolas Patry committed
920
                            content: "How many helicopters can a human eat in one sitting?".to_string(),
921
922
923
924
925
                        },
                    ],
                    add_generation_prompt: true,
                    bos_token: Some(""),
                    eos_token: Some("</s>"),
926
                    ..Default::default()
927
                },
928
                target: "<|system|>\nYou are a friendly chatbot who always responds in the style of a pirate</s><|user|>\nHow many helicopters can a human eat in one sitting?</s><|assistant|>",
929
930
931
932
933
934
935
936
937
            },
            ChatTemplateTestItem {
                name: "HuggingFaceH4/zephyr-7b-gemma-v0.1",
                chat_template: "{% if messages[0]['role'] == 'user' or messages[0]['role'] == 'system' %}{{ bos_token }}{% endif %}{% for message in messages %}{{ '<|im_start|>' + message['role'] + '\\n' + message['content'] + '<|im_end|>' + '\\n' }}{% endfor %}{% if add_generation_prompt %}{{ '<|im_start|>assistant\n' }}{% elif messages[-1]['role'] == 'assistant' %}{{ eos_token }}{% endif %}",
                input: ChatTemplateInputs {
                    messages: example_chat.clone(),
                    add_generation_prompt: false,
                    bos_token: Some("<bos>"),
                    eos_token: Some("<eos>"),
938
                    ..Default::default()
939
940
941
942
943
944
945
946
947
948
949
                },
                target: "<bos><|im_start|>user\nHello, how are you?<|im_end|>\n<|im_start|>assistant\nI'm doing great. How can I help you today?<|im_end|>\n<|im_start|>user\nI'd like to show off how chat templating works!<|im_end|>\n",
            },
            ChatTemplateTestItem {
                name: "mistralai/Mistral-7B-Instruct-v0.1",
                chat_template: "{{ bos_token }}{% for message in messages %}{% if (message['role'] == 'user') != (loop.index0 % 2 == 0) %}{{ raise_exception('Conversation roles must alternate user/assistant/user/assistant/...') }}{% endif %}{% if message['role'] == 'user' %}{{ '[INST] ' + message['content'] + ' [/INST]' }}{% elif message['role'] == 'assistant' %}{{ message['content'] + eos_token + ' ' }}{% else %}{{ raise_exception('Only user and assistant roles are supported!') }}{% endif %}{% endfor %}",
                input: ChatTemplateInputs {
                    messages: example_chat.clone(),
                    add_generation_prompt: false,
                    bos_token: Some("<s>"),
                    eos_token: Some("</s>"),
950
                    ..Default::default()
951
                },
952
                target: "<s>[INST] Hello, how are you? [/INST]I'm doing great. How can I help you today?</s> [INST] I'd like to show off how chat templating works! [/INST]",
953
954
955
956
957
958
959
960
961
            },
            ChatTemplateTestItem {
                name: "mistralai/Mixtral-8x7B-Instruct-v0.1",
                chat_template: "{{ bos_token }}{% for message in messages %}{% if (message['role'] == 'user') != (loop.index0 % 2 == 0) %}{{ raise_exception('Conversation roles must alternate user/assistant/user/assistant/...') }}{% endif %}{% if message['role'] == 'user' %}{{ '[INST] ' + message['content'] + ' [/INST]' }}{% elif message['role'] == 'assistant' %}{{ message['content'] + eos_token}}{% else %}{{ raise_exception('Only user and assistant roles are supported!') }}{% endif %}{% endfor %}",
                input: ChatTemplateInputs {
                    messages: example_chat.clone(),
                    add_generation_prompt: false,
                    bos_token: Some("<s>"),
                    eos_token: Some("</s>"),
962
                    ..Default::default()
963
964
965
966
967
968
969
                },
                target: "<s>[INST] Hello, how are you? [/INST]I'm doing great. How can I help you today?</s>[INST] I'd like to show off how chat templating works! [/INST]",
            },
            ChatTemplateTestItem {
                name: "cognitivecomputations/dolphin-2.5-mixtral-8x7b",
                chat_template: "{% if not add_generation_prompt is defined %}{% set add_generation_prompt = false %}{% endif %}{% for message in messages %}{{'<|im_start|>' + message['role'] + '\\n' + message['content'] + '<|im_end|>' + '\\n'}}{% endfor %}{% if add_generation_prompt %}{{ '<|im_start|>assistant\\n' }}{% endif %}",
                input: ChatTemplateInputs {
970
                    messages: example_chat.clone(),
971
972
973
                    add_generation_prompt: false,
                    bos_token: Some("<s>"),
                    eos_token: Some("</s>"),
974
                    ..Default::default()
975
976
977
978
979
980
981
982
983
984
985
986
                },
                target: "<|im_start|>user\nHello, how are you?<|im_end|>\n<|im_start|>assistant\nI'm doing great. How can I help you today?<|im_end|>\n<|im_start|>user\nI'd like to show off how chat templating works!<|im_end|>\n",
            },
            ChatTemplateTestItem {
                name: "openchat/openchat-3.5-0106",
                // `.title()` has been replaced with `| upper` in the following template
                chat_template: "{{ bos_token }}{% for message in messages %}{{ 'GPT4 Correct ' + (message['role'] | title) + ': ' + message['content'] + '<|end_of_turn|>'}}{% endfor %}{% if add_generation_prompt %}{{ 'GPT4 Correct Assistant:' }}{% endif %}",
                input: ChatTemplateInputs {
                    messages: example_chat.clone(),
                    add_generation_prompt: false,
                    bos_token: Some("<s>"),
                    eos_token: Some("</s>"),
987
                    ..Default::default()
988
989
990
991
992
993
994
995
996
997
998
                },
                target: "<s>GPT4 Correct User: Hello, how are you?<|end_of_turn|>GPT4 Correct Assistant: I'm doing great. How can I help you today?<|end_of_turn|>GPT4 Correct User: I'd like to show off how chat templating works!<|end_of_turn|>",
            },
            ChatTemplateTestItem {
                name: "upstage/SOLAR-10.7B-Instruct-v1.0",
                chat_template: "{% for message in messages %}{{ message.content }}{{ eos_token }}{% endfor %}",
                input: ChatTemplateInputs {
                    messages: example_chat.clone(),
                    add_generation_prompt: false,
                    bos_token: Some("<s>"),
                    eos_token: Some("</s>"),
999
                    ..Default::default()
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
                },
                target: "Hello, how are you?</s>I'm doing great. How can I help you today?</s>I'd like to show off how chat templating works!</s>",
            },
            ChatTemplateTestItem {
                name: "codellama/CodeLlama-70b-Instruct-hf",
                // NOTE: `.strip()` has been replaced with `| trim` in the following template
                chat_template: "{% if messages[0]['role'] == 'system' %}{% set user_index = 1 %}{% else %}{% set user_index = 0 %}{% endif %}{% for message in messages %}{% if (message['role'] == 'user') != ((loop.index0 + user_index) % 2 == 0) %}{{ raise_exception('Conversation roles must alternate user/assistant/user/assistant/...') }}{% endif %}{% if loop.index0 == 0 %}{{ '<s>' }}{% endif %}{% set content = 'Source: ' + message['role'] + '\\n\\n ' + message['content'] | trim %}{{ content + ' <step> ' }}{% endfor %}{{'Source: assistant\\nDestination: user\\n\\n '}}",
                input: ChatTemplateInputs {
                    messages: example_chat.clone(),
                    add_generation_prompt: false,
                    bos_token: Some("<s>"),
                    eos_token: Some("</s>"),
1012
                    ..Default::default()
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
                },
                target: "<s>Source: user\n\n Hello, how are you? <step> Source: assistant\n\n I'm doing great. How can I help you today? <step> Source: user\n\n I'd like to show off how chat templating works! <step> Source: assistant\nDestination: user\n\n ",
            },
            ChatTemplateTestItem {
                name: "Deci/DeciLM-7B-instruct",
                chat_template: "{% for message in messages %}\n{% if message['role'] == 'user' %}\n{{ '### User:\\n' + message['content'] }}\n{% elif message['role'] == 'system' %}\n{{ '### System:\\n' + message['content'] }}\n{% elif message['role'] == 'assistant' %}\n{{ '### Assistant:\\n'  + message['content'] }}\n{% endif %}\n{% if loop.last and add_generation_prompt %}\n{{ '### Assistant:' }}\n{% endif %}\n{% endfor %}",
                input: ChatTemplateInputs {
                    messages: example_chat.clone(),
                    add_generation_prompt: false,
                    bos_token: Some("<s>"),
                    eos_token: Some("</s>"),
1024
                    ..Default::default()
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
                },
                target: "### User:\nHello, how are you?### Assistant:\nI'm doing great. How can I help you today?### User:\nI'd like to show off how chat templating works!",
            },
            ChatTemplateTestItem {
                name: "Qwen/Qwen1.5-72B-Chat",
                chat_template: "{% for message in messages %}{% if loop.first and messages[0]['role'] != 'system' %}{{ '<|im_start|>system\\nYou are a helpful assistant<|im_end|>\\n' }}{% endif %}{{'<|im_start|>' + message['role'] + '\\n' + message['content']}}{% if (loop.last and add_generation_prompt) or not loop.last %}{{ '<|im_end|>' + '\\n'}}{% endif %}{% endfor %}{% if add_generation_prompt and messages[-1]['role'] != 'assistant' %}{{ '<|im_start|>assistant\\n' }}{% endif %}",
                input: ChatTemplateInputs {
                    messages: example_chat.clone(),
                    add_generation_prompt: false,
                    bos_token: Some("<s>"),
                    eos_token: Some("</s>"),
1036
                    ..Default::default()
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
                },
                target: "<|im_start|>system\nYou are a helpful assistant<|im_end|>\n<|im_start|>user\nHello, how are you?<|im_end|>\n<|im_start|>assistant\nI'm doing great. How can I help you today?<|im_end|>\n<|im_start|>user\nI'd like to show off how chat templating works!",
            },
            ChatTemplateTestItem {
                name: "deepseek-ai/deepseek-llm-7b-chat",
                chat_template: "{% if not add_generation_prompt is defined %}{% set add_generation_prompt = false %}{% endif %}{{ bos_token }}{% for message in messages %}{% if message['role'] == 'user' %}{{ 'User: ' + message['content'] + '\\n\\n' }}{% elif message['role'] == 'assistant' %}{{ 'Assistant: ' + message['content'] + eos_token }}{% elif message['role'] == 'system' %}{{ message['content'] + '\\n\\n' }}{% endif %}{% endfor %}{% if add_generation_prompt %}{{ 'Assistant:' }}{% endif %}",
                input: ChatTemplateInputs {
                    messages: example_chat.clone(),
                    add_generation_prompt: false,
                    bos_token: Some("<|begin▁of▁sentence|>"),
                    eos_token: Some("<|end▁of▁sentence|>"),
1048
                    ..Default::default()
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
                },
                target: "<|begin▁of▁sentence|>User: Hello, how are you?\n\nAssistant: I'm doing great. How can I help you today?<|end▁of▁sentence|>User: I'd like to show off how chat templating works!\n\n",
            },
            ChatTemplateTestItem {
                name: "h2oai/h2o-danube-1.8b-chat",
                chat_template: "{% for message in messages %}{% if message['role'] == 'user' %}{{ '<|prompt|>' + message['content'] + eos_token }}{% elif message['role'] == 'system' %}{{ '<|system|>' + message['content'] + eos_token }}{% elif message['role'] == 'assistant' %}{{ '<|answer|>'  + message['content'] + eos_token }}{% endif %}{% if loop.last and add_generation_prompt %}{{ '<|answer|>' }}{% endif %}{% endfor %}",
                input: ChatTemplateInputs {
                    messages: example_chat.clone(),
                    add_generation_prompt: false,
                    bos_token: Some("<s>"),
                    eos_token: Some("</s>"),
1060
                    ..Default::default()
1061
                },
1062
                target: "<|prompt|>Hello, how are you?</s><|answer|>I'm doing great. How can I help you today?</s><|prompt|>I'd like to show off how chat templating works!</s>",
1063
1064
1065
1066
1067
1068
1069
1070
1071
            },
            ChatTemplateTestItem {
                name: "internlm/internlm2-chat-7b",
                chat_template: "{% if messages[0]['role'] == 'user' or messages[0]['role'] == 'system' %}{{ bos_token }}{% endif %}{% for message in messages %}{{ '<|im_start|>' + message['role'] + '\\n' + message['content'] + '<|im_end|>' + '\\n' }}{% endfor %}{% if add_generation_prompt %}{{ '<|im_start|>assistant\\n' }}{% elif messages[-1]['role'] == 'assistant' %}{{ eos_token }}{% endif %}",
                input: ChatTemplateInputs {
                    messages: example_chat.clone(),
                    add_generation_prompt: false,
                    bos_token: Some("<s>"),
                    eos_token: Some("</s>"),
1072
                    ..Default::default()
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
                },
                target: "<s><|im_start|>user\nHello, how are you?<|im_end|>\n<|im_start|>assistant\nI'm doing great. How can I help you today?<|im_end|>\n<|im_start|>user\nI'd like to show off how chat templating works!<|im_end|>\n",
            },
            ChatTemplateTestItem {
                name: "TheBloke/deepseek-coder-33B-instruct-AWQ",
                chat_template: "{%- set found_item = false -%}\n{%- for message in messages -%}\n    {%- if message['role'] == 'system' -%}\n        {%- set found_item = true -%}\n    {%- endif -%}\n{%- endfor -%}\n{%- if not found_item -%}\n{{'You are an AI programming assistant, utilizing the Deepseek Coder model, developed by Deepseek Company, and you only answer questions related to computer science. For politically sensitive questions, security and privacy issues, and other non-computer science questions, you will refuse to answer.\\n'}}\n{%- endif %}\n{%- for message in messages %}\n    {%- if message['role'] == 'system' %}\n{{ message['content'] }}\n    {%- else %}\n        {%- if message['role'] == 'user' %}\n{{'### Instruction:\\n' + message['content'] + '\\n'}}\n        {%- else %}\n{{'### Response:\\n' + message['content'] + '\\n<|EOT|>\\n'}}\n        {%- endif %}\n    {%- endif %}\n{%- endfor %}\n{{'### Response:\\n'}}\n",
                input: ChatTemplateInputs {
                    messages: example_chat.clone(),
                    add_generation_prompt: false,
                    bos_token: Some("<|begin▁of▁sentence|>"),
                    eos_token: Some("<|EOT|>"),
1084
                    ..Default::default()
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
                },
                target: "You are an AI programming assistant, utilizing the Deepseek Coder model, developed by Deepseek Company, and you only answer questions related to computer science. For politically sensitive questions, security and privacy issues, and other non-computer science questions, you will refuse to answer.\n### Instruction:\nHello, how are you?\n### Response:\nI'm doing great. How can I help you today?\n<|EOT|>\n### Instruction:\nI'd like to show off how chat templating works!\n### Response:\n",
            },
            ChatTemplateTestItem {
                name: "ericzzz/falcon-rw-1b-chat",
                // `.strip()` has been replaced with `| trim` in the following template
                chat_template: "{% for message in messages %}{% if loop.index > 1 and loop.previtem['role'] != 'assistant' %}{{ ' ' }}{% endif %}{% if message['role'] == 'system' %}{{ '[SYS] ' + message['content'] | trim }}{% elif message['role'] == 'user' %}{{ '[INST] ' + message['content'] | trim }}{% elif message['role'] == 'assistant' %}{{ '[RESP] '  + message['content'] + eos_token }}{% endif %}{% endfor %}{% if add_generation_prompt %}{{ ' [RESP] ' }}{% endif %}",
                input: ChatTemplateInputs {
                    messages: example_chat.clone(),
                    add_generation_prompt: false,
                    bos_token: Some("<|endoftext|>"),
                    eos_token: Some("<|endoftext|>"),
1097
                    ..Default::default()
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
                },
                target: "[INST] Hello, how are you? [RESP] I'm doing great. How can I help you today?<|endoftext|>[INST] I'd like to show off how chat templating works!",
            },
            ChatTemplateTestItem {
                name: "abacusai/Smaug-34B-v0.1",
                chat_template: "{%- for idx in range(0, messages|length) -%}\n{%- if messages[idx]['role'] == 'user' -%}\n{%- if idx > 1 -%}\n{{- bos_token + '[INST] ' + messages[idx]['content'] + ' [/INST]' -}}\n{%- else -%}\n{{- messages[idx]['content'] + ' [/INST]' -}}\n{%- endif -%}\n{% elif messages[idx]['role'] == 'system' %}\n{{- '[INST] <<SYS>>\\n' + messages[idx]['content'] + '\\n<</SYS>>\\n\\n' -}}\n{%- elif messages[idx]['role'] == 'assistant' -%}\n{{- ' '  + messages[idx]['content'] + ' ' + eos_token -}}\n{% endif %}\n{% endfor %}",
                input: ChatTemplateInputs {
                    messages: example_chat.clone(),
                    add_generation_prompt: false,
                    bos_token: Some("<s>"),
                    eos_token: Some("</s>"),
1109
                    ..Default::default()
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
                },
                target: "Hello, how are you? [/INST] I'm doing great. How can I help you today? </s><s>[INST] I'd like to show off how chat templating works! [/INST]",
            },
            ChatTemplateTestItem {
                name: "maywell/Synatra-Mixtral-8x7B",
                chat_template: "Below is an instruction that describes a task. Write a response that appropriately completes the request.\n\n{% for message in messages %}{% if message['role'] == 'user' %}### Instruction:\n{{ message['content']|trim -}}{% if not loop.last %}{% endif %}\n{% elif message['role'] == 'assistant' %}### Response:\n{{ message['content']|trim -}}{% if not loop.last %}{% endif %}\n{% elif message['role'] == 'system' %}{{ message['content']|trim -}}{% if not loop.last %}{% endif %}\n{% endif %}\n{% endfor %}\n{% if add_generation_prompt and messages[-1]['role'] != 'assistant' %}\n### Response:\n{% endif %}",
                input: ChatTemplateInputs {
                    messages: example_chat.clone(),
                    add_generation_prompt: false,
                    bos_token: Some("<s>"),
                    eos_token: Some("</s>"),
1121
                    ..Default::default()
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
                },
                target: "Below is an instruction that describes a task. Write a response that appropriately completes the request.### Instruction:Hello, how are you?### Response:I'm doing great. How can I help you today?### Instruction:I'd like to show off how chat templating works!",
            },
            ChatTemplateTestItem {
                name: "deepseek-ai/deepseek-coder-33b-instruct",
                chat_template: "{% if not add_generation_prompt is defined %}\n{% set add_generation_prompt = false %}\n{% endif %}\n{%- set ns = namespace(found=false) -%}\n{%- for message in messages -%}\n    {%- if message['role'] == 'system' -%}\n        {%- set ns.found = true -%}\n    {%- endif -%}\n{%- endfor -%}\n{{bos_token}}{%- if not ns.found -%}\n{{'You are an AI programming assistant, utilizing the Deepseek Coder model, developed by Deepseek Company, and you only answer questions related to computer science. For politically sensitive questions, security and privacy issues, and other non-computer science questions, you will refuse to answer\\n'}}\n{%- endif %}\n{%- for message in messages %}\n    {%- if message['role'] == 'system' %}\n{{ message['content'] }}\n    {%- else %}\n        {%- if message['role'] == 'user' %}\n{{'### Instruction:\\n' + message['content'] + '\\n'}}\n        {%- else %}\n{{'### Response:\\n' + message['content'] + '\\n<|EOT|>\\n'}}\n        {%- endif %}\n    {%- endif %}\n{%- endfor %}\n{% if add_generation_prompt %}\n{{'### Response:'}}\n{% endif %}",
                input: ChatTemplateInputs {
                    messages: example_chat.clone(),
                    add_generation_prompt: false,
                    bos_token: Some("<|begin▁of▁sentence|>"),
                    eos_token: Some("</EOT>"),
1133
                    ..Default::default()
1134
1135
1136
1137
                },
                target: "<|begin▁of▁sentence|>You are an AI programming assistant, utilizing the Deepseek Coder model, developed by Deepseek Company, and you only answer questions related to computer science. For politically sensitive questions, security and privacy issues, and other non-computer science questions, you will refuse to answer\n### Instruction:\nHello, how are you?\n### Response:\nI'm doing great. How can I help you today?\n<|EOT|>\n### Instruction:\nI'd like to show off how chat templating works!\n",
            },
            // NOT INCLUDED
OlivierDehaene's avatar
OlivierDehaene committed
1138
            // - meetkai/functionary-medium-v3.2
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
            // - fireworks-ai/firefunction-v1
            // https://github
            ChatTemplateTestItem {
                name: "maywell/PiVoT-MoE",
                chat_template: "{{ (messages|selectattr('role', 'equalto', 'system')|list|last).content|trim if (messages|selectattr('role', 'equalto', 'system')|list) else '' }}{% for message in messages %}{% if message['role'] == 'system' %}{{ message['content']|trim }}{% elif message['role'] == 'user' %}### Instruction: {{ message['content']|trim }}{% elif message['role'] == 'assistant' %}### Response: {{ message['content']|trim }}{% elif message['role'] == 'user_context' %}### Input: {{ message['content']|trim }}{% endif %}{% if not loop.last %}\n{% endif %}{% endfor %}{% if add_generation_prompt and messages[-1]['role'] != 'assistant' %}### Response:{% endif %}",
                input: ChatTemplateInputs {
                    messages: example_chat_with_system.clone(),
                    add_generation_prompt: false,
                    bos_token: Some("<s>"),
                    eos_token: Some("</s>"),
1149
                    ..Default::default()
1150
1151
                },
                target: "You are a friendly chatbot who always responds in the style of a pirateYou are a friendly chatbot who always responds in the style of a pirate### Instruction: Hello, how are you?### Response: I'm doing great. How can I help you today?### Instruction: I'd like to show off how chat templating works!",
1152
            },
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
        ];

        #[allow(unused_variables)] // name is unused
        for ChatTemplateTestItem {
            name,
            chat_template,
            input,
            target,
        } in test_custom_templates
        {
            let mut env = Environment::new();
            env.add_function("raise_exception", raise_exception);
            // trim all the whitespace
            let chat_template = chat_template
                .lines()
                .map(|line| line.trim())
                .collect::<Vec<&str>>()
                .join("");

            let tmpl = env.template_from_str(&chat_template);
            let result = tmpl.unwrap().render(input).unwrap();
            assert_eq!(result, target);
        }
    }
1177
}