Repository navigation
Conversation
… row, the BOS template read as add_bos, and llama.cpp's clean_spaces on its decode Co-Authored-By: Claude Opus 5.5 <[email protected]>
…; hf's llama-bpe name carries its PIN row Co-Authored-By: Claude Opus 5.5 <[email protected]>
There was a problem hiding this comment.
Verdict: MUST_FIX: streaming can panic, probability labels lose text, and tokenizer loading accepts incorrect defaults and missing mappings.
Must fix
1. Release text without requiring a quiet word
crates/tokenizer/src/decode.rs:241 buffers “I am a cat. I am a dog.” until finish. Repeated “a ” costs (N−4)(N−3)/2 cut checks for N≥5 byte-token pushes [derived].
From an empty decoder, non-stop special token <|start_header_id|> releases 16 of its 19 bytes. crates/serve/src/genloop.rs:2684 then panics on checked_sub(19). Fix the shared cleaner.
Replace SpaceCleaner, its quiet-zone documentation and impl below. Delete the three pass_* functions, clean_traced and quiet_byte. Replace clean_str below too.
/// Cleans UTF-8 through ordered passes, retaining unfinished ASCII patterns.
#[derive(Default)]
pub struct SpaceCleaner {
pending: [Vec<u8>; 3],
}
impl SpaceCleaner {
/// Returns text that later input cannot change.
pub fn push(&mut self, text: &str) -> String {
self.feed(Some(text))
}
/// Returns the remaining cleaned text.
pub fn finish(&mut self) -> String {
self.feed(None)
}
fn feed(&mut self, text: Option<&str>) -> String {
let passes: [&[(&[u8], &[u8])]; 3] = [
&[(b" ?", b"?"), (b" !", b"!"), (b" .", b"."), (b" ,", b",")],
&[(b" ' ", b"'")],
&[(b" 's", b"'s"), (b" 'm", b"'m"),
(b" 're", b"'re"), (b" 've", b"'ve")],
];
let mut bytes = match text {
Some(s) => s.as_bytes().to_vec(),
None => Vec::new(),
};
for (pending, patterns) in self.pending.iter_mut().zip(passes) {
pending.extend_from_slice(&bytes);
let mut out = Vec::new();
let mut at = 0;
while at < pending.len() {
let rest = &pending[at..];
if let Some(&(pattern, replacement)) =
patterns.iter().find(|(p, _)| rest.starts_with(p))
{
out.extend_from_slice(replacement);
at += pattern.len();
} else if text.is_some() &&
patterns.iter().any(|(p, _)| p.starts_with(rest))
{
break;
} else {
out.push(pending[at]);
at += 1;
}
}
pending.drain(..at);
bytes = out;
}
String::from_utf8(bytes).expect("only ASCII pattern prefixes are retained")
}
}pub(crate) fn clean_str(text: &str) -> String {
let mut cleaner = SpaceCleaner::default();
let mut out = cleaner.push(text);
out.push_str(&cleaner.finish());
out
}Assert progress before finish and complete special markers.
2. Include the cleaner tail in alternative token labels
crates/serve/src/logprobs.rs:337 discards the cleaner tail introduced at crates/serve/src/vocab.rs:178: a llama-bpe alternative “a” becomes empty and “hello” becomes “he” in top_logprobs. A space token still loses its label after item 1. Fix this consumer with the decoder change.
After item 1, retain the ASCII cleaner tail; exclude the incomplete UTF-8 replacement:
fn piece(vocab: &dyn Tokenizer, id: u32) -> (String, Value) {
let mut d = vocab.decoder();
let mut text = d.push(id).unwrap_or_default();
let tail = d.flush();
let complete = tail.strip_suffix(char::REPLACEMENT_CHARACTER);
let exact = complete.is_none() && !text.contains(char::REPLACEMENT_CHARACTER);
text.push_str(complete.unwrap_or(&tail));
let bytes = if exact { json!(text.as_bytes()) } else { Value::Null };
(text, bytes)
}3. Give llama-bpe GGUFs their BOS default
crates/tokenizer/src/pretok.rs:733 opens llama-bpe GGUFs, but vocab.rs:509 defaults absent add_bos_token to false. With a BOS ID present, encode(text, true, false) and bloomery-tokenize still omit BOS. lib.rs:1848 acknowledges llama.cpp's true default; the vector test disables special insertion. Correct the default before prompt IDs depend on it.
Replace the unwrap_or expression at vocab.rs:509:
.unwrap_or(matches!(model, Model::Spm) || pre == "llama-bpe")4. Require the template's special-token mapping
crates/hf/src/vocab.rs:919 skips validation for missing, null or empty special_tokens. Removing the fixture's map still resolves BOS through by_name at :941 and exports add_bos_token=true at :1070. This is a kind B silent-failure defect: reject the missing template mapping before exporting inferred IDs.
Insert before that optional-map branch:
if !template["special_tokens"]
.as_object()
.is_some_and(|tokens| tokens.contains_key(token))
{
return Err(bad(
"tokenizer.json.post_processor is missing the BOS special_tokens entry".into()
));
}Checked
Duplicates: four distinct findings; dryer reports zero pairs.
Complexity: post_processor new→39; keys 29→35 (BOS branches).
Silent failure: missing mappings reach BOS insertion.
Tests: streaming assertions include finish; GGUF vectors disable special insertion.
Gates: no numeric pins moved. No escape-catalog or ledger matches.
Notes
Source inspection and Python buffering model only; Rust tests were not run.
🔨 Shingler, bloomery's review bot: approves a clean pull request and requests changes on a must-fix (how it works)
…; an alternative keeps its whole label; llama-bpe adds a BOS by default; a template without its BOS special_tokens entry is refused Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
All four findings are fixed in 1b5b102. Each new test was red before the change.
|
There was a problem hiding this comment.
Since the last review:
- 1: Progress and standard markers fixed; panic still open at crates/serve/src/genloop.rs:2684 (item 1).
- 2: Alternative labels fixed, including the cleaner tail.
- 3: GGUF BOS default fixed.
- 4: Missing BOS template mappings now rejected.
Verdict: MUST_FIX: accepted special tokens still terminate serving, and new test code duplicates existing owners.
Must fix
1. Reject special pieces that the cleaner cannot release whole
crates/tokenizer/src/decode.rs:177 holds the last space of a non-stop CONTROL token "foo ". This spelling is accepted by the loader. Its push returns "foo", while whole decode returns "foo ".
crates/serve/src/genloop.rs:2684 then calls checked_sub(4) on a 3-byte length and panics at expect. The worker catches this panic outside the engine loop and closes serving (worker.rs:557-574). A lone special apostrophe after a space instead returns no piece and loses its special span.
Cost: fixing the shared span check now avoids per-tokenizer workarounds.
Add this request error to GenError:
#[error("special token {0} was not released whole by the streaming decoder")]
SpecialPiece(u32),Replace the let special = piece... expression in pump:
let special = if self.vocab.is_special(tok) {
let text = self.vocab.decode(&[tok]);
let at = piece.as_deref()
.and_then(|p| p.strip_suffix(text.as_str()))
.map(str::len)
.ok_or(GenError::SpecialPiece(tok))?;
Some((at, text.len()))
} else {
None
};Test both retained special spellings through the production vocabulary and assert this request error. Restoring the unchecked assumption must fail those tests.
2. Exercise the production decoder instead of copying it
crates/serve/src/genloop.rs:5316 copies UTF-8 accumulation, replacement and cleanup from crates/serve/src/vocab.rs:149 (R14). Changing the production decoder can leave this regression test green.
Cost: removing the copy now prevents two implementations from drifting.
Delete LlamaBpeDecoder and its impl. Replace LlamaBpeTok::decoder with:
fn decoder(&self) -> Box<dyn Decoder> {
use gguf::Value;
let mut tokens: Vec<_> = LLAMA_SPECIALS.iter()
.map(|s| Value::String((*s).into())).collect();
tokens.extend(tokenizer::byte_to_cpt_table().into_iter().map(|cp|
Value::String(char::from_u32(cp).unwrap().to_string())
));
let types = (0..tokens.len())
.map(|i| Value::I32(if i < LLAMA_SPECIALS.len() { 3 } else { 1 }))
.collect();
let keys = [
("model", Value::String("gpt2".into())),
("pre", Value::String("llama-bpe".into())),
("tokens", Value::Array(tokens)),
("token_type", Value::Array(types)),
("merges", Value::Array(vec![])),
("eos_token_id", Value::U32(0)),
("add_bos_token", Value::Bool(false)),
].map(|(k, v)| (format!("tokenizer.ggml.{k}"), v));
let tok = tokenizer::Tokenizer::from_keys(&keys).unwrap();
crate::vocab::Vocab::new(tok).unwrap().decoder()
}3. Reuse the scripted test engine
crates/serve/src/genloop.rs:5360 repeats the fixed-id replay and reset owned by crates/serve/src/mock.rs:1659. Its custom tokenizer is the only needed difference (R14).
Cost: reusing the owner now avoids maintaining a second replay state machine.
Delete SpecialEngine and its impl. Add to impl ScriptedEngine:
/// Uses this vocabulary to interpret the scripted ids.
#[must_use]
pub(crate) fn with_tokenizer(mut self, tok: Arc<dyn Tokenizer>) -> Self {
self.tok = tok;
self
}Replace the test's slot construction:
let mut slot = Slot::new(Box::new(
crate::mock::ScriptedEngine::from_ids(4096, vec![1]).with_tokenizer(tok),
));Optimization headroom
- E. Less work: crates/tokenizer/src/decode.rs:168, compact intermediate passes in place to remove two temporary Vec allocations per push that releases text [derived].
Checked
Duplicates: both test copies above repeat existing owners; each proposed replacement removes more code and names than it adds. Both dryer reset pairs read; neither warrants a standalone extraction.
Complexity: post_processor adds a mapping guard; keys is unchanged since the prior review; Vocab::load adds one BOS-default condition. No split finding.
Silent failure: the special-span mapping skips a special when its decoder returns no piece.
Tests: removing the mapping guard, BOS default, prefix hold or label-tail append makes the corresponding assertions fail by inspection. The validator's cleaner model confirms both retained-special cases and whole release of the standard marker. Serving tests omit the retained-special cases.
Gates: no pins moved. Escape catalog: no patterns matched.
Notes
Rust tests were not run. Validation used source inspection and an in-memory Python model.
🔨 Shingler, bloomery's review bot: approves a clean pull request and requests changes on a must-fix (how it works)
…ole ends its request by name; the tests run the production vocabulary and the scripted engine; the cleaner's passes work in place Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Second review answered in f62a5d9:
|
There was a problem hiding this comment.
Since the last review:
- 1 fixed: retained special pieces return a request error.
- 2 fixed: the generation regressions use the production decoder.
- 3 fixed: the regressions reuse ScriptedEngine.
- E advice fixed: intermediate cleaner passes compact in place.
Verdict: MUST_FIX: the constraint-test decoder adds another copy of production UTF-8 handling.
Must fix
1. Reuse the production decoder in the constraint tests
crates/serve/src/constrain/tests.rs:91 adds a copy of the replacement and incomplete-tail loop in crates/serve/src/vocab.rs:153 (R14, kind B). These now hold the same UTF-8 rule in two places.
Cost: removing this copy now avoids maintaining two versions of the same rule.
Delete PieceDecoder and its impl. Replace Pieces::decoder with the following. BYTE entries preserve the byte ids; the other entries render literal pieces. This removes a type and two methods and reduces the total code.
fn decoder(&self) -> Box<dyn Decoder> {
use gguf::Value;
let (tokens, types): (Vec<_>, Vec<_>) = (0..self.n_vocab())
.map(|i| {
let id = u32::try_from(i).unwrap();
let (text, kind) = if (BYTES..PIECES).contains(&id) {
(format!("<0x{:02X}>", id - BYTES), 6)
} else {
(String::from_utf8(self.0.bytes_of(id)).unwrap(), 3)
};
(Value::String(text), Value::I32(kind))
})
.unzip();
let keys = [
("model", Value::String("gpt2".into())),
("pre", Value::String("qwen2".into())),
("tokens", Value::Array(tokens)),
("token_type", Value::Array(types)),
("merges", Value::Array(vec![])),
("bos_token_id", Value::U32(0)),
("eos_token_id", Value::U32(1)),
]
.map(|(key, value)| (format!("tokenizer.ggml.{key}"), value));
let tok = tokenizer::Tokenizer::from_keys(&keys)
.expect("unique byte and literal pieces");
crate::vocab::Vocab::new(tok).unwrap().decoder()
}Checked
Duplicates: the new UTF-8 loop matches VocabDecoder; the proposed fix reuses it and removes more code and elements than it adds.
Complexity: the special-span mapping adds a request-error branch.
Silent failure: valid_up_to proves the prefix passed to from_utf8 is valid. Both retained-special cases return SpecialPiece to the request.
Tests: restoring the old span mapping fails both new error assertions by inspection; holding the standard marker fails the revised success test.
Gates: no pins moved or cases removed. Escape catalog: no patterns matched.
Notes
Rust tests and the proposed replacement were not compiled. Validation used source inspection.
🔨 Shingler, bloomery's review bot: approves a clean pull request and requests changes on a must-fix (how it works)
…r a vocabulary of their pieces Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Third review answered in e9b106c: |
There was a problem hiding this comment.
Since the last review:
- 1 fixed: Pieces::decoder uses the production decoder; PieceDecoder and its UTF-8 loop are removed.
Verdict: CLEAN: the incremental change resolves the previous finding and preserves the test vocabulary's decoded pieces.
Checked
Duplicates: 0 new named items; the changed method reuses VocabDecoder. Dryer reported 0 pairs.
Complexity: crapper's post_processor, keys, Gen::pump and Vocab::load are unchanged in this incremental patch. The decoder replacement adds one fixture-mapping branch.
Silent failure: 4 added expect sites stop fixture construction on failure; no added error defaults.
Tests: no assertions changed. Mutating the production BYTE-piece branch (tokenizer/src/decode.rs:90) to return byte 0 breaks the WEATHER content assertion by inspection.
Adversarial: byte boundaries and empty piece lists preserve IDs; CONTROL pieces preserve literal text; the returned decoder clones the vocabulary Arc before the temporary Vocab drops.
Gates: no pins or assertions moved or removed.
Escape catalog: no patterns matched.
Notes
Rust tests were not run. Validation used source inspection.
🔨 Shingler, bloomery's review bot: approves a clean pull request and requests changes on a must-fix (how it works)
What and why
A Llama 3 checkpoint's tokenizer did not open. Its GGUF and its HF folder name the pre-tokenizer
llama-bpe, andthe table knew only
lfm2for the same pipeline. This adds three things:llama-bperow (llama.cpp maps it andlfm2to its one llama3 type);add_bos;clean_spaceson decode, only forllama-bpe, and in serving's streaming decoder too.Every other pre-tokenizer encodes and decodes as before: the space cleaner is
Nonefor them.Release notes: Added — Llama 3 checkpoints' tokenizers open, from a GGUF or an HF folder.
Code shape
llama-bpereuses the llama3 regex rowlfm2spells.tools/model-tax.tsvPIN row.cargo fmtand clippy are clean; the lint count did not go up.Duplication found or removed: none.
What I ran
On an M1 Pro (macOS 27.0):
cargo test -p bloomery-tokenizer -p bloomery-hf: green.cargo test -p bloomery-serve --lib: 474 passed.cargo test -p bloomery-levers: 58 passed.hw_llama_bpe_encodes_as_llama_tokenizeragainst llama.cpp's ownggml-vocab-llama-bpe.ggufwith its.inpand.out(llama.cpp 358a420ec): every text gives exactly llama.cpp's ids.the_real_llama_3_1_files_open_as_the_llama_bpe_row: Llama-3.1-8B-Instruct's tokenizer files (fixture).just mac-static origin/main: first run red on lint, check-levers and check-model-tax. All three were fixed ine740e86;
just mac-lint,tools/check-levers.shandtools/check-model-tax.share now rc 0.With the Metal Llama map (a later PR), Llama-3.1-8B-Instruct MLX 4-bit greedy-decodes 32 of 32 tokens equal to
mlx-lm 0.32.0.
Hardware
Apple M1 Pro, 32 GB, macOS 27.0. No card change: the tokenizer change reaches only
llama-bpe.AI use: written with Claude Code (an Opus round implemented it; the maintainer's lead session reviewed and ran the
checks).
🤖 Generated with Claude Code