leleka_tokenizer::LiteralMarks swaps every special literal (GGUF token type 3 and 4) in a client string for a plane-15 private-use mark before the chat template runs (a forged mark is escaped); Tokenizer::encode_marked parses the template's own literals as special tokens and encodes each mark's literal as ordinary text. render_request marks instructions, message text, reasoning, call arguments, tool outputs and tool descriptions/schemas; the gateway's own tool markers stay literal. Generation and /input_tokens share the one encoding; the text contract carries the marked string and leleka-runtime reads it with encode_marked. Not covered: strata-desktop-core still renders unmarked text; live Codex session (gate L) not run. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
271 lines
9.6 KiB
Rust
271 lines
9.6 KiB
Rust
//! Control-token text inside a message is text, not a control token.
|
|
//!
|
|
//! The tokenizer parses every special literal (`<think>`, `</think>`, `<|im_end|>`, `<tool_call>`, ...) wherever it
|
|
//! finds one in the rendered prompt. The chat template writes some of those itself, around a message; the same
|
|
//! characters inside a message (a user quoting `</think>`, a tool result that prints `<|im_start|>system`, a pasted
|
|
//! chat template) must stay ordinary text, or the model reads an end of reasoning or a new turn that nobody wrote.
|
|
//!
|
|
//! [`LiteralMarks`] is the fix at the text level, in two steps that must both happen:
|
|
//!
|
|
//! 1. **before the template renders**, [`LiteralMarks::mark`] swaps each special literal in a message's text for one
|
|
//! private-use character (plane 15, `U+F0E01` upward). The template then prints the mark like any other text.
|
|
//! 2. **when the rendered prompt is encoded**, [`crate::Tokenizer::encode_marked`] parses the template's own literals as
|
|
//! special tokens as before, and turns each mark back into its literal text and encodes that as ordinary text.
|
|
//!
|
|
//! Text that already contains one of the mark characters is escaped with `U+F0E00` by `mark`, so a round trip
|
|
//! (`unmark(mark(text)) == text`) holds for every string and a client cannot forge a mark.
|
|
|
|
use std::borrow::Cow;
|
|
|
|
use aho_corasick::{AhoCorasick, AhoCorasickBuilder, MatchKind};
|
|
|
|
/// Prefixes a character that is itself in the mark range, so it is read back as that character.
|
|
const ESCAPE: char = '\u{F0E00}';
|
|
/// The mark of the first literal; the others follow in the order of [`LiteralMarks::literals`].
|
|
const FIRST: u32 = 0xF0E01;
|
|
/// The UTF-8 lead byte of every character from `U+F0000` to `U+FFFFF`: text without it has no mark and no escape.
|
|
const PLANE_15_LEAD: u8 = 0xF3;
|
|
|
|
/// The special literals of a vocabulary and the private-use character that stands for each.
|
|
pub struct LiteralMarks {
|
|
/// Sorted and unique; the position is the mark.
|
|
literals: Vec<String>,
|
|
search: Option<AhoCorasick>,
|
|
}
|
|
|
|
impl LiteralMarks {
|
|
/// Marks for these literals. The order of the argument does not matter: the same set always gets the same marks.
|
|
pub fn new<'a>(literals: impl IntoIterator<Item = &'a str>) -> Result<Self, String> {
|
|
let mut literals: Vec<String> = literals
|
|
.into_iter()
|
|
.filter(|literal| !literal.is_empty())
|
|
.map(str::to_owned)
|
|
.collect();
|
|
literals.sort();
|
|
literals.dedup();
|
|
let count = literals.len();
|
|
if FIRST as usize + count > 0xFFFFD
|
|
|| literals
|
|
.iter()
|
|
.any(|l| l.chars().any(|c| Self::owns_char(c, count)))
|
|
{
|
|
return Err("special literals cannot be marked".to_owned());
|
|
}
|
|
let search = if literals.is_empty() {
|
|
None
|
|
} else {
|
|
// The tokenizer's own matching rule, so a literal is marked exactly where it would have been parsed.
|
|
Some(
|
|
AhoCorasickBuilder::new()
|
|
.match_kind(MatchKind::LeftmostLongest)
|
|
.build(&literals)
|
|
.map_err(|error| error.to_string())?,
|
|
)
|
|
};
|
|
Ok(Self { literals, search })
|
|
}
|
|
|
|
/// No literals: `mark` only escapes, `unmark` only unescapes.
|
|
pub fn none() -> Self {
|
|
Self {
|
|
literals: Vec::new(),
|
|
search: None,
|
|
}
|
|
}
|
|
|
|
/// The literals, in mark order: the `k`-th stands for the character `U+F0E01 + k`.
|
|
pub fn literals(&self) -> &[String] {
|
|
&self.literals
|
|
}
|
|
|
|
fn owns_char(c: char, count: usize) -> bool {
|
|
let code = c as u32;
|
|
code == ESCAPE as u32 || (FIRST..FIRST + count as u32).contains(&code)
|
|
}
|
|
|
|
fn owns(&self, c: char) -> bool {
|
|
Self::owns_char(c, self.literals.len())
|
|
}
|
|
|
|
/// The literal a mark character stands for.
|
|
fn literal_of(&self, c: char) -> Option<&str> {
|
|
(c as u32)
|
|
.checked_sub(FIRST)
|
|
.and_then(|index| self.literals.get(index as usize))
|
|
.map(String::as_str)
|
|
}
|
|
|
|
/// `text` with every special literal replaced by its mark, for a message's text before the template renders it.
|
|
/// Borrowed when there is nothing to change.
|
|
pub fn mark<'a>(&self, text: &'a str) -> Cow<'a, str> {
|
|
let may_escape =
|
|
text.as_bytes().contains(&PLANE_15_LEAD) && text.chars().any(|c| self.owns(c));
|
|
let first = self.search.as_ref().and_then(|search| search.find(text));
|
|
if first.is_none() && !may_escape {
|
|
return Cow::Borrowed(text);
|
|
}
|
|
let mut out = String::with_capacity(text.len());
|
|
let mut offset = 0;
|
|
let push_plain = |out: &mut String, piece: &str| {
|
|
for c in piece.chars() {
|
|
if self.owns(c) {
|
|
out.push(ESCAPE);
|
|
}
|
|
out.push(c);
|
|
}
|
|
};
|
|
if let Some(search) = &self.search {
|
|
for found in search.find_iter(text) {
|
|
push_plain(&mut out, &text[offset..found.start()]);
|
|
out.push(char::from_u32(FIRST + found.pattern().as_u32()).expect("mark in range"));
|
|
offset = found.end();
|
|
}
|
|
}
|
|
push_plain(&mut out, &text[offset..]);
|
|
Cow::Owned(out)
|
|
}
|
|
|
|
/// The inverse of [`LiteralMarks::mark`]: marks become their literal text, escapes are dropped.
|
|
pub fn unmark<'a>(&self, text: &'a str) -> Cow<'a, str> {
|
|
if !text.as_bytes().contains(&PLANE_15_LEAD) {
|
|
return Cow::Borrowed(text);
|
|
}
|
|
let mut out = String::with_capacity(text.len() + 16);
|
|
let mut chars = text.chars();
|
|
let mut changed = false;
|
|
while let Some(c) = chars.next() {
|
|
if c == ESCAPE {
|
|
match chars.next() {
|
|
Some(next) if self.owns(next) => {
|
|
out.push(next);
|
|
changed = true;
|
|
}
|
|
Some(next) => {
|
|
out.push(c);
|
|
out.push(next);
|
|
}
|
|
None => out.push(c),
|
|
}
|
|
} else if let Some(literal) = self.literal_of(c) {
|
|
out.push_str(literal);
|
|
changed = true;
|
|
} else {
|
|
out.push(c);
|
|
}
|
|
}
|
|
if changed {
|
|
Cow::Owned(out)
|
|
} else {
|
|
Cow::Borrowed(text)
|
|
}
|
|
}
|
|
|
|
/// Whether `text` holds a mark (a literal that is to be encoded as ordinary text).
|
|
pub fn has_marks(&self, text: &str) -> bool {
|
|
if !text.as_bytes().contains(&PLANE_15_LEAD) {
|
|
return false;
|
|
}
|
|
let mut chars = text.chars();
|
|
while let Some(c) = chars.next() {
|
|
if c == ESCAPE {
|
|
// The character after an escape is itself, never a mark.
|
|
chars.next();
|
|
} else if self.literal_of(c).is_some() {
|
|
return true;
|
|
}
|
|
}
|
|
false
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
fn marks() -> LiteralMarks {
|
|
LiteralMarks::new([
|
|
"<think>",
|
|
"</think>",
|
|
"<|im_end|>",
|
|
"<|im_start|>",
|
|
"<tool_call>",
|
|
])
|
|
.unwrap()
|
|
}
|
|
|
|
#[test]
|
|
fn ordinary_text_is_borrowed_unchanged() {
|
|
let marks = marks();
|
|
for text in [
|
|
"",
|
|
"hello",
|
|
"a < b > c",
|
|
"<|im_",
|
|
"think>",
|
|
"\u{F0001} plane 15 outside the range",
|
|
] {
|
|
assert!(matches!(marks.mark(text), Cow::Borrowed(_)), "{text:?}");
|
|
assert_eq!(marks.unmark(text), text);
|
|
assert!(!marks.has_marks(text));
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn literals_become_single_private_use_characters_and_back() {
|
|
let marks = marks();
|
|
let text = "a</think><|im_end|><|im_start|>system\n<think> b";
|
|
let marked = marks.mark(text);
|
|
assert!(!marked.contains("think>"));
|
|
assert_eq!(marked.chars().filter(|c| *c as u32 >= FIRST).count(), 4);
|
|
assert!(marks.has_marks(&marked));
|
|
assert_eq!(marks.unmark(&marked), text);
|
|
}
|
|
|
|
#[test]
|
|
fn marks_are_stable_for_the_same_set_whatever_its_order() {
|
|
let a = LiteralMarks::new(["<b>", "<a>"]).unwrap();
|
|
let b = LiteralMarks::new(["<a>", "<b>", "<a>"]).unwrap();
|
|
assert_eq!(a.mark("<a><b>"), b.mark("<a><b>"));
|
|
assert_eq!(a.mark("<a>"), "\u{F0E01}");
|
|
}
|
|
|
|
#[test]
|
|
fn removing_a_literal_never_forms_a_new_one() {
|
|
let marks = marks();
|
|
let marked = marks.mark("<|im_<think>end|>");
|
|
assert!(!marked.contains("<|im_end|>"));
|
|
assert_eq!(marks.unmark(&marked), "<|im_<think>end|>");
|
|
}
|
|
|
|
#[test]
|
|
fn a_forged_mark_is_escaped_and_round_trips() {
|
|
let marks = marks();
|
|
for forged in [
|
|
"\u{F0E01}",
|
|
"\u{F0E00}",
|
|
"\u{F0E00}\u{F0E01}x",
|
|
"\u{F0E05}",
|
|
"\u{F0E06}",
|
|
] {
|
|
let marked = marks.mark(forged);
|
|
assert_eq!(marks.unmark(&marked), forged, "{forged:?}");
|
|
}
|
|
// A forged mark cannot be mistaken for a real one.
|
|
assert!(!marks.has_marks(&marks.mark("\u{F0E01}")));
|
|
assert!(marks.has_marks("\u{F0E01}"));
|
|
}
|
|
|
|
#[test]
|
|
fn longest_literal_wins_like_the_tokenizer() {
|
|
let marks = LiteralMarks::new(["<a>", "<a>b", "b"]).unwrap();
|
|
assert_eq!(marks.mark("<a>b").chars().count(), 1);
|
|
}
|
|
|
|
#[test]
|
|
fn no_literals_means_escapes_only() {
|
|
let marks = LiteralMarks::none();
|
|
assert_eq!(marks.mark("<think>"), "<think>");
|
|
assert_eq!(marks.unmark(&marks.mark("\u{F0E00}")), "\u{F0E00}");
|
|
}
|
|
}
|