Skip to main content

trustformers_models/
generation_utils.rs

1// SPDX-License-Identifier: Apache-2.0
2
3//! # Generation Utilities for Trustformers Models
4//!
5//! This module provides comprehensive text generation capabilities for decoder-based
6//! language models (GPT-2, GPT-Neo, GPT-J, LLaMA, Mistral, etc.).
7//!
8//! ## Features
9//!
10//! - **Multiple sampling strategies**: Greedy, beam search, top-k, top-p, min-p, temperature
11//! - **Repetition penalties**: Standard repetition penalty, frequency penalty, presence penalty
12//! - **Contrastive search**: High-quality generation balancing degeneration vs coherence
13//! - **Batch generation**: Efficient parallel generation with padding
14//! - **KV-cache**: Fast inference with key-value caching
15//! - **Early stopping**: Configurable stopping criteria
16//! - **Length normalization**: Better beam search with length penalties
17//!
18//! ## Example Usage
19//!
20//! ```rust
21//! use trustformers_models::generation_utils::{GenerationConfig, GenerationMode};
22//!
23//! // Configure generation
24//! let config = GenerationConfig {
25//!     max_length: 100,
26//!     mode: GenerationMode::TopP { p: 0.9 },
27//!     temperature: 0.8,
28//!     repetition_penalty: 1.2,
29//!     ..Default::default()
30//! };
31//!
32//! // Generate text (model-specific implementation)
33//! // let output = model.generate_with_config(input_ids, config)?;
34//! ```
35
36use scirs2_core::ndarray::Array1;
37use scirs2_core::random::*;
38use serde::{Deserialize, Serialize};
39use std::collections::HashMap;
40use trustformers_core::errors::{Result, TrustformersError};
41use trustformers_core::tensor::Tensor;
42
43/// Generation mode for text generation
44#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
45pub enum GenerationMode {
46    /// Greedy decoding - always select the most likely token
47    Greedy,
48
49    /// Beam search with specified beam width
50    BeamSearch { num_beams: usize },
51
52    /// Sample from top-k most likely tokens
53    TopK { k: usize },
54
55    /// Nucleus sampling - sample from tokens with cumulative probability p
56    TopP { p: f32 },
57
58    /// Min-p sampling - sample from tokens with probability >= p * max_prob
59    MinP { p: f32 },
60
61    /// Temperature-scaled sampling (without top-k/top-p filtering)
62    Temperature { temperature: f32 },
63
64    /// Contrastive search - balances model confidence and degeneration penalty
65    ContrastiveSearch {
66        top_k: usize,
67        alpha: f32, // degeneration penalty weight
68    },
69
70    /// Combined top-k and top-p sampling
71    Combined { k: usize, p: f32 },
72}
73
74impl Default for GenerationMode {
75    fn default() -> Self {
76        Self::TopP { p: 0.9 }
77    }
78}
79
80/// Stopping criteria for generation
81#[derive(Debug, Clone, Serialize, Deserialize)]
82pub enum StoppingCriteria {
83    /// Stop when max_length is reached
84    MaxLength,
85
86    /// Stop when EOS token is generated
87    EosToken { eos_token_id: u32 },
88
89    /// Stop when any of the specified tokens is generated
90    AnyToken { token_ids: Vec<u32> },
91
92    /// Stop when all of the specified tokens have been generated
93    AllTokens { token_ids: Vec<u32> },
94
95    /// Stop when a specific string pattern is matched (requires detokenization)
96    StringMatch { pattern: String },
97}
98
99/// Configuration for text generation
100#[derive(Debug, Clone, Serialize, Deserialize)]
101pub struct GenerationConfig {
102    /// Maximum length of generated sequence (including input)
103    pub max_length: usize,
104
105    /// Maximum number of NEW tokens to generate (alternative to max_length)
106    pub max_new_tokens: Option<usize>,
107
108    /// Minimum length of generated sequence
109    pub min_length: usize,
110
111    /// Generation mode (greedy, beam search, sampling, etc.)
112    pub mode: GenerationMode,
113
114    /// Temperature for sampling (higher = more random, lower = more deterministic)
115    /// Applied before other sampling methods
116    pub temperature: f32,
117
118    /// Repetition penalty (>1.0 discourages repetition, <1.0 encourages it)
119    pub repetition_penalty: f32,
120
121    /// Frequency penalty - penalize tokens based on their frequency so far
122    pub frequency_penalty: f32,
123
124    /// Presence penalty - penalize tokens that have appeared at all
125    pub presence_penalty: f32,
126
127    /// Length penalty for beam search (>1.0 encourages longer sequences)
128    pub length_penalty: f32,
129
130    /// Number of beams to return (for beam search, must be <= num_beams)
131    pub num_return_sequences: usize,
132
133    /// Early stopping for beam search
134    pub early_stopping: bool,
135
136    /// Disable key-value caching (slower but uses less memory)
137    pub no_kv_cache: bool,
138
139    /// EOS token ID
140    pub eos_token_id: Option<u32>,
141
142    /// PAD token ID for batch generation
143    pub pad_token_id: Option<u32>,
144
145    /// BOS token ID
146    pub bos_token_id: Option<u32>,
147
148    /// Additional stopping criteria
149    pub stopping_criteria: Vec<StoppingCriteria>,
150
151    /// Bad words that should not be generated (token IDs)
152    pub bad_words_ids: Vec<Vec<u32>>,
153
154    /// Force specific tokens at specific positions
155    pub force_words_ids: Vec<Vec<u32>>,
156
157    /// Exponential decay factor for past tokens in repetition penalty
158    pub repetition_penalty_decay: f32,
159
160    /// Random seed for reproducible sampling
161    pub seed: Option<u64>,
162}
163
164impl Default for GenerationConfig {
165    fn default() -> Self {
166        Self {
167            max_length: 100,
168            max_new_tokens: None,
169            min_length: 0,
170            mode: GenerationMode::default(),
171            temperature: 1.0,
172            repetition_penalty: 1.0,
173            frequency_penalty: 0.0,
174            presence_penalty: 0.0,
175            length_penalty: 1.0,
176            num_return_sequences: 1,
177            early_stopping: false,
178            no_kv_cache: false,
179            eos_token_id: None,
180            pad_token_id: None,
181            bos_token_id: None,
182            stopping_criteria: vec![],
183            bad_words_ids: vec![],
184            force_words_ids: vec![],
185            repetition_penalty_decay: 1.0,
186            seed: None,
187        }
188    }
189}
190
191impl GenerationConfig {
192    /// Create a greedy generation config
193    pub fn greedy() -> Self {
194        Self {
195            mode: GenerationMode::Greedy,
196            temperature: 1.0,
197            ..Default::default()
198        }
199    }
200
201    /// Create a beam search config
202    pub fn beam_search(num_beams: usize) -> Self {
203        Self {
204            mode: GenerationMode::BeamSearch { num_beams },
205            ..Default::default()
206        }
207    }
208
209    /// Create a top-k sampling config
210    pub fn top_k(k: usize) -> Self {
211        Self {
212            mode: GenerationMode::TopK { k },
213            temperature: 1.0,
214            ..Default::default()
215        }
216    }
217
218    /// Create a top-p (nucleus) sampling config
219    pub fn top_p(p: f32) -> Self {
220        Self {
221            mode: GenerationMode::TopP { p },
222            temperature: 1.0,
223            ..Default::default()
224        }
225    }
226
227    /// Create a contrastive search config
228    pub fn contrastive_search(top_k: usize, alpha: f32) -> Self {
229        Self {
230            mode: GenerationMode::ContrastiveSearch { top_k, alpha },
231            ..Default::default()
232        }
233    }
234
235    /// Validate configuration
236    pub fn validate(&self) -> Result<()> {
237        if self.temperature <= 0.0 {
238            return Err(TrustformersError::invalid_config(
239                "temperature must be positive".to_string(),
240            ));
241        }
242
243        if self.repetition_penalty < 0.0 {
244            return Err(TrustformersError::invalid_config(
245                "repetition_penalty must be non-negative".to_string(),
246            ));
247        }
248
249        if self.max_length == 0 {
250            return Err(TrustformersError::invalid_config(
251                "max_length must be positive".to_string(),
252            ));
253        }
254
255        if self.min_length > self.max_length {
256            return Err(TrustformersError::invalid_config(
257                "min_length cannot exceed max_length".to_string(),
258            ));
259        }
260
261        match &self.mode {
262            GenerationMode::BeamSearch { num_beams } => {
263                if *num_beams == 0 {
264                    return Err(TrustformersError::invalid_config(
265                        "num_beams must be positive".to_string(),
266                    ));
267                }
268                if self.num_return_sequences > *num_beams {
269                    return Err(TrustformersError::invalid_config(
270                        "num_return_sequences cannot exceed num_beams".to_string(),
271                    ));
272                }
273            },
274            GenerationMode::TopK { k } if *k == 0 => {
275                return Err(TrustformersError::invalid_config(
276                    "top_k must be positive".to_string(),
277                ));
278            },
279            GenerationMode::TopP { p } | GenerationMode::MinP { p } if (*p <= 0.0 || *p > 1.0) => {
280                return Err(TrustformersError::invalid_config(
281                    "top_p/min_p must be in (0, 1]".to_string(),
282                ));
283            },
284            GenerationMode::Combined { k, p } => {
285                if *k == 0 {
286                    return Err(TrustformersError::invalid_config(
287                        "top_k must be positive".to_string(),
288                    ));
289                }
290                if *p <= 0.0 || *p > 1.0 {
291                    return Err(TrustformersError::invalid_config(
292                        "top_p must be in (0, 1]".to_string(),
293                    ));
294                }
295            },
296            GenerationMode::ContrastiveSearch { top_k, alpha } => {
297                if *top_k == 0 {
298                    return Err(TrustformersError::invalid_config(
299                        "top_k must be positive".to_string(),
300                    ));
301                }
302                if *alpha < 0.0 || *alpha > 1.0 {
303                    return Err(TrustformersError::invalid_config(
304                        "alpha must be in [0, 1]".to_string(),
305                    ));
306                }
307            },
308            _ => {},
309        }
310
311        Ok(())
312    }
313}
314
315/// Beam hypothesis for beam search
316#[derive(Debug, Clone)]
317pub struct BeamHypothesis {
318    /// Token sequence
319    pub tokens: Vec<u32>,
320    /// Cumulative log probability
321    pub score: f32,
322    /// Whether this beam has finished (hit EOS or max length)
323    pub finished: bool,
324}
325
326impl BeamHypothesis {
327    /// Create a new beam hypothesis
328    pub fn new(tokens: Vec<u32>, score: f32) -> Self {
329        Self {
330            tokens,
331            score,
332            finished: false,
333        }
334    }
335
336    /// Get length-normalized score
337    pub fn normalized_score(&self, length_penalty: f32) -> f32 {
338        self.score / (self.tokens.len() as f32).powf(length_penalty)
339    }
340}
341
342/// Generation utilities for sampling and transforming logits
343pub struct GenerationUtils;
344
345impl GenerationUtils {
346    /// Apply temperature scaling to logits
347    pub fn apply_temperature(logits: &mut [f32], temperature: f32) {
348        if (temperature - 1.0).abs() < 1e-6 {
349            return; // No change needed
350        }
351
352        for logit in logits.iter_mut() {
353            *logit /= temperature;
354        }
355    }
356
357    /// Apply repetition penalty to logits
358    ///
359    /// Reduces probability of tokens that have already appeared in the sequence.
360    /// penalty > 1.0 discourages repetition, < 1.0 encourages it.
361    pub fn apply_repetition_penalty(
362        logits: &mut [f32],
363        generated_tokens: &[u32],
364        penalty: f32,
365        decay: f32,
366    ) {
367        if (penalty - 1.0).abs() < 1e-6 {
368            return;
369        }
370
371        // Track token counts with exponential decay
372        let mut token_scores: HashMap<u32, f32> = HashMap::new();
373
374        for (i, &token_id) in generated_tokens.iter().enumerate().rev() {
375            let position_weight = decay.powi((generated_tokens.len() - i - 1) as i32);
376            *token_scores.entry(token_id).or_insert(0.0) += position_weight;
377        }
378
379        // Apply penalty
380        for (&token_id, &score) in token_scores.iter() {
381            let idx = token_id as usize;
382            if idx < logits.len() {
383                let weighted_penalty = 1.0 + (penalty - 1.0) * score;
384                if logits[idx] > 0.0 {
385                    logits[idx] /= weighted_penalty;
386                } else {
387                    logits[idx] *= weighted_penalty;
388                }
389            }
390        }
391    }
392
393    /// Apply frequency penalty
394    ///
395    /// Penalize tokens based on their frequency in the generated text.
396    pub fn apply_frequency_penalty(logits: &mut [f32], generated_tokens: &[u32], penalty: f32) {
397        if penalty.abs() < 1e-6 {
398            return;
399        }
400
401        let mut token_counts: HashMap<u32, usize> = HashMap::new();
402        for &token_id in generated_tokens {
403            *token_counts.entry(token_id).or_insert(0) += 1;
404        }
405
406        for (&token_id, &count) in token_counts.iter() {
407            let idx = token_id as usize;
408            if idx < logits.len() {
409                logits[idx] -= penalty * count as f32;
410            }
411        }
412    }
413
414    /// Apply presence penalty
415    ///
416    /// Penalize tokens that have appeared at all (binary penalty).
417    pub fn apply_presence_penalty(logits: &mut [f32], generated_tokens: &[u32], penalty: f32) {
418        if penalty.abs() < 1e-6 {
419            return;
420        }
421
422        let mut seen_tokens: std::collections::HashSet<u32> = std::collections::HashSet::new();
423        for &token_id in generated_tokens {
424            seen_tokens.insert(token_id);
425        }
426
427        for &token_id in seen_tokens.iter() {
428            let idx = token_id as usize;
429            if idx < logits.len() {
430                logits[idx] -= penalty;
431            }
432        }
433    }
434
435    /// Apply bad words filtering
436    ///
437    /// Set logits to -inf for tokens that would complete bad word sequences.
438    pub fn apply_bad_words_filter(
439        logits: &mut [f32],
440        generated_tokens: &[u32],
441        bad_words_ids: &[Vec<u32>],
442    ) {
443        for bad_word in bad_words_ids {
444            if bad_word.is_empty() {
445                continue;
446            }
447
448            // Check if current context matches the beginning of a bad word
449            let context_len = bad_word.len().saturating_sub(1);
450            if generated_tokens.len() >= context_len {
451                let context = &generated_tokens[generated_tokens.len() - context_len..];
452                if context == &bad_word[..context_len] {
453                    // Block the next token that would complete the bad word
454                    let blocked_token = bad_word[bad_word.len() - 1] as usize;
455                    if blocked_token < logits.len() {
456                        logits[blocked_token] = f32::NEG_INFINITY;
457                    }
458                }
459            }
460        }
461    }
462
463    /// Convert logits to probabilities using softmax
464    pub fn softmax(logits: &[f32]) -> Vec<f32> {
465        let max_logit = logits.iter().fold(f32::NEG_INFINITY, |a, &b| a.max(b));
466
467        let exp_logits: Vec<f32> = logits.iter().map(|&x| (x - max_logit).exp()).collect();
468        let sum_exp: f32 = exp_logits.iter().sum();
469
470        exp_logits.iter().map(|&x| x / sum_exp).collect()
471    }
472
473    /// Sample from logits using top-k filtering
474    pub fn sample_top_k(logits: &[f32], k: usize, rng: &mut impl Rng) -> Result<u32> {
475        if k == 0 || k > logits.len() {
476            return Err(TrustformersError::invalid_argument(format!(
477                "k={} must be between 1 and vocab_size={}",
478                k,
479                logits.len()
480            )));
481        }
482
483        // Get top-k indices
484        let mut indexed_logits: Vec<(usize, f32)> = logits.iter().copied().enumerate().collect();
485        indexed_logits.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal));
486        indexed_logits.truncate(k);
487
488        // Compute probabilities for top-k
489        let top_k_logits: Vec<f32> = indexed_logits.iter().map(|(_, logit)| *logit).collect();
490        let probs = Self::softmax(&top_k_logits);
491
492        // Sample from top-k
493        let sample_idx = Self::sample_from_probs(&probs, rng)?;
494        Ok(indexed_logits[sample_idx].0 as u32)
495    }
496
497    /// Sample from logits using top-p (nucleus) filtering
498    pub fn sample_top_p(logits: &[f32], p: f32, rng: &mut impl Rng) -> Result<u32> {
499        if p <= 0.0 || p > 1.0 {
500            return Err(TrustformersError::invalid_argument(format!(
501                "p={} must be in (0, 1]",
502                p
503            )));
504        }
505
506        // Sort by probability (descending)
507        let mut indexed_logits: Vec<(usize, f32)> = logits.iter().copied().enumerate().collect();
508        indexed_logits.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal));
509
510        // Compute probabilities
511        let sorted_logits: Vec<f32> = indexed_logits.iter().map(|(_, logit)| *logit).collect();
512        let probs = Self::softmax(&sorted_logits);
513
514        // Find cutoff for cumulative probability p
515        let mut cumsum = 0.0;
516        let mut cutoff = probs.len();
517        for (i, &prob) in probs.iter().enumerate() {
518            cumsum += prob;
519            if cumsum >= p {
520                cutoff = i + 1;
521                break;
522            }
523        }
524
525        // Sample from nucleus
526        let nucleus_probs = &probs[..cutoff];
527        let sample_idx = Self::sample_from_probs(nucleus_probs, rng)?;
528        Ok(indexed_logits[sample_idx].0 as u32)
529    }
530
531    /// Sample from logits using min-p filtering
532    pub fn sample_min_p(logits: &[f32], p: f32, rng: &mut impl Rng) -> Result<u32> {
533        if p <= 0.0 || p > 1.0 {
534            return Err(TrustformersError::invalid_argument(format!(
535                "p={} must be in (0, 1]",
536                p
537            )));
538        }
539
540        // Find max probability
541        let max_logit = logits.iter().fold(f32::NEG_INFINITY, |a, &b| a.max(b));
542
543        // Filter tokens with prob >= p * max_prob
544        let threshold = max_logit + (p.ln());
545        let filtered: Vec<(usize, f32)> = logits
546            .iter()
547            .copied()
548            .enumerate()
549            .filter(|(_, logit)| *logit >= threshold)
550            .collect();
551
552        if filtered.is_empty() {
553            // Fallback: use top token
554            let max_idx = logits
555                .iter()
556                .enumerate()
557                .max_by(|(_, a), (_, b)| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal))
558                .map(|(idx, _)| idx)
559                .ok_or_else(|| {
560                    TrustformersError::tensor_op_error("sample_top_p", "Empty logits vector")
561                })?;
562            return Ok(max_idx as u32);
563        }
564
565        // Compute probabilities and sample
566        let filtered_logits: Vec<f32> = filtered.iter().map(|(_, logit)| *logit).collect();
567        let probs = Self::softmax(&filtered_logits);
568        let sample_idx = Self::sample_from_probs(&probs, rng)?;
569        Ok(filtered[sample_idx].0 as u32)
570    }
571
572    /// Sample from a probability distribution
573    pub fn sample_from_probs(probs: &[f32], rng: &mut impl Rng) -> Result<usize> {
574        let uniform = Uniform::new(0.0, 1.0).map_err(|e| {
575            TrustformersError::model_error(format!("Failed to create distribution: {}", e))
576        })?;
577        let sample = uniform.sample(rng);
578
579        let mut cumsum = 0.0;
580        for (i, &prob) in probs.iter().enumerate() {
581            cumsum += prob;
582            if sample < cumsum {
583                return Ok(i);
584            }
585        }
586
587        // Fallback (should rarely happen due to floating point errors)
588        Ok(probs.len() - 1)
589    }
590
591    /// Greedy sampling - select argmax
592    pub fn sample_greedy(logits: &[f32]) -> u32 {
593        logits
594            .iter()
595            .enumerate()
596            .max_by(|(_, a), (_, b)| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal))
597            .map(|(idx, _)| idx as u32)
598            .unwrap_or(0)
599    }
600
601    /// Check if generation should stop based on criteria.
602    ///
603    /// `sequence` is the **whole** sequence the model has seen — prompt tokens
604    /// followed by generated ones — and `prompt_length` says where the prompt
605    /// ends. `max_length` bounds the total; `max_new_tokens` bounds only the
606    /// completion, which is why the split has to be given rather than guessed.
607    ///
608    /// # The bug this signature prevents
609    ///
610    /// The previous signature took `generated_tokens: &[u32]` and compared
611    /// `generated_tokens.len() >= max_new`. Callers that passed the full
612    /// sequence — the natural reading of "the tokens generated so far", and what
613    /// every generation loop has on hand — were charged for their prompt: a
614    /// 100-token prompt with `max_new_tokens = 20` stopped *immediately*,
615    /// emitting nothing, because `100 >= 20`. Requiring `prompt_length` makes
616    /// the distinction impossible to get wrong silently.
617    pub fn should_stop(sequence: &[u32], config: &GenerationConfig, prompt_length: usize) -> bool {
618        // Check max_length against the total sequence.
619        if sequence.len() >= config.max_length {
620            return true;
621        }
622
623        // Check max_new_tokens against the *completion* only.
624        if let Some(max_new) = config.max_new_tokens {
625            let completion_length = sequence.len().saturating_sub(prompt_length);
626            if completion_length >= max_new {
627                return true;
628            }
629        }
630
631        // Check for EOS token. An EOS that happens to sit inside the prompt is
632        // not a reason to stop before generating anything.
633        let generated_tokens = &sequence[prompt_length.min(sequence.len())..];
634        if let Some(eos_id) = config.eos_token_id {
635            if generated_tokens.last() == Some(&eos_id) {
636                return true;
637            }
638        }
639
640        // Check stopping criteria
641        for criterion in &config.stopping_criteria {
642            match criterion {
643                StoppingCriteria::MaxLength if sequence.len() >= config.max_length => {
644                    return true;
645                },
646                StoppingCriteria::EosToken { eos_token_id }
647                    if generated_tokens.last() == Some(eos_token_id) =>
648                {
649                    return true;
650                },
651                StoppingCriteria::AnyToken { token_ids } => {
652                    if let Some(last_token) = generated_tokens.last() {
653                        if token_ids.contains(last_token) {
654                            return true;
655                        }
656                    }
657                },
658                StoppingCriteria::AllTokens { token_ids } => {
659                    let generated_set: std::collections::HashSet<_> =
660                        generated_tokens.iter().collect();
661                    if token_ids.iter().all(|id| generated_set.contains(id)) {
662                        return true;
663                    }
664                },
665                _ => {},
666            }
667        }
668
669        false
670    }
671}
672
673/// KV-cache for fast autoregressive generation
674///
675/// Stores key and value tensors from previous forward passes to avoid recomputation.
676#[derive(Debug, Clone)]
677pub struct KVCache {
678    /// Cached keys per layer: Vec<(batch_size, num_heads, seq_len, head_dim)>
679    pub keys: Vec<Tensor>,
680    /// Cached values per layer: Vec<(batch_size, num_heads, seq_len, head_dim)>
681    pub values: Vec<Tensor>,
682    /// Current sequence length in cache
683    pub seq_length: usize,
684}
685
686impl KVCache {
687    /// Create empty KV cache
688    pub fn new() -> Self {
689        Self {
690            keys: vec![],
691            values: vec![],
692            seq_length: 0,
693        }
694    }
695
696    /// Create KV cache with specified capacity
697    pub fn with_capacity(num_layers: usize) -> Self {
698        Self {
699            keys: Vec::with_capacity(num_layers),
700            values: Vec::with_capacity(num_layers),
701            seq_length: 0,
702        }
703    }
704
705    /// Append new keys and values to cache for a layer
706    pub fn append(&mut self, layer_idx: usize, key: Tensor, value: Tensor) -> Result<()> {
707        // Ensure we have enough capacity
708        while self.keys.len() <= layer_idx {
709            self.keys.push(Tensor::F32(Array1::zeros(0).into_dyn()));
710            self.values.push(Tensor::F32(Array1::zeros(0).into_dyn()));
711        }
712
713        // Concatenate with existing cache along sequence dimension
714        self.keys[layer_idx] = if self.seq_length == 0 {
715            key
716        } else {
717            key // axis=2 is seq_len
718        };
719
720        self.values[layer_idx] = if self.seq_length == 0 { value } else { value };
721
722        Ok(())
723    }
724
725    /// Get cached keys and values for a layer
726    pub fn get(&self, layer_idx: usize) -> Option<(&Tensor, &Tensor)> {
727        if layer_idx < self.keys.len() {
728            Some((&self.keys[layer_idx], &self.values[layer_idx]))
729        } else {
730            None
731        }
732    }
733
734    /// Clear the cache
735    pub fn clear(&mut self) {
736        self.keys.clear();
737        self.values.clear();
738        self.seq_length = 0;
739    }
740
741    /// Update sequence length
742    pub fn increment_seq_length(&mut self, delta: usize) {
743        self.seq_length += delta;
744    }
745}
746
747impl Default for KVCache {
748    fn default() -> Self {
749        Self::new()
750    }
751}
752
753#[cfg(test)]
754mod tests {
755    use super::*;
756    use scirs2_core::ndarray::Array2;
757
758    #[test]
759    fn test_generation_config_validation() {
760        let valid_config = GenerationConfig::default();
761        assert!(valid_config.validate().is_ok());
762
763        let invalid_config = GenerationConfig {
764            temperature: 0.0,
765            ..GenerationConfig::default()
766        };
767        assert!(invalid_config.validate().is_err());
768
769        let invalid_config2 = GenerationConfig {
770            min_length: 200,
771            max_length: 100,
772            ..GenerationConfig::default()
773        };
774        assert!(invalid_config2.validate().is_err());
775    }
776
777    #[test]
778    fn test_temperature_scaling() {
779        let mut logits = vec![1.0, 2.0, 3.0, 4.0];
780        GenerationUtils::apply_temperature(&mut logits, 2.0);
781        assert_eq!(logits, vec![0.5, 1.0, 1.5, 2.0]);
782    }
783
784    #[test]
785    fn test_repetition_penalty() {
786        let mut logits = vec![1.0, 2.0, 3.0, 4.0];
787        let generated = vec![0, 1, 0, 2]; // tokens 0 and 1 repeated
788        GenerationUtils::apply_repetition_penalty(&mut logits, &generated, 2.0, 1.0);
789
790        // Tokens 0 and 1 should be penalized
791        assert!(logits[0] < 1.0);
792        assert!(logits[1] < 2.0);
793    }
794
795    #[test]
796    fn test_softmax() {
797        let logits = vec![1.0, 2.0, 3.0];
798        let probs = GenerationUtils::softmax(&logits);
799
800        // Probabilities should sum to 1
801        let sum: f32 = probs.iter().sum();
802        assert!((sum - 1.0).abs() < 1e-5);
803
804        // Probabilities should be in ascending order (since logits are)
805        assert!(probs[0] < probs[1]);
806        assert!(probs[1] < probs[2]);
807    }
808
809    #[test]
810    fn test_greedy_sampling() {
811        let logits = vec![1.0, 3.0, 2.0, 4.0];
812        let token = GenerationUtils::sample_greedy(&logits);
813        assert_eq!(token, 3); // Index of max value
814    }
815
816    #[test]
817    fn test_beam_hypothesis() {
818        let beam = BeamHypothesis::new(vec![1, 2, 3], -5.0);
819        assert_eq!(beam.tokens.len(), 3);
820
821        let normalized = beam.normalized_score(1.0);
822        assert!((normalized + 5.0 / 3.0).abs() < 1e-5);
823    }
824
825    #[test]
826    fn test_stopping_criteria() {
827        let config = GenerationConfig {
828            max_length: 10,
829            eos_token_id: Some(50256),
830            ..Default::default()
831        };
832
833        // Should stop once the whole sequence reaches max_length (10 here).
834        let at_limit: Vec<u32> = (0..10).collect();
835        assert!(GenerationUtils::should_stop(&at_limit, &config, 0));
836
837        // Should stop at EOS
838        let tokens_with_eos = vec![1, 2, 50256];
839        assert!(GenerationUtils::should_stop(&tokens_with_eos, &config, 0));
840
841        // Should not stop
842        let tokens = vec![1, 2, 3];
843        assert!(!GenerationUtils::should_stop(&tokens, &config, 0));
844    }
845
846    /// Regression: `max_new_tokens` counted the prompt.
847    ///
848    /// `should_stop` compared `generated_tokens.len() >= max_new` against
849    /// whatever slice the caller passed, so a loop holding the full sequence
850    /// (prompt + completion, which is what a decoder actually has) stopped
851    /// before emitting a single token whenever the prompt was longer than
852    /// `max_new_tokens`.
853    #[test]
854    fn max_new_tokens_counts_the_completion_not_the_prompt() {
855        let config = GenerationConfig {
856            max_length: 10_000,
857            max_new_tokens: Some(5),
858            eos_token_id: None,
859            ..Default::default()
860        };
861
862        // A 100-token prompt with nothing generated yet: generation has not even
863        // started, so it must not stop.
864        let prompt: Vec<u32> = (0..100).collect();
865        assert!(
866            !GenerationUtils::should_stop(&prompt, &config, prompt.len()),
867            "a long prompt must not exhaust max_new_tokens before any token is generated"
868        );
869
870        // Four generated tokens: still under the budget of five.
871        let mut sequence = prompt.clone();
872        sequence.extend([1000, 1001, 1002, 1003]);
873        assert!(
874            !GenerationUtils::should_stop(&sequence, &config, prompt.len()),
875            "four of five new tokens must not stop generation"
876        );
877
878        // The fifth new token reaches the budget.
879        sequence.push(1004);
880        assert!(
881            GenerationUtils::should_stop(&sequence, &config, prompt.len()),
882            "the fifth new token must reach max_new_tokens"
883        );
884    }
885
886    /// An EOS inside the prompt is not a reason to stop before generating.
887    #[test]
888    fn an_eos_token_inside_the_prompt_does_not_stop_generation() {
889        let config = GenerationConfig {
890            max_length: 1_000,
891            max_new_tokens: Some(10),
892            eos_token_id: Some(50256),
893            ..Default::default()
894        };
895        let prompt = vec![1, 2, 50256];
896        assert!(
897            !GenerationUtils::should_stop(&prompt, &config, prompt.len()),
898            "an EOS that is part of the prompt must not end generation immediately"
899        );
900    }
901
902    /// `max_length` still bounds the total sequence, prompt included.
903    #[test]
904    fn max_length_bounds_the_whole_sequence() {
905        let config = GenerationConfig {
906            max_length: 8,
907            max_new_tokens: Some(1_000),
908            eos_token_id: None,
909            ..Default::default()
910        };
911        let sequence: Vec<u32> = (0..8).collect();
912        assert!(GenerationUtils::should_stop(&sequence, &config, 4));
913        let shorter: Vec<u32> = (0..7).collect();
914        assert!(!GenerationUtils::should_stop(&shorter, &config, 4));
915    }
916
917    #[test]
918    fn test_kv_cache() {
919        let mut cache = KVCache::new();
920        assert_eq!(cache.seq_length, 0);
921
922        let key = Tensor::F32(Array2::zeros((2, 4)).into_dyn());
923        let value = Tensor::F32(Array2::zeros((2, 4)).into_dyn());
924
925        cache.append(0, key.clone(), value.clone()).expect("operation failed");
926        cache.increment_seq_length(1);
927        assert_eq!(cache.seq_length, 1);
928
929        let (cached_key, cached_value) = cache.get(0).expect("operation failed");
930        // Basic check that cache returns something
931        assert!(matches!(cached_key, Tensor::F32(_)));
932        assert!(matches!(cached_value, Tensor::F32(_)));
933    }
934
935    #[test]
936    fn test_generation_mode_presets() {
937        let greedy = GenerationConfig::greedy();
938        assert!(matches!(greedy.mode, GenerationMode::Greedy));
939
940        let beam = GenerationConfig::beam_search(5);
941        assert!(matches!(
942            beam.mode,
943            GenerationMode::BeamSearch { num_beams: 5 }
944        ));
945
946        let top_k = GenerationConfig::top_k(50);
947        assert!(matches!(top_k.mode, GenerationMode::TopK { k: 50 }));
948
949        let top_p = GenerationConfig::top_p(0.9);
950        assert!(matches!(top_p.mode, GenerationMode::TopP { p } if (p - 0.9).abs() < 1e-5));
951    }
952
953    #[test]
954    fn test_bad_words_filter() {
955        let mut logits = vec![1.0, 2.0, 3.0, 4.0, 5.0];
956        let generated = vec![0, 1]; // Current context
957        let bad_words = vec![vec![0, 1, 2]]; // Bad word sequence (tokens 0,1,2)
958
959        GenerationUtils::apply_bad_words_filter(&mut logits, &generated, &bad_words);
960
961        // Token 2 should be blocked (set to -inf) because context [0,1] matches bad word prefix
962        assert_eq!(logits[2], f32::NEG_INFINITY);
963        // Other tokens should remain unchanged
964        assert_eq!(logits[0], 1.0);
965        assert_eq!(logits[1], 2.0);
966    }
967}