tokenmeter-core 0.2.0

Token counts of text in o200k_base, with the text split into token groups on grapheme boundaries
Documentation
#![doc = include_str!("../README.md")]
#![forbid(unsafe_code)]
#![warn(missing_docs)]

use std::collections::HashSet;
use std::fmt;
use std::sync::LazyLock;

use rustc_hash::FxHashMap;
use tiktoken_rs::{CoreBPE, ENDOFPROMPT, ENDOFTEXT, EncodeError, O200K_BASE_PAT_STR, Rank};
use unicode_segmentation::UnicodeSegmentation;

/// The name of the embedded encoding.
pub const ENCODING: &str = "o200k_base";

/// The largest accepted input, in UTF-8 bytes.
pub const MAX_INPUT_BYTES: usize = 1_048_576;

/// A failure to prepare the encoding or tokenize the input.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Error {
    /// The text exceeds [`MAX_INPUT_BYTES`].
    InputTooLarge,
    /// The tokenizer could not segment the input.
    Tokenization,
    /// The embedded encoding could not be initialized or returned inconsistent data.
    Internal,
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            Self::InputTooLarge => "text exceeds the UTF-8 byte limit",
            Self::Tokenization => "tokenization failed",
            Self::Internal => "internal encoding error",
        })
    }
}

impl std::error::Error for Error {}

/// One consecutive group of tokens spanning whole grapheme clusters.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Group {
    /// Exclusive UTF-8 byte offset in the original text.
    pub end: usize,
    /// Number of tokens in this group.
    pub tokens: usize,
}

/// A preview of the start of a text, with its complete token count.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Split {
    /// Number of tokens in the entire input.
    pub tokens: usize,
    /// Consecutive groups starting at byte zero, in input order.
    pub groups: Vec<Group>,
    /// Whether any text remains after the last returned group.
    pub truncated: bool,
}

static TABLE: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/o200k_base.bin"));

struct Encoding {
    core: CoreBPE,
    tokens: Vec<&'static [u8]>,
}

static ENCODING_TABLES: LazyLock<Result<Encoding, Error>> = LazyLock::new(|| {
    let mut tokens = Vec::with_capacity(200_000);
    let mut at = 0;

    while at < TABLE.len() {
        let end = at + 1 + usize::from(TABLE[at]);

        tokens.push(&TABLE[at + 1..end]);
        at = end;
    }

    let encoder: FxHashMap<Vec<u8>, Rank> =
        tokens.iter().enumerate().map(|(rank, token)| (token.to_vec(), rank as Rank)).collect();
    let special = [(ENDOFTEXT.to_owned(), 199_999), (ENDOFPROMPT.to_owned(), 200_018)].into_iter().collect();
    let core = CoreBPE::new(encoder, special, O200K_BASE_PAT_STR).map_err(|_| Error::Internal)?;

    Ok(Encoding { core, tokens })
});

fn encoding() -> Result<&'static Encoding, Error> {
    ENCODING_TABLES.as_ref().map_err(|&error| error)
}

/// Initializes the shared encoding. Later calls reuse the result.
///
/// # Errors
/// Returns [`Error::Internal`] if the encoding cannot be initialized.
pub fn prepare() -> Result<(), Error> {
    encoding().map(|_| ())
}

/// Counts tokens in the entire input using the same rules and errors as [`encode`].
pub fn count(text: &str) -> Result<usize, Error> {
    Ok(encode(text)?.len())
}

/// Returns the ordinary token IDs of `o200k_base`, including for literal special markers.
///
/// # Errors
/// Returns [`Error::InputTooLarge`] before initialization or tokenization if the UTF-8 input
/// exceeds [`MAX_INPUT_BYTES`], [`Error::Internal`] if initialization fails, and
/// [`Error::Tokenization`] if the tokenizer cannot segment the input.
pub fn encode(text: &str) -> Result<Vec<u32>, Error> {
    if text.len() > MAX_INPUT_BYTES {
        return Err(Error::InputTooLarge);
    }
    ordinary_ids(encoding()?.core.encode(text, &HashSet::new()))
}

fn ordinary_ids(result: Result<(Vec<Rank>, usize), EncodeError>) -> Result<Vec<Rank>, Error> {
    result.map(|(ids, _)| ids).map_err(|_| Error::Tokenization)
}

