Linux / keyless-cuda-gate (push) Skipped
Rust port / port-typecheck (push) Failing after 8s
Desktop foundation / core (ubuntu-latest) (push) Failing after 11s
Rust port / port-oracles (push) Failing after 11s
Rust port / port-linux-tests (push) Failing after 14s
Rust port / port-fast (push) Failing after 9s
Linux / verify (push) Failing after 17s
Linux / keyless-cuda (push) Skipped
Linux / static-cuda-package (push) Skipped
Linux / hosted-cuda-package (push) Skipped
Linux / linux-static-cli (push) Skipped
Linux / linux-cli-container (push) Skipped
Linux / release-cli (push) Skipped
Brings the Rust/CUDA port of the Strata mode17 serve path together with the CPU/iGPU/NPU gpt-oss runtime that main gained meanwhile. Control plane: the Qwen tokenizer is the implementation behind the Qwen35 variant of codec::TextCodec (qwen(), encode_prompt() widen the trait; QwenCodec derefs to the tokenizer), so control-token marks, images, chat template, the runtime backend and vision keep their behavior, while the gpt-oss/Harmony path and the worker pool keep main's. Config carries the union of fields; extra_workers is rejected together with runtime, lazy_load, idle_unload_s and vision; the gpt-oss family refuses top_k/min_p/penalties (its GEN line has no such keys). leleka-kar-codec takes f16_bits_to_f32 from leleka-quant-core (identical code). Workspace members and default-members are the union of both sides. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
841 lines
29 KiB
Rust
841 lines
29 KiB
Rust
//! Native qwen35 byte-level BPE, matching the pinned Strata tokenizer oracle.
|
|
|
|
pub mod gguf_bpe;
|
|
|
|
use std::{
|
|
cmp::Reverse,
|
|
collections::{BinaryHeap, HashMap},
|
|
error::Error,
|
|
fs,
|
|
path::Path,
|
|
};
|
|
|
|
use aho_corasick::{AhoCorasick, AhoCorasickBuilder, MatchKind};
|
|
use fancy_regex::Regex;
|
|
use serde::Deserialize;
|
|
|
|
mod cache;
|
|
mod fast;
|
|
mod marks;
|
|
|
|
pub use cache::{DEFAULT_BUDGET as DEFAULT_SEGMENT_CACHE_BYTES, MIN_SEGMENT_BYTES};
|
|
pub use marks::LiteralMarks;
|
|
|
|
/// Pre-tokenization expression pinned to the Qwen35 GGUF vocabulary oracle.
|
|
pub const QWEN35_PATTERN: &str = concat!(
|
|
r"(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])",
|
|
r"|[^\r\n\p{L}\p{N}]?[\p{L}\p{M}]+",
|
|
r"|\p{N}",
|
|
r"| ?[^\s\p{L}\p{M}\p{N}]+[\r\n]*",
|
|
r"|\s*[\r\n]+",
|
|
r"|\s+(?!\S)",
|
|
r"|\s+",
|
|
);
|
|
|
|
type Result<T> = std::result::Result<T, Box<dyn Error>>;
|
|
|
|
/// The `qwen35` pre-tokenizer alone: the pieces `text` is split into before byte-level BPE. Exposed so the split can
|
|
/// be compared with Python's `regex` for every Unicode scalar value (scripts/offline/diff_tokenizer.py).
|
|
pub fn pre_tokenize(text: &str) -> Result<Vec<&str>> {
|
|
static PATTERN: std::sync::OnceLock<Regex> = std::sync::OnceLock::new();
|
|
let pattern = match PATTERN.get() {
|
|
Some(pattern) => pattern,
|
|
None => PATTERN.get_or_init(|| Regex::new(QWEN35_PATTERN).expect("pinned qwen35 pattern")),
|
|
};
|
|
let mut pieces = Vec::new();
|
|
for found in pattern.find_iter(text) {
|
|
pieces.push(found?.as_str());
|
|
}
|
|
Ok(pieces)
|
|
}
|
|
|
|
/// [`pre_tokenize`] by the hand-written scanner the tokenizer's fast path uses (same pieces; exposed for the differential tests).
|
|
#[doc(hidden)]
|
|
pub fn pre_tokenize_fast(text: &str) -> Vec<&str> {
|
|
static CLASSES: std::sync::OnceLock<fast::Classes> = std::sync::OnceLock::new();
|
|
let classes = CLASSES.get_or_init(|| fast::Classes::new().expect("unicode classes"));
|
|
let mut pieces = Vec::new();
|
|
let mut at = 0;
|
|
while at < text.len() {
|
|
let end = classes.piece_end(text, at);
|
|
pieces.push(&text[at..end]);
|
|
at = end;
|
|
}
|
|
pieces
|
|
}
|
|
|
|
#[derive(Deserialize)]
|
|
struct Config {
|
|
model: String,
|
|
pre: String,
|
|
vocab_size: usize,
|
|
n_merges: usize,
|
|
pre_pattern: String,
|
|
special_ids: HashMap<String, u32>,
|
|
}
|
|
|
|
struct LiteralMatcher {
|
|
search: AhoCorasick,
|
|
ids: Vec<u32>,
|
|
}
|
|
|
|
/// The bytes of every token, flat, for decoding without a hash lookup per character.
|
|
struct DecodeTable {
|
|
bytes: Vec<u8>,
|
|
starts: Vec<u32>,
|
|
/// Tokens with a character outside the byte alphabet (decoding them is an error, as it always was).
|
|
outside: Vec<bool>,
|
|
}
|
|
|
|
impl DecodeTable {
|
|
fn new(tokens: &[String], char_bytes: &HashMap<char, u8>) -> Self {
|
|
let mut bytes = Vec::new();
|
|
let mut starts = Vec::with_capacity(tokens.len() + 1);
|
|
let mut outside = Vec::with_capacity(tokens.len());
|
|
for token in tokens {
|
|
starts.push(bytes.len() as u32);
|
|
let mark = bytes.len();
|
|
let mut bad = false;
|
|
for ch in token.chars() {
|
|
match char_bytes.get(&ch) {
|
|
Some(&byte) => bytes.push(byte),
|
|
None => {
|
|
bad = true;
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
if bad {
|
|
bytes.truncate(mark);
|
|
}
|
|
outside.push(bad);
|
|
}
|
|
starts.push(bytes.len() as u32);
|
|
Self {
|
|
bytes,
|
|
starts,
|
|
outside,
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
fn empty() -> Self {
|
|
Self {
|
|
bytes: Vec::new(),
|
|
starts: vec![0],
|
|
outside: Vec::new(),
|
|
}
|
|
}
|
|
|
|
#[inline]
|
|
fn token(&self, id: u32) -> Result<&[u8]> {
|
|
let index = id as usize;
|
|
if index >= self.outside.len() {
|
|
return Err("token ID exceeds vocabulary".into());
|
|
}
|
|
if self.outside[index] {
|
|
return Err("token is outside byte alphabet".into());
|
|
}
|
|
Ok(&self.bytes[self.starts[index] as usize..self.starts[index + 1] as usize])
|
|
}
|
|
}
|
|
|
|
pub struct Tokenizer {
|
|
vocab: HashMap<String, u32>,
|
|
ranks: HashMap<String, usize>,
|
|
pattern: Regex,
|
|
always: Option<LiteralMatcher>,
|
|
special: Option<LiteralMatcher>,
|
|
marks: LiteralMarks,
|
|
byte_chars: [char; 256],
|
|
decode_table: DecodeTable,
|
|
/// Table-driven pre-tokenizer and BPE; `None` for a vocabulary it cannot reproduce exactly.
|
|
fast: Option<fast::Fast>,
|
|
segments: cache::SegmentCache,
|
|
}
|
|
|
|
impl Tokenizer {
|
|
pub fn from_assets(path: &Path) -> Result<Self> {
|
|
let config: Config = serde_json::from_slice(&fs::read(path.join("tokenizer.json"))?)?;
|
|
if config.model != "gpt2" || config.pre != "qwen35" || config.pre_pattern != QWEN35_PATTERN
|
|
{
|
|
return Err("unsupported tokenizer model, pre-tokenizer, or pattern".into());
|
|
}
|
|
let vocab: HashMap<String, u32> =
|
|
serde_json::from_slice(&fs::read(path.join("vocab.json"))?)?;
|
|
if vocab.len() != config.vocab_size || vocab.is_empty() {
|
|
return Err("tokenizer vocabulary size mismatch".into());
|
|
}
|
|
let mut ordered = vec![None; vocab.len()];
|
|
for (token, &id) in &vocab {
|
|
let slot = ordered
|
|
.get_mut(id as usize)
|
|
.ok_or("tokenizer ID exceeds vocabulary length")?;
|
|
if slot.replace(token.clone()).is_some() {
|
|
return Err("duplicate tokenizer ID".into());
|
|
}
|
|
}
|
|
let tokens = ordered
|
|
.into_iter()
|
|
.collect::<Option<Vec<_>>>()
|
|
.ok_or("tokenizer IDs are not contiguous")?;
|
|
if tokens.iter().any(|token| token.contains('\0')) {
|
|
return Err("tokenizer vocabulary contains a NUL character".into());
|
|
}
|
|
let merge_text = fs::read_to_string(path.join("merges.txt"))?;
|
|
let merges: Vec<&str> = if merge_text.is_empty() {
|
|
Vec::new()
|
|
} else {
|
|
merge_text.split('\n').collect()
|
|
};
|
|
if merges.len() != config.n_merges {
|
|
return Err("tokenizer merge count mismatch".into());
|
|
}
|
|
let token_types: Option<Vec<u32>> =
|
|
serde_json::from_slice(&fs::read(path.join("token_type.json"))?)?;
|
|
if token_types
|
|
.as_ref()
|
|
.is_some_and(|types| types.len() != tokens.len())
|
|
{
|
|
return Err("token type count mismatch".into());
|
|
}
|
|
for &id in config.special_ids.values() {
|
|
if id as usize >= tokens.len() {
|
|
return Err("special token ID exceeds vocabulary".into());
|
|
}
|
|
}
|
|
drop(vocab);
|
|
Self::from_vocabulary(
|
|
&config.model,
|
|
&config.pre,
|
|
tokens,
|
|
merges.into_iter().map(str::to_owned).collect(),
|
|
token_types,
|
|
)
|
|
}
|
|
|
|
/// Construct the same tokenizer from already verified model metadata.
|
|
pub fn from_vocabulary(
|
|
model: &str,
|
|
pre: &str,
|
|
tokens: Vec<String>,
|
|
merges: Vec<String>,
|
|
token_types: Option<Vec<u32>>,
|
|
) -> Result<Self> {
|
|
if model != "gpt2" || pre != "qwen35" {
|
|
return Err("unsupported tokenizer configuration".into());
|
|
}
|
|
if tokens.is_empty() || tokens.len() > u32::MAX as usize {
|
|
return Err("vocabulary size mismatch".into());
|
|
}
|
|
let mut vocab = HashMap::with_capacity(tokens.len());
|
|
for (id, token) in tokens.iter().enumerate() {
|
|
if token.is_empty()
|
|
|| token.contains('\0')
|
|
|| vocab.insert(token.clone(), id as u32).is_some()
|
|
{
|
|
return Err("vocabulary contains NUL or duplicate tokens".into());
|
|
}
|
|
}
|
|
if token_types
|
|
.as_ref()
|
|
.is_some_and(|types| types.len() != tokens.len())
|
|
{
|
|
return Err("token type count mismatch".into());
|
|
}
|
|
let mut ranks = HashMap::with_capacity(merges.len());
|
|
for (rank, merge) in merges.iter().enumerate() {
|
|
let Some((left, right)) = merge.split_once(' ') else {
|
|
return Err("BPE merge is not a pair".into());
|
|
};
|
|
if left.is_empty()
|
|
|| right.is_empty()
|
|
|| right.contains(' ')
|
|
|| !vocab.contains_key(left)
|
|
|| !vocab.contains_key(right)
|
|
|| ranks.insert(pair_key(left, right), rank).is_some()
|
|
{
|
|
return Err("BPE merge is invalid or duplicated".into());
|
|
}
|
|
}
|
|
let types = token_types.unwrap_or_default();
|
|
let always = literal_matcher(&tokens, &types, false)?;
|
|
let special = literal_matcher(&tokens, &types, true)?;
|
|
let marks = LiteralMarks::new(
|
|
types
|
|
.iter()
|
|
.enumerate()
|
|
.filter(|(_, kind)| matches!(**kind, 3 | 4))
|
|
.map(|(id, _)| tokens[id].as_str()),
|
|
)?;
|
|
let pattern = Regex::new(QWEN35_PATTERN)?;
|
|
let (byte_chars, char_bytes) = byte_alphabet();
|
|
let pairs: Vec<(String, String)> = merges
|
|
.iter()
|
|
.filter_map(|merge| merge.split_once(' '))
|
|
.map(|(left, right)| (left.to_owned(), right.to_owned()))
|
|
.collect();
|
|
// Kill switches for an operator who suspects the fast path: `LELEKA_TOKENIZER_REFERENCE=1` runs the original
|
|
// implementation only; `LELEKA_TOKENIZER_SEGMENT_CACHE_MIB=n` sizes the segment cache (0 turns it off).
|
|
let reference_only =
|
|
std::env::var_os("LELEKA_TOKENIZER_REFERENCE").is_some_and(|v| v == "1");
|
|
let fast = if reference_only {
|
|
None
|
|
} else {
|
|
fast::Fast::build(&vocab, &pairs, &byte_chars)
|
|
};
|
|
let cache_budget = std::env::var("LELEKA_TOKENIZER_SEGMENT_CACHE_MIB")
|
|
.ok()
|
|
.and_then(|value| value.parse::<usize>().ok())
|
|
.map_or(cache::DEFAULT_BUDGET, |mib| mib << 20);
|
|
let decode_table = DecodeTable::new(&tokens, &char_bytes);
|
|
Ok(Self {
|
|
vocab,
|
|
ranks,
|
|
pattern,
|
|
always,
|
|
special,
|
|
marks,
|
|
byte_chars,
|
|
decode_table,
|
|
fast,
|
|
segments: cache::SegmentCache::new(cache_budget),
|
|
})
|
|
}
|
|
|
|
/// Bound the cache of segment encodings (bytes of text and ids; 0 turns it off). The default is
|
|
/// [`DEFAULT_SEGMENT_CACHE_BYTES`].
|
|
pub fn set_segment_cache_bytes(&self, budget: usize) {
|
|
self.segments.set_budget(budget);
|
|
}
|
|
|
|
/// (segments, approximate bytes) held by the segment cache.
|
|
pub fn segment_cache_stats(&self) -> (usize, usize) {
|
|
self.segments.stats()
|
|
}
|
|
|
|
/// Whether the table-driven path is in use (it is for every real vocabulary).
|
|
pub fn has_fast_path(&self) -> bool {
|
|
self.fast.is_some()
|
|
}
|
|
|
|
pub fn special_id(&self, token: &str) -> Option<u32> {
|
|
self.vocab.get(token).copied()
|
|
}
|
|
|
|
/// The marks that keep a special literal inside a message from becoming a special token (see [`LiteralMarks`]).
|
|
pub fn marks(&self) -> &LiteralMarks {
|
|
&self.marks
|
|
}
|
|
|
|
/// Token ids of a rendered prompt whose message text went through [`LiteralMarks::mark`] before the chat template ran:
|
|
/// the literals the template wrote parse as special tokens, exactly as `encode(prompt, true)` does, and every mark
|
|
/// is turned back into its literal and encoded as ordinary text. For a prompt without marks this is
|
|
/// `encode(prompt, true)`. The token count of a prompt is the length of this, never of `encode(.., true)` on the
|
|
/// marked text and never of the unmarked one.
|
|
pub fn encode_marked(&self, text: &str) -> Result<Vec<u32>> {
|
|
let mut ids = Vec::with_capacity(text.len() / 3 + 16);
|
|
self.encode_marked_into(text, &mut ids)?;
|
|
Ok(ids)
|
|
}
|
|
|
|
/// [`Tokenizer::encode_marked`] appending to `ids`.
|
|
pub fn encode_marked_into(&self, text: &str, ids: &mut Vec<u32>) -> Result<()> {
|
|
let Some(matcher) = &self.special else {
|
|
let plain = self.marks.unmark(text);
|
|
return self.encode_segment(&plain, ids, &mut fast::Scratch::default());
|
|
};
|
|
let mut scratch = fast::Scratch::default();
|
|
let mut offset = 0;
|
|
for found in matcher.search.find_iter(text) {
|
|
let plain = self.marks.unmark(&text[offset..found.start()]);
|
|
self.encode_segment(&plain, ids, &mut scratch)?;
|
|
ids.push(matcher.ids[found.pattern().as_usize()]);
|
|
offset = found.end();
|
|
}
|
|
let plain = self.marks.unmark(&text[offset..]);
|
|
self.encode_segment(&plain, ids, &mut scratch)
|
|
}
|
|
|
|
/// Token ids of `text` as ordinary text: no literal is parsed, not even the user-defined ones that
|
|
/// `encode(text, false)` still matches.
|
|
pub fn encode_plain_text(&self, text: &str) -> Result<Vec<u32>> {
|
|
let mut ids = Vec::with_capacity(text.len() / 3 + 16);
|
|
self.encode_segment(text, &mut ids, &mut fast::Scratch::default())?;
|
|
Ok(ids)
|
|
}
|
|
|
|
/// Token ids of `text`. Text between special tokens is looked up in the segment cache first; whatever the cache or the
|
|
/// fast path does, the ids are the ones [`Tokenizer::encode_reference`] returns.
|
|
pub fn encode(&self, text: &str, parse_special: bool) -> Result<Vec<u32>> {
|
|
let mut ids = Vec::with_capacity(text.len() / 3 + 16);
|
|
self.encode_into(text, parse_special, &mut ids)?;
|
|
Ok(ids)
|
|
}
|
|
|
|
/// [`Tokenizer::encode`] appending to `ids`.
|
|
pub fn encode_into(&self, text: &str, parse_special: bool, ids: &mut Vec<u32>) -> Result<()> {
|
|
let matcher = if parse_special {
|
|
&self.special
|
|
} else {
|
|
&self.always
|
|
};
|
|
let mut scratch = fast::Scratch::default();
|
|
let Some(matcher) = matcher else {
|
|
return self.encode_segment(text, ids, &mut scratch);
|
|
};
|
|
let mut offset = 0;
|
|
for found in matcher.search.find_iter(text) {
|
|
self.encode_segment(&text[offset..found.start()], ids, &mut scratch)?;
|
|
ids.push(matcher.ids[found.pattern().as_usize()]);
|
|
offset = found.end();
|
|
}
|
|
self.encode_segment(&text[offset..], ids, &mut scratch)
|
|
}
|
|
|
|
/// Text without special tokens: cache, then the fast path, then the string BPE.
|
|
fn encode_segment(
|
|
&self,
|
|
text: &str,
|
|
ids: &mut Vec<u32>,
|
|
scratch: &mut fast::Scratch,
|
|
) -> Result<()> {
|
|
if text.is_empty() {
|
|
return Ok(());
|
|
}
|
|
let Some(fast) = &self.fast else {
|
|
ids.extend(self.encode_plain(text)?);
|
|
return Ok(());
|
|
};
|
|
let key = if text.len() >= cache::MIN_SEGMENT_BYTES {
|
|
match self.segments.lookup(text) {
|
|
(_, Some(hit)) => {
|
|
ids.extend_from_slice(&hit);
|
|
return Ok(());
|
|
}
|
|
(key, None) => Some(key),
|
|
}
|
|
} else {
|
|
None
|
|
};
|
|
let mark = ids.len();
|
|
let mut at = 0;
|
|
while at < text.len() {
|
|
let end = fast.classes.piece_end(text, at);
|
|
fast.encode_piece(&text.as_bytes()[at..end], ids, scratch);
|
|
at = end;
|
|
}
|
|
if let Some(key) = key {
|
|
self.segments.insert(key, text, &ids[mark..]);
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
/// The original implementation (regex pre-tokenizer, string BPE, no cache): the oracle the fast path is tested against.
|
|
#[doc(hidden)]
|
|
pub fn encode_reference(&self, text: &str, parse_special: bool) -> Result<Vec<u32>> {
|
|
let matcher = if parse_special {
|
|
&self.special
|
|
} else {
|
|
&self.always
|
|
};
|
|
let Some(matcher) = matcher else {
|
|
return self.encode_plain(text);
|
|
};
|
|
let mut ids = Vec::new();
|
|
let mut offset = 0;
|
|
for found in matcher.search.find_iter(text) {
|
|
ids.extend(self.encode_plain(&text[offset..found.start()])?);
|
|
ids.push(matcher.ids[found.pattern().as_usize()]);
|
|
offset = found.end();
|
|
}
|
|
ids.extend(self.encode_plain(&text[offset..])?);
|
|
Ok(ids)
|
|
}
|
|
|
|
pub fn decode(&self, ids: &[u32]) -> Result<String> {
|
|
Ok(String::from_utf8_lossy(&self.decode_bytes(ids)?).into_owned())
|
|
}
|
|
|
|
pub fn decode_bytes(&self, ids: &[u32]) -> Result<Vec<u8>> {
|
|
let mut bytes = Vec::with_capacity(ids.len() * 4);
|
|
for &id in ids {
|
|
bytes.extend_from_slice(self.decode_table.token(id)?);
|
|
}
|
|
Ok(bytes)
|
|
}
|
|
|
|
/// Whether `ids` decode to exactly `text`, without building the decoded bytes. An id that cannot be decoded is `false`.
|
|
pub fn decodes_to(&self, ids: &[u32], text: &[u8]) -> bool {
|
|
let mut at = 0;
|
|
for &id in ids {
|
|
let Ok(token) = self.decode_table.token(id) else {
|
|
return false;
|
|
};
|
|
if text.len() - at < token.len() || &text[at..at + token.len()] != token {
|
|
return false;
|
|
}
|
|
at += token.len();
|
|
}
|
|
at == text.len()
|
|
}
|
|
|
|
fn encode_plain(&self, text: &str) -> Result<Vec<u32>> {
|
|
let mut ids = Vec::new();
|
|
let mut offset = 0;
|
|
for found in self.pattern.find_iter(text) {
|
|
let piece = found?;
|
|
if piece.start() != offset || piece.end() == offset {
|
|
return Err("qwen35 pre-tokenizer left an unmatched text span".into());
|
|
}
|
|
let mapped: String = piece
|
|
.as_str()
|
|
.as_bytes()
|
|
.iter()
|
|
.map(|byte| self.byte_chars[*byte as usize])
|
|
.collect();
|
|
let parts = if mapped.chars().count() > 64 {
|
|
self.bpe_heap(&mapped)
|
|
} else {
|
|
self.bpe_scan(&mapped)
|
|
};
|
|
for token in parts {
|
|
ids.push(
|
|
*self
|
|
.vocab
|
|
.get(&token)
|
|
.ok_or("BPE produced a token outside the vocabulary")?,
|
|
);
|
|
}
|
|
offset = piece.end();
|
|
}
|
|
if offset != text.len() {
|
|
return Err("qwen35 pre-tokenizer left an unmatched text suffix".into());
|
|
}
|
|
Ok(ids)
|
|
}
|
|
|
|
fn rank(&self, left: &str, right: &str) -> Option<usize> {
|
|
self.ranks.get(&pair_key(left, right)).copied()
|
|
}
|
|
|
|
fn bpe_scan(&self, word: &str) -> Vec<String> {
|
|
let mut parts: Vec<String> = word.chars().map(|ch| ch.to_string()).collect();
|
|
while parts.len() > 1 {
|
|
let mut best = None;
|
|
for index in 0..parts.len() - 1 {
|
|
if let Some(rank) = self.rank(&parts[index], &parts[index + 1])
|
|
&& best.is_none_or(|(_, current)| rank < current)
|
|
{
|
|
best = Some((index, rank));
|
|
}
|
|
}
|
|
let Some((index, _)) = best else { break };
|
|
let right = parts.remove(index + 1);
|
|
parts[index].push_str(&right);
|
|
}
|
|
parts
|
|
}
|
|
|
|
fn bpe_heap(&self, word: &str) -> Vec<String> {
|
|
let mut nodes: Vec<Node> = word
|
|
.chars()
|
|
.enumerate()
|
|
.map(|(index, ch)| Node {
|
|
text: ch.to_string(),
|
|
prev: index.checked_sub(1),
|
|
next: Some(index + 1),
|
|
version: 0,
|
|
alive: true,
|
|
})
|
|
.collect();
|
|
if let Some(last) = nodes.last_mut() {
|
|
last.next = None;
|
|
}
|
|
let mut heap = BinaryHeap::new();
|
|
for left in 0..nodes.len().saturating_sub(1) {
|
|
self.push_pair(&nodes, left, &mut heap);
|
|
}
|
|
while let Some(Reverse((_, left, right, left_version, right_version))) = heap.pop() {
|
|
if !nodes[left].alive
|
|
|| !nodes[right].alive
|
|
|| nodes[left].next != Some(right)
|
|
|| nodes[left].version != left_version
|
|
|| nodes[right].version != right_version
|
|
{
|
|
continue;
|
|
}
|
|
let successor = nodes[right].next;
|
|
let merged = std::mem::take(&mut nodes[right].text);
|
|
nodes[left].text.push_str(&merged);
|
|
nodes[left].next = successor;
|
|
nodes[left].version += 1;
|
|
nodes[right].alive = false;
|
|
if let Some(next) = successor {
|
|
nodes[next].prev = Some(left);
|
|
}
|
|
self.push_pair(&nodes, left, &mut heap);
|
|
if let Some(prev) = nodes[left].prev {
|
|
self.push_pair(&nodes, prev, &mut heap);
|
|
}
|
|
}
|
|
let mut parts = Vec::new();
|
|
let mut current = (!nodes.is_empty()).then_some(0);
|
|
while let Some(index) = current {
|
|
parts.push(std::mem::take(&mut nodes[index].text));
|
|
current = nodes[index].next;
|
|
}
|
|
parts
|
|
}
|
|
|
|
fn push_pair(&self, nodes: &[Node], left: usize, heap: &mut BinaryHeap<Reverse<HeapEntry>>) {
|
|
if let Some(right) = nodes[left].next
|
|
&& let Some(rank) = self.rank(&nodes[left].text, &nodes[right].text)
|
|
{
|
|
heap.push(Reverse((
|
|
rank,
|
|
left,
|
|
right,
|
|
nodes[left].version,
|
|
nodes[right].version,
|
|
)));
|
|
}
|
|
}
|
|
}
|
|
|
|
type HeapEntry = (usize, usize, usize, u64, u64);
|
|
|
|
struct Node {
|
|
text: String,
|
|
prev: Option<usize>,
|
|
next: Option<usize>,
|
|
version: u64,
|
|
alive: bool,
|
|
}
|
|
|
|
fn pair_key(left: &str, right: &str) -> String {
|
|
let mut key = String::with_capacity(left.len() + right.len() + 1);
|
|
key.push_str(left);
|
|
key.push('\0');
|
|
key.push_str(right);
|
|
key
|
|
}
|
|
|
|
fn literal_matcher(
|
|
tokens: &[String],
|
|
types: &[u32],
|
|
include_control: bool,
|
|
) -> Result<Option<LiteralMatcher>> {
|
|
let selected: Vec<(u32, &str)> = types
|
|
.iter()
|
|
.enumerate()
|
|
.filter(|(_, kind)| **kind == 4 || (include_control && **kind == 3))
|
|
.map(|(id, _)| (id as u32, tokens[id].as_str()))
|
|
.collect();
|
|
if selected.iter().any(|(_, token)| token.is_empty()) {
|
|
return Err("empty special token literal".into());
|
|
}
|
|
if selected.is_empty() {
|
|
return Ok(None);
|
|
}
|
|
let ids = selected.iter().map(|(id, _)| *id).collect();
|
|
let search = AhoCorasickBuilder::new()
|
|
.match_kind(MatchKind::LeftmostLongest)
|
|
.build(selected.iter().map(|(_, token)| *token))?;
|
|
Ok(Some(LiteralMatcher { search, ids }))
|
|
}
|
|
|
|
#[doc(hidden)]
|
|
pub fn byte_alphabet() -> ([char; 256], HashMap<char, u8>) {
|
|
let mut chars = ['\0'; 256];
|
|
for byte in (0x21..=0x7e).chain(0xa1..=0xac).chain(0xae..=0xff) {
|
|
chars[byte] = char::from_u32(byte as u32).expect("byte code point");
|
|
}
|
|
let mut next = 0;
|
|
for mapped in &mut chars {
|
|
if *mapped == '\0' {
|
|
*mapped = char::from_u32(256 + next).expect("shifted byte code point");
|
|
next += 1;
|
|
}
|
|
}
|
|
let reverse = chars
|
|
.iter()
|
|
.enumerate()
|
|
.map(|(byte, &ch)| (ch, byte as u8))
|
|
.collect();
|
|
(chars, reverse)
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
use serde_json::json;
|
|
|
|
#[test]
|
|
fn verified_vocabulary_constructor_rejects_invalid_metadata() {
|
|
let build = |tokens, merges, types| {
|
|
Tokenizer::from_vocabulary("gpt2", "qwen35", tokens, merges, types)
|
|
};
|
|
assert!(build(vec![], vec![], None).is_err());
|
|
assert!(build(vec![String::new()], vec![], None).is_err());
|
|
assert!(build(vec!["a".into(), "a".into()], vec![], None).is_err());
|
|
assert!(build(vec!["a\0".into()], vec![], None).is_err());
|
|
assert!(build(vec!["a".into()], vec![], Some(vec![])).is_err());
|
|
assert!(build(vec!["a".into()], vec!["a missing".into()], None).is_err());
|
|
assert!(
|
|
Tokenizer::from_vocabulary("unknown", "qwen35", vec!["a".into()], vec![], None)
|
|
.is_err()
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn byte_alphabet_is_bijective() {
|
|
let (forward, reverse) = byte_alphabet();
|
|
assert_eq!(reverse.len(), 256);
|
|
for (byte, ch) in forward.iter().enumerate() {
|
|
assert_eq!(reverse[ch], byte as u8);
|
|
}
|
|
assert_eq!(forward[b' ' as usize], 'Ġ');
|
|
}
|
|
|
|
#[test]
|
|
fn heap_and_scan_choose_the_same_rank_order() {
|
|
let mut ranks = HashMap::new();
|
|
ranks.insert(pair_key("a", "b"), 1);
|
|
ranks.insert(pair_key("b", "a"), 2);
|
|
ranks.insert(pair_key("ab", "a"), 3);
|
|
let (byte_chars, _) = byte_alphabet();
|
|
let tokenizer = Tokenizer {
|
|
vocab: HashMap::new(),
|
|
ranks,
|
|
pattern: Regex::new(QWEN35_PATTERN).unwrap(),
|
|
always: None,
|
|
special: None,
|
|
marks: LiteralMarks::none(),
|
|
byte_chars,
|
|
decode_table: DecodeTable::empty(),
|
|
fast: None,
|
|
segments: cache::SegmentCache::new(0),
|
|
};
|
|
for word in [
|
|
"aba",
|
|
"ababa",
|
|
"aaabbb",
|
|
"abababab",
|
|
"ab".repeat(100).as_str(),
|
|
] {
|
|
assert_eq!(tokenizer.bpe_scan(word), tokenizer.bpe_heap(word));
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn qwen35_matches_oracle_ids_for_merges_unicode_and_specials() {
|
|
let root = std::env::temp_dir().join(format!("strata-bpe-test-{}", std::process::id()));
|
|
let _ = fs::remove_dir_all(&root);
|
|
fs::create_dir(&root).unwrap();
|
|
let (alphabet, _) = byte_alphabet();
|
|
let mut tokens: Vec<String> = alphabet.iter().map(char::to_string).collect();
|
|
tokens.extend(
|
|
[
|
|
"He",
|
|
"Hel",
|
|
"ll",
|
|
"llo",
|
|
"xx",
|
|
"xxxx",
|
|
"<|im_end|>",
|
|
"<tool_response>",
|
|
]
|
|
.map(str::to_owned),
|
|
);
|
|
let vocab: HashMap<_, _> = tokens
|
|
.iter()
|
|
.enumerate()
|
|
.map(|(id, token)| (token, id as u32))
|
|
.collect();
|
|
let mut types = vec![1; tokens.len()];
|
|
types[262] = 3;
|
|
types[263] = 4;
|
|
fs::write(root.join("vocab.json"), serde_json::to_vec(&vocab).unwrap()).unwrap();
|
|
fs::write(root.join("merges.txt"), "H e\nHe l\nl l\nll o\nx x\nxx xx").unwrap();
|
|
fs::write(
|
|
root.join("token_type.json"),
|
|
serde_json::to_vec(&types).unwrap(),
|
|
)
|
|
.unwrap();
|
|
fs::write(
|
|
root.join("tokenizer.json"),
|
|
serde_json::to_vec(&json!({
|
|
"model": "gpt2", "pre": "qwen35", "vocab_size": tokens.len(),
|
|
"n_merges": 6, "pre_pattern": QWEN35_PATTERN,
|
|
"special_ids": {"tokenizer.ggml.eos_token_id": 262},
|
|
}))
|
|
.unwrap(),
|
|
)
|
|
.unwrap();
|
|
let tokenizer = Tokenizer::from_assets(&root).unwrap();
|
|
let retained = Tokenizer::from_vocabulary(
|
|
"gpt2",
|
|
"qwen35",
|
|
tokens,
|
|
"H e\nHe l\nl l\nll o\nx x\nxx xx"
|
|
.split('\n')
|
|
.map(str::to_owned)
|
|
.collect(),
|
|
Some(types),
|
|
)
|
|
.unwrap();
|
|
for text in [
|
|
"Hello, world!",
|
|
"😀",
|
|
"<|im_end|>",
|
|
"<tool_response>",
|
|
"e\u{301}",
|
|
] {
|
|
for special in [false, true] {
|
|
assert_eq!(
|
|
tokenizer.encode(text, special).unwrap(),
|
|
retained.encode(text, special).unwrap()
|
|
);
|
|
}
|
|
}
|
|
assert_eq!(
|
|
tokenizer.encode("Hello, world!", false).unwrap(),
|
|
vec![257, 108, 111, 44, 32, 119, 111, 114, 108, 100, 33]
|
|
);
|
|
assert_eq!(
|
|
tokenizer
|
|
.encode("e\u{301}\u{301} combining", false)
|
|
.unwrap(),
|
|
vec![
|
|
101, 204, 129, 204, 129, 32, 99, 111, 109, 98, 105, 110, 105, 110, 103
|
|
]
|
|
);
|
|
assert_eq!(
|
|
tokenizer.encode("<|im_end|>", false).unwrap(),
|
|
vec![60, 124, 105, 109, 95, 101, 110, 100, 124, 62]
|
|
);
|
|
assert_eq!(tokenizer.encode("<|im_end|>", true).unwrap(), vec![262]);
|
|
assert_eq!(
|
|
tokenizer.encode("<tool_response>", false).unwrap(),
|
|
vec![263]
|
|
);
|
|
assert_eq!(tokenizer.decode(&[226]).unwrap(), "�");
|
|
assert_eq!(tokenizer.decode_bytes(&[226]).unwrap(), vec![226]);
|
|
assert_eq!(
|
|
tokenizer.encode(&"x".repeat(65), false).unwrap(),
|
|
[vec![261; 16], vec![120]].concat()
|
|
);
|
|
for sample in [
|
|
"你好,世界",
|
|
"😀🚀🇺🇸",
|
|
"\0\x01\x7f",
|
|
"x".repeat(5000).as_str(),
|
|
] {
|
|
let ids = tokenizer.encode(sample, false).unwrap();
|
|
assert_eq!(tokenizer.decode(&ids).unwrap(), sample);
|
|
}
|
|
fs::remove_dir_all(root).unwrap();
|
|
}
|
|
}
|