Skip to content

tokenizer, hf: Llama 3 tokenizers open (llama-bpe) - #1052

Merged
midagedev merged 5 commits into
mainfrom
mltok
Nov 1, 2026
Merged

midagedev merged 5 commits into
mainfrom
mltok

Conversation

@midagedev

@midagedev midagedev commented Oct 31, 2026 •

Copy link
Copy Markdown
Owner

What and why

A Llama 3 checkpoint's tokenizer did not open. Its GGUF and its HF folder name the pre-tokenizer llama-bpe, and
the table knew only lfm2 for the same pipeline. This adds three things:

  • the llama-bpe row (llama.cpp maps it and lfm2 to its one llama3 type);
  • the HF folder's BOS template, read as add_bos;
  • llama.cpp's clean_spaces on decode, only for llama-bpe, and in serving's streaming decoder too.

Every other pre-tokenizer encodes and decodes as before: the space cleaner is None for them.

Release notes: Added — Llama 3 checkpoints' tokenizers open, from a GGUF or an HF folder.

Code shape

  • No second copy. llama-bpe reuses the llama3 regex row lfm2 spells.
  • Model code holds only architecture facts. The pre-tokenizer name carries a tools/model-tax.tsv PIN row.
  • Dead code is gone.
  • No silent failure. A BOS template the reader cannot read is refused by name.
  • Comments state what is true now.
  • No relaxed gate.
  • cargo fmt and 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_tokenizer against llama.cpp's own ggml-vocab-llama-bpe.gguf with its .inp and
    .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 in
    e740e86; just mac-lint, tools/check-levers.sh and tools/check-model-tax.sh are 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

midagedev and others added 2 commits November 1, 2026 02:20
… 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]>
@github-actions github-actions Bot added host Host crates: qdot, threads, engram, engram-lab, runtime, sampler, levers, decision, vision, refset model The CPU engine and model files: crates/model, models, hf, gguf, tokenizer, jinja serve The HTTP server: crates/serve tools Tools, recipes, CI and the toolchain: tools/, justfile, .github/, Cargo labels Oct 31, 2026

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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]>
@midagedev

Copy link
Copy Markdown
Owner Author

All four findings are fixed in 1b5b102. Each new test was red before the change.

  1. SpaceCleaner holds only a proper prefix of one of its patterns, per pass, in llama.cpp's pass order. Everything else is released in the push that carries it. pass_*, clean_traced and quiet_byte are gone. Tests: every split of a set of texts (the review's sentence, each pattern at a push boundary, multi-byte UTF-8, <|start_header_id|>) equals the one-shot result, and text comes out before finish. serve: a llama-bpe special pushed from an empty decoder no longer panics the loop.
  2. logprobs::piece keeps the cleaner's tail. "a" and "hello" keep their labels.
  3. An absent add_bos_token means true for llama-bpe, as llama.cpp's LLAMA3 type sets it. crates/hf/tests/minimax_encode.rs's synthetic table now writes add_bos_token=false, as the real folder reader always does.
  4. A template that names the BOS with no special_tokens entry for it is refused by name. The check runs after the identity checks, so the existing refusal messages keep their meaning.

cargo test -p bloomery-tokenizer -p bloomery-hf -p bloomery-serve: green. hw_llama_bpe_encodes_as_llama_tokenizer on llama.cpp's vectors: ok. just mac-lint: 0 warnings. Every tools/check-*.sh: green.

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

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]>
@midagedev

Copy link
Copy Markdown
Owner Author

Second review answered in f62a5d9:

  1. pump maps a special id's span with strip_suffix; a piece that does not carry the special's text whole ends the request with GenError::SpecialPiece(id). No expect on this path. Tests through the production Vocab: "foo " and ' after a space both end with SpecialPiece (red before: a panic at genloop.rs:2689, and a lost span); <|start_header_id|> still streams whole with span (0, 19).
  2. LlamaBpeDecoder/LlamaBpeTok deleted; the test vocabulary is a tokenizer::Tokenizer::from_keys through crate::vocab::Vocab. The proposal's ' special collided with byte 0x27's token (DuplicateToken), so the builder skips that byte token.
  3. SpecialEngine deleted; ScriptedEngine::with_tokenizer added.
  • The new error caught a defect in constrain/tests.rs's PieceDecoder: after a hard invalid byte it released nothing, so a later special lost its span. It now follows the production rule (U+FFFD, then continue).
  • The cleaner's passes now work in place (the headroom note).

cargo test -p bloomery-tokenizer -p bloomery-hf -p bloomery-serve: 709 passed, 0 failed. hw_llama_bpe ok. mac-static green except check-model-tax, which flags two qwen rows that main lowered after this branch's base; this branch does not touch them.

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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]>
@midagedev

Copy link
Copy Markdown
Owner Author

Third review answered in e9b106c: PieceDecoder deleted; Pieces::decoder returns Vocab::new(tok).decoder() over a gpt2/qwen2 vocabulary of the same pieces (byte ids as <0xNN> BYTE tokens, the rest CONTROL). No assertion changed. cargo test -p bloomery-serve: 478 passed, 0 failed. Mutating piece(id, true) to false in VocabDecoder::push turns 12 constrain tests red, so the production decoder is on the path.

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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)

@midagedev
midagedev merged commit ea9ea4f into main Nov 1, 2026
7 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

host Host crates: qdot, threads, engram, engram-lab, runtime, sampler, levers, decision, vision, refset model The CPU engine and model files: crates/model, models, hf, gguf, tokenizer, jinja serve The HTTP server: crates/serve tools Tools, recipes, CI and the toolchain: tools/, justfile, .github/, Cargo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant