#[derive(Debug, Clone, Copy, PartialEq)]
pub struct BiasEntry {
pub token: i32,
pub bias: f32,
}
pub fn parse_entry(value: &str) -> Result<BiasEntry, String> {
let invalid = || format!("{value:?}: invalid input format, expected TOKEN_ID(+/-)BIAS");
let rest = value.trim_start_matches(is_c_space);
let (token, rest) = take_int(rest).ok_or_else(invalid)?;
let rest = rest.trim_start_matches(is_c_space);
let mut chars = rest.chars();
let sign = match chars.next() {
Some('+') => 1.0f32,
Some('-') => -1.0f32,
_ => return Err(invalid()),
};
let tail = chars.as_str();
if tail.is_empty() {
return Err(invalid());
}
let magnitude = stof_prefix(tail).ok_or_else(invalid)?;
if magnitude.is_nan() {
return Err(format!(
"{value:?}: a NaN bias makes every distribution it touches NaN; frink refuses it"
));
}
let bias = magnitude * sign;
if bias == f32::INFINITY {
return Err(format!(
"{value:?}: a +inf bias leaves no finite distribution to sample (the softmax of an \
infinite logit is inf - inf); frink refuses it. Use a large finite bias"
));
}
Ok(BiasEntry { token, bias })
}
pub fn apply(entries: &[BiasEntry], logits: &mut [f32]) {
for e in entries {
if let Some(l) = usize::try_from(e.token)
.ok()
.and_then(|i| logits.get_mut(i))
{
*l += e.bias;
}
}
}
fn is_c_space(c: char) -> bool {
matches!(c, ' ' | '\t' | '\n' | '\x0b' | '\x0c' | '\r')
}
fn take_int(s: &str) -> Option<(i32, &str)> {
let b = s.as_bytes();
let mut i = usize::from(matches!(b.first(), Some(b'+' | b'-')));
let digits = i;
while b.get(i).is_some_and(u8::is_ascii_digit) {
i += 1;
}
if i == digits {
return None;
}
Some((s[..i].parse().ok()?, &s[i..]))
}
fn stof_prefix(s: &str) -> Option<f32> {
let s = s.trim_start_matches(is_c_space);
let b = s.as_bytes();
let mut i = usize::from(matches!(b.first(), Some(b'+' | b'-')));
let body = &s[i..];
let lower = body.to_ascii_lowercase();
if lower.starts_with("0x") {
return None;
}
for word in ["infinity", "inf", "nan"] {
if lower.starts_with(word) {
return s[..i + word.len()].parse().ok();
}
}
let int_start = i;
while b.get(i).is_some_and(u8::is_ascii_digit) {
i += 1;
}
let mut mantissa_digits = i - int_start;
if b.get(i) == Some(&b'.') {
let frac_start = i + 1;
let mut j = frac_start;
while b.get(j).is_some_and(u8::is_ascii_digit) {
j += 1;
}
if mantissa_digits > 0 || j > frac_start {
mantissa_digits += j - frac_start;
i = j;
}
}
if mantissa_digits == 0 {
return None;
}
let mantissa_end = i;
if matches!(b.get(i), Some(b'e' | b'E')) {
let mut j = i + 1;
if matches!(b.get(j), Some(b'+' | b'-')) {
j += 1;
}
let exp_start = j;
while b.get(j).is_some_and(u8::is_ascii_digit) {
j += 1;
}
if j > exp_start {
i = j;
}
}
let text = &s[..i];
let v: f32 = text.parse().ok()?;
let nonzero_mantissa = s[int_start..mantissa_end]
.bytes()
.any(|c| matches!(c, b'1'..=b'9'));
if v.is_infinite() || (nonzero_mantissa && (v == 0.0 || v.is_subnormal())) {
return None;
}
Some(v)
}
#[cfg(test)]
mod tests {
use super::*;
fn bias(s: &str) -> BiasEntry {
parse_entry(s).unwrap_or_else(|e| panic!("{s}: {e}"))
}
#[test]
fn llama_cpps_spellings_parse_to_llama_cpps_bias() {
let cases: &[(&str, i32, f32)] = &[
("15043+1", 15043, 1.0),
("15043-1", 15043, -1.0),
("15043-0.5", 15043, -0.5),
(" 15043 + 2", 15043, 2.0),
("15043+ 2", 15043, 2.0),
("15043+1.5x", 15043, 1.5),
("15043+-1", 15043, -1.0),
("15043--1", 15043, 1.0),
("15043+1e1", 15043, 10.0),
("15043+1e", 15043, 1.0),
("15043+.5", 15043, 0.5),
("15043+5.", 15043, 5.0),
("+7+1", 7, 1.0),
("-7+1", -7, 1.0),
];
for &(s, token, b) in cases {
assert_eq!(bias(s), BiasEntry { token, bias: b }, "{s}");
}
let ban = bias("15043-inf");
assert_eq!(ban.token, 15043);
assert_eq!(ban.bias, f32::NEG_INFINITY);
assert_eq!(bias("2-INFINITY").bias, f32::NEG_INFINITY);
}
#[test]
fn what_llama_cpp_throws_on_is_refused() {
for s in [
"",
"15043",
"15043+",
"15043*1",
"abc+1",
"15043+abc",
"15043+ ",
"+1",
"99999999999+1",
"15043+1e50",
"15043+1e-50",
"15043+.",
"15043+e5",
] {
assert!(parse_entry(s).is_err(), "{s:?} parsed");
}
}
#[test]
fn nan_plus_inf_and_hex_are_refused_by_name() {
assert!(parse_entry("1+nan").unwrap_err().contains("NaN"));
assert!(parse_entry("1+inf").unwrap_err().contains("+inf"));
assert!(parse_entry("1--inf").unwrap_err().contains("+inf"));
assert!(parse_entry("1+0x10").is_err());
}
#[test]
fn biases_add_and_out_of_vocab_ids_move_nothing() {
let entries = [
BiasEntry {
token: 1,
bias: 2.0,
},
BiasEntry {
token: 1,
bias: 0.5,
},
BiasEntry {
token: 3,
bias: f32::NEG_INFINITY,
},
BiasEntry {
token: 9,
bias: 5.0,
},
BiasEntry {
token: -1,
bias: 5.0,
},
];
let mut logits = vec![0.0f32; 4];
apply(&entries, &mut logits);
assert_eq!(logits, vec![0.0, 2.5, 0.0, f32::NEG_INFINITY]);
}
}