/// Counts the entire text and returns up to `limit` groups ending on grapheme boundaries.
/// A zero limit returns an empty preview and the full count.
///
/// # Errors
/// Returns the errors described by [`encode`], or [`Error::Internal`] for inconsistent token offsets.
pub fn split(text: &str, limit: usize) -> Result<Split, Error> {
    let ids = encode(text)?;
    let tokens = &encoding()?.tokens;
    let mut graphemes = text.grapheme_indices(true).map(|(start, grapheme)| start + grapheme.len());
    let mut boundary = 0;
    let mut groups = Vec::new();
    let mut offset = 0;
    let mut pending = 0;

    for &id in &ids {
        if groups.len() == limit {
            return Ok(Split { tokens: ids.len(), groups, truncated: true });
        }
        offset += tokens.get(id as usize).ok_or(Error::Internal)?.len();
        pending += 1;

        while boundary < offset {
            boundary = graphemes.next().ok_or(Error::Internal)?;
        }

        if boundary == offset {
            groups.push(Group { end: offset, tokens: pending });
            pending = 0;
        }
    }

    Ok(Split { tokens: ids.len(), groups, truncated: false })
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn counts_a_phrase_from_the_site() {
        assert_eq!(count("Пользователи — это наше всё."), Ok(9));
    }

    #[test]
    fn matcher_error_is_recoverable() {
        let failure = EncodeError { message: "test".to_owned() };
        assert_eq!(ordinary_ids(Err(failure)), Err(Error::Tokenization));
        assert_eq!(count("a"), Ok(1));
    }

    #[test]
    fn counts_special_tokens_as_text() -> Result<(), Error> {
        for marker in [ENDOFTEXT, ENDOFPROMPT] {
            let ids = encode(marker)?;
            assert!(ids.len() > 1);
            assert!(!ids.contains(&199_999) && !ids.contains(&200_018));
        }
        Ok(())
    }

    #[test]
    fn counts_nothing_in_empty_text() {
        assert_eq!(count(""), Ok(0));
        assert_eq!(split("", 200), Ok(Split { tokens: 0, groups: vec![], truncated: false }));
        assert_eq!(split("", 0), Ok(Split { tokens: 0, groups: vec![], truncated: false }));
    }

    #[test]
    fn groups_cover_the_text() -> Result<(), Error> {
        let text = "Съешь же ещё этих мягких французских булок, да выпей чаю.\n\n  fn main() {}";
        let split = split(text, 200)?;

        assert_eq!(split.groups.last().map(|group| group.end), Some(text.len()));
        assert_eq!(split.groups.iter().map(|group| group.tokens).sum::<usize>(), split.tokens);
        assert_eq!(split.tokens, count(text)?);
        assert!(!split.truncated);
        Ok(())
    }

    #[test]
    fn keeps_graphemes_whole_at_every_limit() -> Result<(), Error> {
        let text = "👩🏽‍💻\r\ne\u{301}🇷🇺 ไทย";
        let ends: Vec<_> = text.grapheme_indices(true).map(|(start, grapheme)| start + grapheme.len()).collect();
        let full = split(text, usize::MAX)?;
        assert_eq!(full.groups.last().map(|group| group.end), Some(text.len()));
        for group in &full.groups {
            assert!(ends.contains(&group.end));
        }
        for limit in 0..=full.groups.len() + 1 {
            let preview = split(text, limit)?;
            assert_eq!(preview.groups, full.groups[..limit.min(full.groups.len())]);
            assert_eq!(preview.tokens, full.tokens);
            assert_eq!(preview.truncated, limit < full.groups.len());
        }
        Ok(())
    }

    #[test]
    fn stops_at_the_limit_and_counts_the_rest() -> Result<(), Error> {
        let text = "слово ".repeat(1000);
        let split = split(&text, 200)?;

        assert_eq!(split.groups.len(), 200);
        assert!(split.truncated);
        assert_eq!(split.tokens, count(&text)?);
        Ok(())
    }

    #[test]
    fn enforces_the_utf8_byte_limit() -> Result<(), Error> {
        let mut text = "é ".repeat(MAX_INPUT_BYTES / 3);
        text.push('a');
        assert_eq!(text.len(), MAX_INPUT_BYTES);
        let tokens = count(&text)?;
        assert_eq!(encode(&text)?.len(), tokens);
        assert_eq!(split(&text, 0)?, Split { tokens, groups: vec![], truncated: true });

        text.push('b');
        assert_eq!(count(&text), Err(Error::InputTooLarge));
        assert_eq!(encode(&text), Err(Error::InputTooLarge));
        assert_eq!(split(&text, 1), Err(Error::InputTooLarge));
        Ok(())
    }
}