frink-cli 0.74.0

llama.cpp-style CLI for the Frink inference engine
//! `-l` / `--logit-bias TOKEN_ID(+/-)BIAS`, llama.cpp's spelling and
//! llama.cpp's grammar.
//!
//! Upstream's parser (`common/arg.cpp`, `--logit-bias`) is a
//! `std::stringstream`: `>> llama_token` (whitespace, an optional sign,
//! decimal digits), `>> char` (whitespace, then the `+` or `-`), then
//! `std::getline` for the rest and `std::stof` on it, which skips
//! leading whitespace, reads the longest float prefix and ignores what
//! follows. So `15043+1`, `15043 - 1`, `15043-inf` and `15043+1.5x`
//! all parse there, and they parse here to the same bias.
//!
//! Where `std::stof` would throw (`ERANGE`: a magnitude past `f32`, or
//! one that underflows to a subnormal or zero), this refuses too. Three
//! values upstream accepts are refused by name, because no finite
//! distribution comes out of them: `nan`, a `+inf` bias (the softmax
//! of an infinite logit is `inf - inf`), and a hexadecimal float, which
//! `strtof` reads and Rust's float parser does not.
//!
//! Applied by `TokenStep` to the raw logits before the sampler, which
//! is where upstream's chain puts it: the logit-bias sampler is added
//! before the `--samplers` loop (`common/sampling.cpp:338-349`), so it
//! runs before the penalties. An id outside the vocabulary moves
//! nothing, as upstream's search finds no candidate for it.

/// One `TOKEN_ID(+/-)BIAS`.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct BiasEntry {
    pub token: i32,
    pub bias: f32,
}

/// clap's value parser for `--logit-bias`.
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();
    // `std::getline` fails when it extracts nothing at end of input.
    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 })
}

/// Adds every entry's bias to its token's logit, in order, so two
/// entries for one id add as upstream's do.
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;
        }
    }
}

/// C's `isspace` in the "C" locale.
fn is_c_space(c: char) -> bool {
    matches!(c, ' ' | '\t' | '\n' | '\x0b' | '\x0c' | '\r')
}

/// `istream >> int32_t`: an optional sign and at least one digit;
/// overflow fails the extraction.
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..]))
}

/// `std::stof`: leading whitespace skipped, the longest decimal float
/// prefix read, the rest ignored. `None` where `stof` throws (no
/// conversion, or `ERANGE`) and for a hexadecimal float.
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'));
    // `strtof` sets ERANGE on overflow and on an underflow to a
    // subnormal or zero, and `std::stof` turns ERANGE into a throw.
    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}"))
    }

    /// The forms `common/arg.cpp`'s help text and its stream parser
    /// accept, with the bias each one means there.
    #[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);
    }

    /// Where upstream's stream extraction or `std::stof` fails.
    #[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");
        }
    }

    /// The three values upstream reads and frink refuses by name.
    #[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());
    }

    /// Biases on one id add, an id outside the vocabulary (or negative)
    /// moves nothing, and every other logit is untouched.
    #[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]);
    }
}