use crate::{KuteError, PayloadKind, Result, Version, VocabularyId};
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
pub const GPT4_PATTERN: &str = r"'(?i:[sdmt]|ll|ve|re)|[^\r\n\p{L}\p{N}]?+\p{L}+|\p{N}{1,3}| ?[^\s\p{L}\p{N}]++[\r\n]*|\s*[\r\n]|\s+(?!\S)|\s+";
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum Pretokenizer {
#[default]
None,
Gpt4,
Regex(String),
}
impl Pretokenizer {
pub fn pattern(&self) -> Option<&str> {
match self {
Pretokenizer::None => None,
Pretokenizer::Gpt4 => Some(GPT4_PATTERN),
Pretokenizer::Regex(p) => Some(p.as_str()),
}
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct TrainingConfig {
pub vocabulary_id: VocabularyId,
pub vocabulary_version: Version,
pub vocab_size: u32,
#[serde(default = "one")]
pub min_frequency: u64,
#[serde(default)]
pub pretokenizer: Pretokenizer,
#[serde(default)]
pub reserved_tokens: Vec<String>,
#[serde(default)]
pub max_token_length: Option<usize>,
#[serde(default = "default_window")]
pub train_window: usize,
#[serde(default)]
pub dictionary: Vec<String>,
#[serde(default)]
pub max_corpus_units: Option<u64>,
#[serde(default)]
pub seed: u64,
#[serde(default)]
pub description: Option<String>,
#[serde(default)]
pub license: Option<String>,
#[serde(default = "yes", skip_serializing_if = "is_true")]
pub embed_test_vectors: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub stream_bytes: Option<usize>,
}
fn yes() -> bool {
true
}
fn is_true(b: &bool) -> bool {
*b
}
fn one() -> u64 {
1
}
fn default_window() -> usize {
256
}
impl TrainingConfig {
pub fn new(vocabulary_id: VocabularyId, vocab_size: u32) -> Self {
Self {
vocabulary_id,
vocabulary_version: Version::new(0, 1, 0),
vocab_size,
min_frequency: 1,
pretokenizer: Pretokenizer::None,
reserved_tokens: Vec::new(),
max_token_length: None,
train_window: default_window(),
dictionary: Vec::new(),
max_corpus_units: None,
seed: 0,
description: None,
license: None,
embed_test_vectors: true,
stream_bytes: None,
}
}
pub fn validate(&self) -> Result<()> {
const MAX_VOCAB: u32 = 4_000_000;
if self.vocab_size == 0 || self.vocab_size > MAX_VOCAB {
return Err(KuteError::InvalidConfig(format!("vocab_size must be between 1 and {MAX_VOCAB}")));
}
if self.min_frequency == 0 {
return Err(KuteError::InvalidConfig("min_frequency must be at least 1".into()));
}
if self.train_window < 2 || self.train_window > 1 << 20 {
return Err(KuteError::InvalidConfig("train_window must be between 2 and 1048576".into()));
}
if self.stream_bytes.is_some_and(|n| !(4096..=1 << 30).contains(&n)) {
return Err(KuteError::InvalidConfig("stream_bytes must be between 4096 and 1073741824".into()));
}
if self.max_token_length == Some(0) {
return Err(KuteError::InvalidConfig("max_token_length must be at least 1".into()));
}
let mut seen = std::collections::BTreeSet::new();
for t in &self.reserved_tokens {
if t.is_empty() || t.len() > 256 {
return Err(KuteError::InvalidConfig("reserved tokens must be 1 to 256 bytes".into()));
}
if !seen.insert(t) {
return Err(KuteError::InvalidConfig(format!("reserved token {t:?} is listed twice")));
}
}
if let Pretokenizer::Regex(p) = &self.pretokenizer {
if p.is_empty() || p.len() > 4096 {
return Err(KuteError::InvalidConfig("pretokenizer regex must be 1 to 4096 bytes".into()));
}
}
Ok(())
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct AdapterConfig {
#[serde(flatten)]
pub options: BTreeMap<String, String>,
}
impl AdapterConfig {
pub fn with(mut self, key: &str, value: &str) -> Self {
self.options.insert(key.to_string(), value.to_string());
self
}
pub fn get(&self, key: &str) -> Option<&str> {
self.options.get(key).map(String::as_str)
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct TokenizerCapabilities {
pub algorithm: String,
pub lossless: bool,
pub trainable: bool,
pub deterministic: bool,
pub accepts: Vec<PayloadKind>,
pub rejects_unknown: bool,
pub notes: String,
}