mirror of
https://github.com/huggingface/candle.git
synced 2025-06-22 12:28:06 +00:00
23 lines
716 B
Rust
23 lines
716 B
Rust
use candle::{Result, Tensor};
|
|
|
|
pub fn apply_repeat_penalty(logits: &Tensor, penalty: f32, context: &[u32]) -> Result<Tensor> {
|
|
let device = logits.device();
|
|
let mut logits = logits.to_vec1::<f32>()?;
|
|
let mut already_seen = std::collections::HashSet::new();
|
|
for token_id in context {
|
|
if already_seen.contains(token_id) {
|
|
continue;
|
|
}
|
|
already_seen.insert(token_id);
|
|
if let Some(logit) = logits.get_mut(*token_id as usize) {
|
|
if *logit >= 0. {
|
|
*logit /= penalty
|
|
} else {
|
|
*logit *= penalty
|
|
}
|
|
}
|
|
}
|
|
let logits_len = logits.len();
|
|
Tensor::from_vec(logits, logits_len, device)
|
|
}
|