".github/vscode:/vscode.git/clone" did not exist on "07256f04b105081eda7749cff952efb03923d4d7"
backend.rs 26.7 KB
Newer Older
1
// SPDX-FileCopyrightText: Copyright (c) 2024-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
Biswa Panda's avatar
Biswa Panda committed
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// SPDX-License-Identifier: Apache-2.0

//! Backend
//!
//! An [`Backend`] is the final stage of the pipeline. It represents the execution of the LLM
//! on some processing hardware.
//!
//! At minimum, the Backend is split into two components, the [`Backend`] itself and a downstream [`ExecutionContext`].
//!
//! The [`ExecutionContext`] can be thought of as the core driver of the forward pass, whereas the [`Backend`] is the
//! manager of all resources and concurrent tasks surrounding the LLM execution context / forward pass.
//!
//! For almost every known scenario, detokenization and initial post processing must happen in the Backend.
//! Further post-processing can happen in the response stream. One example is the jailing mechanism for partial
//! hidden stop condition matches, which can be handled in the response stream rather than the backend.

18
use std::{collections::HashSet, sync::Arc, time::Instant};
Biswa Panda's avatar
Biswa Panda committed
19

20
use anyhow::Result;
Biswa Panda's avatar
Biswa Panda committed
21
22
use futures::stream::{self, StreamExt};

23
use crate::model_card::ModelDeploymentCard;
24
use dynamo_runtime::dynamo_nvtx_range;
Neelay Shah's avatar
Neelay Shah committed
25
use dynamo_runtime::{
Biswa Panda's avatar
Biswa Panda committed
26
    pipeline::{
27
28
        AsyncEngineContextProvider, ManyOut, Operator, ResponseStream, ServerStreamingEngine,
        SingleIn, async_trait,
Biswa Panda's avatar
Biswa Panda committed
29
30
31
32
33
    },
    protocols::annotated::Annotated,
};

use crate::protocols::{
34
    TokenIdType,
Biswa Panda's avatar
Biswa Panda committed
35
    common::{
36
        StopConditions,
37
38
39
40
41
        llm_backend::{
            BackendOutput, EmbeddingsEngineOutput, FinishReason, LLMEngineOutput,
            PreprocessedRequest,
        },
        preprocessor::PreprocessedEmbeddingRequest,
42
        timing::RequestTracker,
Biswa Panda's avatar
Biswa Panda committed
43
44
    },
};
Nikita's avatar
Nikita committed
45
use crate::tokenizers::{DecodeStream, Tokenizer};
46
use dynamo_async_openai::types::StopReason;
Biswa Panda's avatar
Biswa Panda committed
47
48
49
50
51

/// Represents the output stream from the execution engine
pub type ExecutionOutputStream = Annotated<LLMEngineOutput>;

/// Context for executing LLM inference, engine consumes backend input and produces execution output stream
52
pub type ExecutionContext = ServerStreamingEngine<PreprocessedRequest, ExecutionOutputStream>;
Biswa Panda's avatar
Biswa Panda committed
53
54
55
56

/// Backend handles resource management and orchestrates LLM execution
#[allow(dead_code)]
pub struct Backend {
57
58
    pub tokenizer: Option<Tokenizer>, // Handles token encoding/decoding
    validate_engine_decode: bool,     // Enable validation of engine decoding
Biswa Panda's avatar
Biswa Panda committed
59
60
61
62
63
64
65
66
}

/// Internal state for managing token decoding and stream processing
#[allow(dead_code)]
struct DecoderUnfoldState {
    stream: ManyOut<ExecutionOutputStream>,
    decoder: Decoder,
    validate_engine_decode: bool,
67
68
    /// Set to true when a local stop condition is detected, causing the stream to end
    finished: bool,
Biswa Panda's avatar
Biswa Panda committed
69
70
71
}

impl Backend {
Nikita's avatar
Nikita committed
72
    pub fn from_tokenizer(tokenizer: Tokenizer) -> Arc<Self> {
73
        Arc::new(Self {
74
            tokenizer: Some(tokenizer),
Biswa Panda's avatar
Biswa Panda committed
75
            validate_engine_decode: false,
76
        })
Biswa Panda's avatar
Biswa Panda committed
77
78
    }

79
    pub fn from_mdc(mdc: &ModelDeploymentCard) -> Arc<Self> {
Nikita's avatar
Nikita committed
80
        match mdc.tokenizer() {
81
82
            Ok(tokenizer) => Self::from_tokenizer(tokenizer),
            Err(err) => {
Nikita's avatar
Nikita committed
83
                tracing::warn!(%err, "error loading tokenizer from ModelDeploymentCard");
84
                Arc::new(Self {
85
86
                    tokenizer: None,
                    validate_engine_decode: false,
87
                })
88
            }
89
        }
90
91
    }

Biswa Panda's avatar
Biswa Panda committed
92
93
94
    fn decoder(
        &self,
        stream: ManyOut<ExecutionOutputStream>,
95
        prompt_token_ids: &[TokenIdType],
Biswa Panda's avatar
Biswa Panda committed
96
        stop_conditions: StopConditions,
97
        skip_special_tokens: bool,
98
        include_stop_str_in_output: bool,
99
        tracker: Option<Arc<RequestTracker>>,
100
101
102
103
    ) -> anyhow::Result<DecoderUnfoldState> {
        let Some(tokenizer) = self.tokenizer.as_ref() else {
            anyhow::bail!("Backend built from blank ModelDeploymentCard, no tokenizer");
        };
104
        let decoder = Decoder::new(
105
            tokenizer.decode_stream(prompt_token_ids, skip_special_tokens),
106
            stop_conditions,
107
            include_stop_str_in_output,
108
            tracker,
109
        );
Biswa Panda's avatar
Biswa Panda committed
110

111
        Ok(DecoderUnfoldState {
Biswa Panda's avatar
Biswa Panda committed
112
113
114
            stream,
            decoder,
            validate_engine_decode: self.validate_engine_decode,
115
            finished: false,
116
        })
Biswa Panda's avatar
Biswa Panda committed
117
118
119
120
121
122
    }
}

#[async_trait]
impl
    Operator<
123
        SingleIn<PreprocessedRequest>,
Biswa Panda's avatar
Biswa Panda committed
124
        ManyOut<Annotated<BackendOutput>>,
125
        SingleIn<PreprocessedRequest>,
