1use 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#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
45pub enum GenerationMode {
46 Greedy,
48
49 BeamSearch { num_beams: usize },
51
52 TopK { k: usize },
54
55 TopP { p: f32 },
57
58 MinP { p: f32 },
60
61 Temperature { temperature: f32 },
63
64 ContrastiveSearch {
66 top_k: usize,
67 alpha: f32, },
69
70 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#[derive(Debug, Clone, Serialize, Deserialize)]
82pub enum StoppingCriteria {
83 MaxLength,
85
86 EosToken { eos_token_id: u32 },
88
89 AnyToken { token_ids: Vec<u32> },
91
92 AllTokens { token_ids: Vec<u32> },
94
95 StringMatch { pattern: String },
97}
98
99#[derive(Debug, Clone, Serialize, Deserialize)]
101pub struct GenerationConfig {
102 pub max_length: usize,
104
105 pub max_new_tokens: Option<usize>,
107
108 pub min_length: usize,
110
111 pub mode: GenerationMode,
113
114 pub temperature: f32,
117
118 pub repetition_penalty: f32,
120
121 pub frequency_penalty: f32,
123
124 pub presence_penalty: f32,
126
127 pub length_penalty: f32,
129
130 pub num_return_sequences: usize,
132
133 pub early_stopping: bool,
135
136 pub no_kv_cache: bool,
138
139 pub eos_token_id: Option<u32>,
141
142 pub pad_token_id: Option<u32>,
144
145 pub bos_token_id: Option<u32>,
147
148 pub stopping_criteria: Vec<StoppingCriteria>,
150
151 pub bad_words_ids: Vec<Vec<u32>>,
153
154 pub force_words_ids: Vec<Vec<u32>>,
156
157 pub repetition_penalty_decay: f32,
159
160 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 pub fn greedy() -> Self {
194 Self {
195 mode: GenerationMode::Greedy,
196 temperature: 1.0,
197 ..Default::default()
198 }
199 }
200
201 pub fn beam_search(num_beams: usize) -> Self {
203 Self {
204 mode: GenerationMode::BeamSearch { num_beams },
205 ..Default::default()
206 }
207 }
208
209 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 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 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 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#[derive(Debug, Clone)]
317pub struct BeamHypothesis {
318 pub tokens: Vec<u32>,
320 pub score: f32,
322 pub finished: bool,
324}
325
326impl BeamHypothesis {
327 pub fn new(tokens: Vec<u32>, score: f32) -> Self {
329 Self {
330 tokens,
331 score,
332 finished: false,
333 }
334 }
335
336 pub fn normalized_score(&self, length_penalty: f32) -> f32 {
338 self.score / (self.tokens.len() as f32).powf(length_penalty)
339 }
340}
341
342pub struct GenerationUtils;
344
345impl GenerationUtils {
346 pub fn apply_temperature(logits: &mut [f32], temperature: f32) {
348 if (temperature - 1.0).abs() < 1e-6 {
349 return; }
351
352 for logit in logits.iter_mut() {
353 *logit /= temperature;
354 }
355 }
356
357 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 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 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 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 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 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 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 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 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 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 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 let top_k_logits: Vec<f32> = indexed_logits.iter().map(|(_, logit)| *logit).collect();
490 let probs = Self::softmax(&top_k_logits);
491
492 let sample_idx = Self::sample_from_probs(&probs, rng)?;
494 Ok(indexed_logits[sample_idx].0 as u32)
495 }
496
497 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 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 let sorted_logits: Vec<f32> = indexed_logits.iter().map(|(_, logit)| *logit).collect();
512 let probs = Self::softmax(&sorted_logits);
513
514 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 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 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 let max_logit = logits.iter().fold(f32::NEG_INFINITY, |a, &b| a.max(b));
542
543 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 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 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 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 Ok(probs.len() - 1)
589 }
590
591 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 pub fn should_stop(sequence: &[u32], config: &GenerationConfig, prompt_length: usize) -> bool {
618 if sequence.len() >= config.max_length {
620 return true;
621 }
622
623 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 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 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#[derive(Debug, Clone)]
677pub struct KVCache {
678 pub keys: Vec<Tensor>,
680 pub values: Vec<Tensor>,
682 pub seq_length: usize,
684}
685
686impl KVCache {
687 pub fn new() -> Self {
689 Self {
690 keys: vec![],
691 values: vec![],
692 seq_length: 0,
693 }
694 }
695
696 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 pub fn append(&mut self, layer_idx: usize, key: Tensor, value: Tensor) -> Result<()> {
707 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 self.keys[layer_idx] = if self.seq_length == 0 {
715 key
716 } else {
717 key };
719
720 self.values[layer_idx] = if self.seq_length == 0 { value } else { value };
721
722 Ok(())
723 }
724
725 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 pub fn clear(&mut self) {
736 self.keys.clear();
737 self.values.clear();
738 self.seq_length = 0;
739 }
740
741 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]; GenerationUtils::apply_repetition_penalty(&mut logits, &generated, 2.0, 1.0);
789
790 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 let sum: f32 = probs.iter().sum();
802 assert!((sum - 1.0).abs() < 1e-5);
803
804 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); }
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 let at_limit: Vec<u32> = (0..10).collect();
835 assert!(GenerationUtils::should_stop(&at_limit, &config, 0));
836
837 let tokens_with_eos = vec![1, 2, 50256];
839 assert!(GenerationUtils::should_stop(&tokens_with_eos, &config, 0));
840
841 let tokens = vec![1, 2, 3];
843 assert!(!GenerationUtils::should_stop(&tokens, &config, 0));
844 }
845
846 #[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 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 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 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 #[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 #[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 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]; let bad_words = vec![vec![0, 1, 2]]; GenerationUtils::apply_bad_words_filter(&mut logits, &generated, &bad_words);
960
961 assert_eq!(logits[2], f32::NEG_INFINITY);
963 assert_eq!(logits[0], 1.0);
965 assert_eq!(logits[1], 2.0);
966 }
967}