127 lines
5.3 KiB
Rust
127 lines
5.3 KiB
Rust
//! Encoding text to ids: marked text, plain text, special tokens, segments and the reference path.
|
|
|
|
#[allow(unused_imports)]
|
|
use super::*;
|
|
|
|
impl Tokenizer {
|
|
/// 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.
|
|
pub(super) 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();
|
|
encode_pieces(fast, text, ids, scratch);
|
|
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)
|
|
}
|
|
}
|
|
|
|
/// Pre-tokenize `text` with the table-driven scanner and merge each piece.
|
|
#[inline]
|
|
fn encode_pieces(fast: &fast::Fast, text: &str, ids: &mut Vec<u32>, scratch: &mut fast::Scratch) {
|
|
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;
|
|
}
|
|
}
|