Biswa Panda's avatar
Biswa Panda committed
126
127
128
129
130
        ManyOut<Annotated<LLMEngineOutput>>,
    > for Backend
{
    async fn generate(
        &self,
131
132
        request: SingleIn<PreprocessedRequest>,
        next: ServerStreamingEngine<PreprocessedRequest, Annotated<LLMEngineOutput>>,
Biswa Panda's avatar
Biswa Panda committed
133
    ) -> Result<ManyOut<Annotated<BackendOutput>>> {
134
        let stop_conditions = request.stop_conditions.clone();
135
136
137

        let prompt_token_ids = request.token_ids.clone();

138
139
140
        // TODO: Consider updating default to true to match behavior of other frameworks
        let skip_special_tokens = request.output_options.skip_special_tokens.unwrap_or(false);

141
142
143
144
145
        // Extract include_stop_str_in_output from sampling_options (defaults to false)
        let include_stop_str_in_output = request
            .sampling_options
            .include_stop_str_in_output
            .unwrap_or(false);
146
        let tracker = request.tracker.clone();
147

Biswa Panda's avatar
Biswa Panda committed
148
149
150
        let next_stream = next.generate(request).await?;

        let context = next_stream.context();
151
152
153
154
155
        let state = self.decoder(
            next_stream,
            &prompt_token_ids,
            stop_conditions,
            skip_special_tokens,
156
            include_stop_str_in_output,
157
            tracker,
158
        )?;
Biswa Panda's avatar
Biswa Panda committed
159
160

        let processed_stream = stream::unfold(state, |mut state| async move {
161
162
163
164
165
            // If we've already detected a local stop condition, end the stream
            if state.finished {
                return None;
            }

Biswa Panda's avatar
Biswa Panda committed
166
167
168
169
170
171
172
173
174
175
176
            match state.stream.next().await {
                Some(output) => {
                    // move to state.process_output
                    // handle any error conditions / unwraps here

                    // events are pass thru
                    if output.is_event() || output.data.is_none() {
                        return Some((output, state));
                    }

                    // if we have a data field without an event, then we might need to update the data
177
178
179
180
181
                    if let Some(data) = &output.data
                        && data.text.is_some()
                        && !state.validate_engine_decode
                    {
                        return Some((output, state));
Biswa Panda's avatar
Biswa Panda committed
182
183
184
185
                    }

                    let data = output.data.as_ref().unwrap();

186
187
188
189
190
191
192
193
194
195
196
197
198
199
                    let result = match state.decoder.process_token_ids(&data.token_ids) {
                        Ok(result) => result,
                        Err(e) => {
                            tracing::error!("Failed to process token_ids: {e}");
                            state.stream.context().stop_generating();
                            state.finished = true;
                            let mut output = output;
                            if let Some(data) = &mut output.data {
                                data.finish_reason =
                                    Some(FinishReason::Error(format!("decode error: {e}")));
                            }
                            return Some((output, state));
                        }
                    };
Biswa Panda's avatar
Biswa Panda committed
200

201
202
203
                    // NOTE: the `finish_reason` is computed from the generated `token_ids` alone.
                    // The `data` field can have a `finish_reason` set, coming from the underlying
                    // LLM inference `Engine`, and empty `token_ids`. See comment below for more details.
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
                    //
                    // stop_reason is only set for user-provided stop sequences, not for system
                    // EOS tokens (HiddenStopTokenDetected). This matches OpenAI API behavior where
                    // stop_reason is only present when a user-specified stop sequence is matched.
                    let (finish_reason, stop_reason) = match &result.stop_trigger {
                        Some(StopTrigger::MaxTokensLimit) => (Some(FinishReason::Length), None),
                        Some(StopTrigger::HiddenStopTokenDetected(_)) => {
                            // System EOS token - no stop_reason (user didn't request this stop)
                            (Some(FinishReason::Stop), None)
                        }
                        Some(StopTrigger::HiddenStopSequenceDetected(seq)) => {
                            // User-provided stop sequence (hidden from output)
                            (
                                Some(FinishReason::Stop),
                                Some(StopReason::String(seq.clone())),
                            )
Biswa Panda's avatar
Biswa Panda committed
220
                        }
221
222
223
224
225
226
227
228
                        Some(StopTrigger::VisibleStopSequenceDetected(seq)) => {
                            // User-provided stop sequence (included in output)
                            (
                                Some(FinishReason::Stop),
                                Some(StopReason::String(seq.clone())),
                            )
                        }
                        None => (None, None),
Biswa Panda's avatar
Biswa Panda committed
229
230
                    };

231
232
233
                    // If we detected a local stop condition, mark stream as finished
                    // so we stop iterating (upstream may keep generating, but we ignore it)
                    if finish_reason.is_some() && data.finish_reason.is_none() {
Biswa Panda's avatar
Biswa Panda committed
234
                        state.stream.context().stop_generating();
235
                        state.finished = true;
Biswa Panda's avatar
Biswa Panda committed
236
237
238
239
240
241
242
                    }

                    let text = result.text;
                    let tokens = result.tokens;

                    if state.validate_engine_decode {
                        if data.finish_reason != finish_reason {
243
                            tracing::warn!(
Biswa Panda's avatar
Biswa Panda committed
244
245
246
247
248
249
250
                                "finish reason mismatch: expected {:?}, got {:?}",
                                data.finish_reason,
                                finish_reason
                            );
                        }

                        if data.text.is_some() && data.text != text {
251
252
253
254
255
                            tracing::warn!(
                                "text mismatch: expected {:?}, got {:?}",
                                data.text,
                                text
                            );
Biswa Panda's avatar
Biswa Panda committed
256
257
258
259
260
261
262
                        }
                    }

                    // update output in-place
                    let mut output = output;
                    let mut data = output.data.take().unwrap();

263
264
265
266
267
268
269
270
                    // NOTE: If `finish_reason.is_some()`, then one of the stop conditions was triggered
                    // by the token generation. We should update the `data.finish_reason` in that case.
                    // However, if `finish_reason.is_none()`, it is possible that we are in the case where
                    // `data.token_ids` is empty, and `data.finish_reason` is already correctly set.
                    // In that case, `process_token_ids` above will rewrite `finish_reason` to `None`,
                    // which we don't want to propagate to `data.finish_reason`.
                    if finish_reason.is_some() {
                        data.finish_reason = finish_reason;
271
                        data.stop_reason = stop_reason;
272
                    }
Biswa Panda's avatar
Biswa Panda committed
273
274
275
276
277
278
279
280
281
282
                    data.text = text;
                    data.tokens = Some(tokens);

                    output.data = Some(data);

                    Some((output, state))
                }

                None => None,
            }
283
284
        })
        .fuse();
Biswa Panda's avatar
Biswa Panda committed
285
286

        // convert stream of processed Annotated<LLMEngineOutput> to Annotated<BackendOutput>
287
        //let mdcsum = self.mdcsum.clone();
Biswa Panda's avatar
Biswa Panda committed
288
289
290
291
292
293
294
295
        let stream = processed_stream.map(move |output| {
            output.map_data(|data| {
                Ok(BackendOutput {
                    token_ids: data.token_ids,
                    tokens: data.tokens.unwrap_or_default(),
                    text: data.text,
                    cum_log_probs: data.cum_log_probs,
                    log_probs: data.log_probs,
Greg Clark's avatar
Greg Clark committed
296
                    top_logprobs: data.top_logprobs,
Biswa Panda's avatar
Biswa Panda committed
297
                    finish_reason: data.finish_reason,
298
                    stop_reason: data.stop_reason,
299
                    //mdcsum: mdcsum.clone(),
300
                    index: data.index,
301
                    completion_usage: data.completion_usage,
302
                    disaggregated_params: data.disaggregated_params,
Biswa Panda's avatar
Biswa Panda committed
303
304
305
306
307
308
309
310
                })
            })
        });

        Ok(ResponseStream::new(Box::pin(stream), context))
    }
}

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
#[async_trait]
impl
    Operator<
        SingleIn<PreprocessedEmbeddingRequest>,
        ManyOut<Annotated<EmbeddingsEngineOutput>>,
        SingleIn<PreprocessedEmbeddingRequest>,
        ManyOut<Annotated<EmbeddingsEngineOutput>>,
    > for Backend
{
    async fn generate(
        &self,
        request: SingleIn<PreprocessedEmbeddingRequest>,
        next: ServerStreamingEngine<
            PreprocessedEmbeddingRequest,
            Annotated<EmbeddingsEngineOutput>,
        >,
    ) -> Result<ManyOut<Annotated<EmbeddingsEngineOutput>>> {
        // For embeddings, we mostly pass through since no detokenization is needed
        // But we could add validation, logging, or other post-processing here
        let response_stream = next.generate(request).await?;

        // Could add embedding-specific post-processing here:
        // - Validation of embedding dimensions
        // - Normalization if requested
        // - Usage statistics validation

        Ok(response_stream)
    }
}

