use crate::error::LocalError;
use std::sync::atomic::AtomicBool;
use std::sync::Arc;
const MAX_TOKENS_DEFAULT: usize = 512;
const TEMPERATURE_DEFAULT: f32 = 0.7;
const TOP_P_DEFAULT: f32 = 0.95;
const SEED_DEFAULT: u32 = 0x5452_4B54;
const ROOT_MAX_BYTES: usize = 64;
pub trait LocalModel: Send + Sync {
fn info(&self) -> &LocalInfo;
fn tokenize(&self, text: &str, special: bool) -> Result<Vec<u32>, LocalError>;
fn detokenize(&self, tokens: &[u32]) -> Result<String, LocalError>;
fn render_chat(&self, msgs: &[ChatMessage], add_assistant: bool) -> Result<String, LocalError>;
fn generate(
&self,
prompt: &[u32],
params: &GenParams,
on_token: &mut dyn FnMut(&str) -> Flow,
) -> Result<Generation, LocalError>;
fn score(&self, tokens: &[u32]) -> Result<f64, LocalError>;
fn embed(&self, texts: &[String]) -> Result<Vec<Vec<f32>>, LocalError>;
fn reset(&self);
fn count_tokens(&self, text: &str) -> Result<usize, LocalError> {
Ok(self.tokenize(text, false)?.len())
}
}
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LocalInfo {
context_length: usize,
vocab_size: usize,
embedding_dims: usize,
chat_template: bool,
}
impl LocalInfo {
pub fn new(
context_length: usize,
vocab_size: usize,
embedding_dims: usize,
chat_template: bool,
) -> Self {
assert!(
context_length > 0,
"a model has a context of at least one token"
);
assert!(
vocab_size > 0,
"a model has at least one token in its vocabulary"
);
Self {
context_length,
vocab_size,
embedding_dims,
chat_template,
}
}
pub fn context_length(&self) -> usize {
self.context_length
}
pub fn vocab_size(&self) -> usize {
self.vocab_size
}
pub fn embedding_dims(&self) -> usize {
self.embedding_dims
}
pub fn chat_template(&self) -> bool {
self.chat_template
}
}
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ChatRole {
System,
#[default]
User,
Assistant,
Tool,
}
impl ChatRole {
pub fn as_str(&self) -> &'static str {
match self {
ChatRole::System => "system",
ChatRole::User => "user",
ChatRole::Assistant => "assistant",
ChatRole::Tool => "tool",
}
}
}
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ChatMessage {
role: ChatRole,
content: String,
}
impl ChatMessage {
pub fn new(role: ChatRole, content: impl Into<String>) -> Self {
Self {
role,
content: content.into(),
}
}
pub fn role(&self) -> ChatRole {
self.role
}
pub fn content(&self) -> &str {
&self.content
}
}
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Grammar {
gbnf: String,
root: String,
}
impl Grammar {
pub const MAX_BYTES: usize = 256 * 1024;
pub fn new(gbnf: &str, root: &str) -> Result<Self, LocalError> {
if gbnf.trim().is_empty() {
return Err(LocalError::Grammar("grammar text is empty".into()));
}
if gbnf.len() > Self::MAX_BYTES {
return Err(LocalError::Grammar(format!(
"grammar is {} bytes, limit {}",
gbnf.len(),
Self::MAX_BYTES
)));
}
if gbnf.contains('\0') {
return Err(LocalError::Grammar("grammar text holds a NUL byte".into()));
}
let root_ok = !root.is_empty()
&& root.len() <= ROOT_MAX_BYTES
&& root
.bytes()
.all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_');
if !root_ok {
return Err(LocalError::Grammar(format!(
"root rule name {root:?} is not a rule name"
)));
}
Ok(Self {
gbnf: gbnf.to_string(),
root: root.to_string(),
})
}
pub fn gbnf(&self) -> &str {
&self.gbnf
}
pub fn root(&self) -> &str {
&self.root
}
}
#[non_exhaustive]
#[derive(Debug, Clone)]
pub struct GenParams {
max_tokens: usize,
temperature: f32,
top_p: f32,
seed: u32,
stop: Vec<String>,
grammar: Option<Grammar>,
confidence: bool,
ban_eos: bool,
cancel: Option<Arc<AtomicBool>>,
}
impl Default for GenParams {
fn default() -> Self {
Self {
max_tokens: MAX_TOKENS_DEFAULT,
temperature: TEMPERATURE_DEFAULT,
top_p: TOP_P_DEFAULT,
seed: SEED_DEFAULT,
stop: Vec::new(),
grammar: None,
confidence: false,
ban_eos: false,
cancel: None,
}
}
}
impl GenParams {
pub fn with_max_tokens(mut self, max_tokens: usize) -> Self {
self.max_tokens = max_tokens;
self
}
pub fn with_temperature(mut self, temperature: f32) -> Self {
self.temperature = temperature;
self
}
pub fn with_top_p(mut self, top_p: f32) -> Self {
self.top_p = top_p;
self
}
pub fn with_seed(mut self, seed: u32) -> Self {
self.seed = seed;
self
}
pub fn with_stop(mut self, stop: Vec<String>) -> Self {
self.stop = stop;
self
}
pub fn with_grammar(mut self, grammar: Option<Grammar>) -> Self {
self.grammar = grammar;
self
}
pub fn with_confidence(mut self, confidence: bool) -> Self {
self.confidence = confidence;
self
}
pub fn with_ban_eos(mut self, ban_eos: bool) -> Self {
self.ban_eos = ban_eos;
self
}
pub fn with_cancel(mut self, cancel: Option<Arc<AtomicBool>>) -> Self {
self.cancel = cancel;
self
}
pub fn max_tokens(&self) -> usize {
self.max_tokens
}
pub fn temperature(&self) -> f32 {
self.temperature
}
pub fn top_p(&self) -> f32 {
self.top_p
}
pub fn seed(&self) -> u32 {
self.seed
}
pub fn stop(&self) -> &[String] {
&self.stop
}
pub fn grammar(&self) -> Option<&Grammar> {
self.grammar.as_ref()
}
pub fn confidence(&self) -> bool {
self.confidence
}
pub fn ban_eos(&self) -> bool {
self.ban_eos
}
pub fn cancel(&self) -> Option<&Arc<AtomicBool>> {
self.cancel.as_ref()
}
}
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum GenStop {
EndOfText,
MaxTokens,
Stop,
Cancelled,
}
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Default)]
pub struct LocalMetrics {
prefill_tokens_per_second: f64,
decode_tokens_per_second: f64,
time_to_first_token_ms: f64,
peak_ram_bytes: Option<u64>,
reused_prefix_tokens: usize,
}
impl LocalMetrics {
pub fn with_prefill_tokens_per_second(mut self, value: f64) -> Self {
self.prefill_tokens_per_second = value;
self
}
pub fn with_decode_tokens_per_second(mut self, value: f64) -> Self {
self.decode_tokens_per_second = value;
self
}
pub fn with_time_to_first_token_ms(mut self, value: f64) -> Self {
self.time_to_first_token_ms = value;
self
}
pub fn with_peak_ram_bytes(mut self, value: Option<u64>) -> Self {
self.peak_ram_bytes = value;
self
}
pub fn with_reused_prefix_tokens(mut self, value: usize) -> Self {
self.reused_prefix_tokens = value;
self
}
pub fn prefill_tokens_per_second(&self) -> f64 {
self.prefill_tokens_per_second
}
pub fn decode_tokens_per_second(&self) -> f64 {
self.decode_tokens_per_second
}
pub fn time_to_first_token_ms(&self) -> f64 {
self.time_to_first_token_ms
}
pub fn peak_ram_bytes(&self) -> Option<u64> {
self.peak_ram_bytes
}
pub fn reused_prefix_tokens(&self) -> usize {
self.reused_prefix_tokens
}
}
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq)]
pub struct Generation {
text: String,
tokens: usize,
stop: GenStop,
mean_logprob: Option<f64>,
metrics: LocalMetrics,
}
impl Generation {
pub fn new(
text: String,
tokens: usize,
stop: GenStop,
mean_logprob: Option<f64>,
metrics: LocalMetrics,
) -> Self {
if let Some(lp) = mean_logprob {
assert!(lp <= 0.0, "a mean log-probability is at most 0");
}
Self {
text,
tokens,
stop,
mean_logprob,
metrics,
}
}
pub fn text(&self) -> &str {
&self.text
}
pub fn tokens(&self) -> usize {
self.tokens
}
pub fn stop(&self) -> GenStop {
self.stop
}
pub fn mean_logprob(&self) -> Option<f64> {
self.mean_logprob
}
pub fn metrics(&self) -> &LocalMetrics {
&self.metrics
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Flow {
Continue,
Stop,
}