Biswa Panda's avatar
Biswa Panda committed
341
342
343
344
345
346
/// The [`Decoder`] object could be a member of either the internal LLM engine or part of the
/// postprocessor. If in the postprocessor, should be minimally in the same process or at very minimum
/// on the same physical machine connected by an IPC.
#[allow(dead_code)]
pub struct Decoder {
    decode_stream: DecodeStream,
347
    tracker: Option<Arc<RequestTracker>>,
Biswa Panda's avatar
Biswa Panda committed
348
349
350
351
352
353
354
355
356

    // do not trigger stop conditions until at least this many tokens have been generated
    min_tokens: u32,

    // single tokens that if found in the response will trigger a stop condition after the
    // minimum number of tokens have been generated
    hidden_stop_ids: HashSet<TokenIdType>,

    // text sequences that if found in the response will trigger a stop condition after the
357
    // minimum number of tokens have been generated (excluded from output)
Biswa Panda's avatar
Biswa Panda committed
358
359
    hidden_stop_sequences: Vec<String>,

360
361
362
363
    // text sequences that if found in the response will trigger a stop condition after the
    // minimum number of tokens have been generated (included in output)
    visible_stop_sequences: Vec<String>,

Biswa Panda's avatar
Biswa Panda committed
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
    // number of generated tokens
    generated_tokens: u32,

    // content jailed by partial hidden stop matches
    jail: String,

    // maximum number of bytes for the largest stop sequence
    jail_max_bytes: usize,

    // the number of bytes currently jailed
    jailed_bytes: usize,
}

#[allow(dead_code)]
#[derive(Debug)]
pub enum StopTrigger {
    MaxTokensLimit,
    HiddenStopTokenDetected(TokenIdType),
    HiddenStopSequenceDetected(String),
383
    VisibleStopSequenceDetected(String),
Biswa Panda's avatar
Biswa Panda committed
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
}

pub struct StepResult {
    pub token: Option<String>,
    pub stop_trigger: Option<StopTrigger>,
}

impl StepResult {
    fn ok(token: Option<String>) -> Self {
        Self {
            token,
            stop_trigger: None,
        }
    }

    fn with_stop_trigger(token: Option<String>, stop_trigger: StopTrigger) -> Self {
        Self {
            token,
            stop_trigger: Some(stop_trigger),
        }
    }
}

/// Result of processing a sequence of tokens
pub struct SeqResult {
    pub tokens: Vec<Option<String>>,       // Individual decoded tokens
    pub text: Option<String>,              // Combined decoded text
    pub stop_trigger: Option<StopTrigger>, // Reason for stopping generation, if any
}

#[allow(dead_code)]
impl Decoder {
    pub fn new(
        decode_stream: DecodeStream,
        stop_condition: StopConditions,
419
        include_stop_str_in_output: bool,
420
        tracker: Option<Arc<RequestTracker>>,
Biswa Panda's avatar
Biswa Panda committed
421
422
423
424
425
426
427
428
    ) -> Self {
        let hidden_stop_ids: HashSet<TokenIdType> = stop_condition
            .stop_token_ids_hidden
            .unwrap_or_default()
            .iter()
            .copied()
            .collect();

429
430
431
432
433
434
435
436
        // Categorize stop sequences based on include_stop_str_in_output:
        // - When true: user-provided stop sequences go to visible (included in output)
        // - When false: user-provided stop sequences go to hidden (excluded from output)
        let (hidden_stop_sequences, visible_stop_sequences) = if include_stop_str_in_output {
            (Vec::new(), stop_condition.stop.unwrap_or_default())
        } else {
            (stop_condition.stop.unwrap_or_default(), Vec::new())
        };
Biswa Panda's avatar
Biswa Panda committed
437

438
        // Calculate jail_max_bytes considering both hidden and visible stop sequences
Biswa Panda's avatar
Biswa Panda committed
439
440
        let jail_max_bytes = hidden_stop_sequences
            .iter()
441
            .chain(visible_stop_sequences.iter())
Biswa Panda's avatar
Biswa Panda committed
442
443
444
445
446
447
            .map(|x| x.len())
            .max()
            .unwrap_or(0);

        Self {
            decode_stream,
448
            tracker,
Biswa Panda's avatar
Biswa Panda committed
449
450
            hidden_stop_ids,
            hidden_stop_sequences,
451
            visible_stop_sequences,
Biswa Panda's avatar
Biswa Panda committed
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
            min_tokens: stop_condition.min_tokens.unwrap_or(0),
            generated_tokens: 0,
            jail: String::new(),
            jail_max_bytes,
            jailed_bytes: 0,
        }
    }

    /// Minimum amount of work to determine if a given generated/decoded sequence should be stopped
    /// This method can be called by the inner most loop of the LLM engine or minimally in the same
    /// process as the LLM engine.
    ///
    /// In the future, this method may kick off async cpu/tokio tasks and or async cuda tasks to
    /// handle logits post-processing and/or other tasks.
    pub fn step(&mut self, token_id: TokenIdType) -> Result<StepResult> {
        // increment the generated tokens
        self.generated_tokens += 1;

        // decode the token
471
        let detokenize_start = Instant::now();
472
473
474
475
476
        let token = {
            let _nvtx = dynamo_nvtx_range!("detokenize");
            self.decode_stream.step(token_id)?
        };
        let detokenize_elapsed = detokenize_start.elapsed();
477
        if let Some(tracker) = &self.tracker {
478
            tracker.record_detokenize_latency(detokenize_elapsed);
479
        }
Biswa Panda's avatar
Biswa Panda committed
480
481
482
483
484
485
486
487
488

        // stop conditions to not apply until the minimum number of tokens have been generated
        if self.generated_tokens < self.min_tokens {
            return Ok(StepResult::ok(token));
        }

        // check for hidden stop tokens - eos takes precedence
        if self.hidden_stop_ids.contains(&token_id) {
            return Ok(StepResult::with_stop_trigger(
489
                None,
Biswa Panda's avatar
Biswa Panda committed
490
491
492
493
494
495
                StopTrigger::HiddenStopTokenDetected(token_id),
            ));
        }

        // check stop sequences - the jail will always hold at least the largest stop sequence
        // if jail_max_bytes is 0, then there are no stop sequences
496
497
498
499
500
501
        if self.jail_max_bytes > 0
            && let Some(token) = &token
        {
            let pre_append = self.jail.len();
            self.jail.push_str(token);

502
            // Check hidden stop sequences first (excluded from output)
503
504
505
            for seq in &self.hidden_stop_sequences {
                if let Some(offset) = galil_seiferas::gs_find(self.jail.as_bytes(), seq.as_bytes())
                {
506
                    // return only new bytes after pre_append .. offset (excluding stop sequence)
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
                    // example: seq = "ox", token = "boxes", return "b"
                    // note: this changes when we start jailing tokens for partial matches
                    // on the suffix of the jail with prefixes of the stop sequences
                    //
                    // we might have returned a partial match, if so, then offset < pre_append
                    // in that case, we return the empty string
                    let partial_token = if offset >= pre_append {
                        self.jail[pre_append..offset].to_string()
                    } else {
                        "".to_string()
                    };
                    return Ok(StepResult::with_stop_trigger(
                        Some(partial_token),
                        StopTrigger::HiddenStopSequenceDetected(seq.to_string()),
                    ));
Biswa Panda's avatar
Biswa Panda committed
522
                }
523
            }
Biswa Panda's avatar
Biswa Panda committed
524

525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
            // Check visible stop sequences (included in output)
            for seq in &self.visible_stop_sequences {
                if let Some(offset) = galil_seiferas::gs_find(self.jail.as_bytes(), seq.as_bytes())
                {
                    // For visible stop sequences, include the stop string in the output
                    // Return all text from pre_append up to and including the stop sequence
                    let stop_end = offset + seq.len();
                    let token_with_stop = if stop_end > pre_append {
                        self.jail[pre_append..stop_end].to_string()
                    } else {
                        // Stop sequence was entirely in previously returned text
                        "".to_string()
                    };
                    return Ok(StepResult::with_stop_trigger(
                        Some(token_with_stop),
                        StopTrigger::VisibleStopSequenceDetected(seq.to_string()),
                    ));
                }
            }

545
            Self::maybe_drain_to_max_bytes(&mut self.jail, self.jail_max_bytes);
Biswa Panda's avatar
Biswa Panda committed
546
547
548
549
550
551
552
        }

        Ok(StepResult::ok(token))
    }

    pub fn process_token_ids(&mut self, token_ids: &[TokenIdType]) -> Result<SeqResult> {
        let mut text: Option<String> = None;
553
        let mut tokens = Vec::with_capacity(token_ids.len());
Biswa Panda's avatar
Biswa Panda committed
554
555
556
557
558
559
560

        for token_id in token_ids {
            let StepResult {
                token,
                stop_trigger,
            } = self.step(*token_id)?;

561
562
            // Always include token text (for visible stops, the stop string is already in the token)
            if let Some(token) = &token {
563
564
                text.get_or_insert_with(|| String::with_capacity(token_ids.len()))
                    .push_str(token);
Biswa Panda's avatar
Biswa Panda committed
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
            }
            tokens.push(token);

            if let Some(stop_trigger) = stop_trigger {
                return Ok(SeqResult {
                    tokens,
                    text,
                    stop_trigger: Some(stop_trigger),
                });
            }
        }

        Ok(SeqResult {
            tokens,
            text,
            stop_trigger: None,
        })
    }

    fn jailed_string(&self) -> Option<String> {
        if self.jailed_bytes > 0 {
            // get the last jailed_bytes from the jail
            Some(self.jail[self.jail.len() - self.jailed_bytes..].to_string())
        } else {
            None
        }
    }
592
593
594
595
596
597
598
599
600
601
602
603

    fn maybe_drain_to_max_bytes(s: &mut String, max_bytes: usize) {
        if s.len() > max_bytes {
            let mut drain_len = s.len() - max_bytes;
            while !s.is_char_boundary(drain_len) {
                drain_len -= 1;
            }
            s.drain(0..drain_len);
        }
    }
}

604
#[cfg(test)]
605
mod tests {
606
607
608
    use super::*;
    use crate::tokenizers::traits;
    use std::sync::Arc;
609
610
611
612
613
614
615
616
617
618

    #[test]
    fn test_char_boundary_drain() {
        let mut s = String::from("helloñworld"); // 12 bytes total ñ is 2 bytes
        let max_bytes = 6; // 12 - 6 = 6 which is inside ñ
        assert!(!s.is_char_boundary(s.len() - max_bytes)); // initially we are not on a char boundary
        Decoder::maybe_drain_to_max_bytes(&mut s, max_bytes);
        assert!(s.is_char_boundary(0)); // front of jail string on valid char boundary
        assert_eq!(s, "ñworld");
    }
619
620
621
622
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
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702

    /// A mock tokenizer that always returns Err from decode().
    /// Used to test the error propagation path in Decoder::process_token_ids().
    struct FailingDecoder;

    impl traits::Encoder for FailingDecoder {
        fn encode(&self, _input: &str) -> anyhow::Result<crate::tokenizers::Encoding> {
            Ok(crate::tokenizers::Encoding::Sp(vec![]))
        }
        fn encode_batch(
            &self,
            _inputs: &[&str],
        ) -> anyhow::Result<Vec<crate::tokenizers::Encoding>> {
            Ok(vec![])
        }
    }

    impl traits::Decoder for FailingDecoder {
        fn decode(
            &self,
            _token_ids: &[TokenIdType],
            _skip_special_tokens: bool,
        ) -> anyhow::Result<String> {
            Err(anyhow::anyhow!(
                "Unable to decode into a valid UTF-8 string: incomplete utf-8 byte sequence from index 6"
            ))
        }
    }

    impl traits::Tokenizer for FailingDecoder {}

    /// When the tokenizer's decode() returns Err, Decoder::process_token_ids()
    /// should propagate the error. In the backend unfold closure, this error
    /// gets caught and converted to FinishReason::Error.
    #[test]
    fn test_decoder_process_token_ids_propagates_decode_error() {
        let tokenizer: Arc<dyn traits::Tokenizer> = Arc::new(FailingDecoder);
        let decode_stream = crate::tokenizers::DecodeStream::new(tokenizer, &[], false);
        let stop_conditions = StopConditions::default();

        let mut decoder = Decoder::new(decode_stream, stop_conditions, false, None);

        let result = decoder.process_token_ids(&[42]);
        assert!(
            result.is_err(),
            "process_token_ids should propagate decode errors"
        );

        let err_msg = result.err().unwrap().to_string();
        assert!(
            err_msg.contains("incomplete utf-8 byte sequence"),
            "error should contain the original decode error message, got: {err_msg}"
        );
    }

    /// Verify that the error message format matches what the backend unfold
    /// closure would wrap into FinishReason::Error.
    #[test]
    fn test_decoder_error_message_format_for_finish_reason() {
        let tokenizer: Arc<dyn traits::Tokenizer> = Arc::new(FailingDecoder);
        let decode_stream = crate::tokenizers::DecodeStream::new(tokenizer, &[], false);
        let stop_conditions = StopConditions::default();

        let mut decoder = Decoder::new(decode_stream, stop_conditions, false, None);

        let result = decoder.process_token_ids(&[42]);
        let err = result.err().expect("should be Err");

        // This is what the backend unfold closure does:
        let finish_reason = FinishReason::Error(format!("decode error: {err}"));
        match &finish_reason {
            FinishReason::Error(msg) => {
                assert!(
                    msg.starts_with("decode error:"),
                    "FinishReason::Error should have 'decode error:' prefix, got: {msg}"
                );
                assert!(
                    msg.contains("incomplete utf-8 byte sequence"),
                    "FinishReason::Error should contain original error, got: {msg}"
                );
            }
            other => panic!("Expected FinishReason::Error, got: {:?}", other),
        }
    }
Biswa Panda's avatar
Biswa Panda committed
703
}