Skip to content

byte-level: index the char->byte table by codepoint instead of hashing - #2178

Merged
ArthurZucker merged 1 commit into
huggingface:feat/train_encode_splitfrom
sebpop:detok-idrange-skip
Sep 15, 2026
Merged

ArthurZucker merged 1 commit into
huggingface:feat/train_encode_splitfrom
sebpop:detok-idrange-skip

Conversation

@sebpop

@sebpop sebpop commented Jul 9, 2026 •

Copy link
Copy Markdown
Contributor

byte-level: index the char->byte table by codepoint instead of hashing

@HuggingFaceDocBuilderDev

Copy link
Copy Markdown

The docs for this PR live here. All of your documentation changes will be reflected on that endpoint. The docs are available until 30 days after the last update.

@sebpop
sebpop force-pushed the detok-idrange-skip branch 2 times, most recently from 9e532f7 to 794df99 Compare July 13, 2026 22:09
@sebpop
sebpop force-pushed the detok-idrange-skip branch from 794df99 to 2ef4a0a Compare July 22, 2026 20:15
@sebpop

sebpop commented Jul 23, 2026

Copy link
Copy Markdown
Contributor Author

Ping patch: @ArthurZucker could you please restart the CI?

@ArthurZucker

Copy link
Copy Markdown
Collaborator

I can't without a rebase now!

ArthurZucker added a commit that referenced this pull request Sep 3, 2026
Every SentencePiece-family config -- gemma, llama-2, mistral, T5 -- decoded
through a route that allocates roughly three `String`s per token: one in the
gather (`id_to_token` is `from_utf8_lossy(..).into_owned()`), one in `Replace`
(`"".to_string()` per token), a fresh `Vec<String>` plus a
`previous_byte_tokens.clone()` per byte run in `ByteFallback`, then `join("")`
in `Fuse`. About 4.5M allocations for one pass over big.txt, and 34 MiB/s
against 514 for a byte-level model on the same corpus.

`Sequence[Replace{literal}, ByteFallback, Fuse]`, optionally followed by
`Strip`, is now recognised at load and run as a single pass into a reused
buffer: `Replace` inline per token, `ByteFallback` accumulating a run and
resolving it at the end, `Fuse` being the concatenation the loop already does,
`Strip` applied to the finished output. Nothing is allocated per token. An
unrecognised chain declines and keeps the generic route.

Measured, verified byte-exact against the released crate in
huggingface/tokbench (`decode_verified` on all 9 cells, encode ids too):

  gemma-3    chinese   39.4 -> 190.6 MB/s   4.8x
             english   37.2 -> 177.9        4.8x
             japanese  44.1 -> 218.4        5.0x
  llama-2    now 198-273 MB/s on the same path
  llama-3    unchanged (byte-level, 401-553)

And on the larger gemma-4 config in `tk-serialize`'s bench: english
34.4 -> 197.8 MiB/s, japanese 45.1 -> 303.4.

Two things this gets right that a cheaper version did not, both caught by that
gate rather than by reasoning:

  * `ByteFallback` is run-based, not per-token. Precomputing the chain per
    vocabulary entry asks it to validate one byte alone; a lone `0xE4` is not
    UTF-8 and comes back U+FFFD, so every three-token CJK character became
    three replacement characters. An **invalid** run must yield one U+FFFD per
    byte of the run, which "append raw bytes and let `from_utf8_lossy` sort it
    out" also does not reproduce.
  * `Strip` runs *after* `Fuse`, so it applies to the whole output, not to each
    token. That position-dependence is why a per-token table cannot express
    this chain, and it broke every llama-2 cell before being handled here.

Membership in the added vocabulary is a binary search over the added ids rather
than `id >= added_id_min`: that short-circuit never fires for these configs,
because gemma's `<pad>` is id 0 and so every token clears the threshold. Worth
knowing for #2178, which proposes exactly that short-circuit.
`CHAR_BYTES_LOOKUP` was an `AHashMap<char, u8>` holding the 256-entry inverse of
`BYTES_CHAR_LOOKUP`. `make_byte_char_lookup` only ever emits codepoints below
324 -- printable bytes map to themselves and the other 68 are shifted to
`256..=323` -- so the inverse fits in a fixed `[Option<u8>; 512]` indexed by the
codepoint, with no hashing and no probe.

Read it through the new `char_to_byte`, which handles the out-of-range case, so
the call sites stop repeating the lookup dance. All four are per-character over
whole vocabularies or whole token streams:

  * `transform_vocab`, through `reverse_lookup`: every char of every vocab entry
    when a byte-level model is built.
  * `ByteLevelFold::fold` and `boundary_merge_ranks`: every char of every vocab
    entry again, also at build time.
  * `ByteLevelDecoder::decode_chain`: every char of every token, for a model
    whose vocab store does not already hold pre-decoded bytes.

Three tests pin the invariant the unguarded indexing rests on. A future change
to `make_byte_char_lookup` that moved the alphabet past 512 would otherwise
panic on first use of the table, and guarding the write instead would silently
drop the entry and decode wrongly, which is worse.

Representation change only: decode output is byte-for-byte identical.

Measured on three machines, each an exclusive node with the work pinned to one
CPU. Both arms are built from the same tree and run round-robin rather than in
sequence, so thermal or neighbor drift cannot land entirely on one of them.
Change in `decode_chain` throughput, head vs base, median of 3 rounds:

  CPU                          arch       English   Japanese
  AMD EPYC 9655P, 96 core      x86_64       +8.1%     +36.6%
  Intel Xeon Platinum 8568CXL  x86_64       +7.1%     +33.4%
  NVIDIA Grace, Neoverse-V2    aarch64     +16.7%     +29.3%

`pipeline_decode` over the same corpora never reaches this code on these models,
and it stayed within 2.1% on every machine; that is the run-to-run floor the
gains above have to clear. Model load, which walks the table once per vocab
entry, gained 0.6 to 3.6%.

Japanese gains about twice what English does, which is what the change predicts:
the removed probe is per character of the token string, and a Japanese codepoint
is three UTF-8 bytes and therefore three byte-level characters to look up,
against roughly one for English.
@sebpop
sebpop force-pushed the detok-idrange-skip branch from 2ef4a0a to 35d5bb4 Compare September 3, 2026 18:10

@ArthurZucker ArthurZucker left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

LGTM, ty

@ArthurZucker ArthurZucker changed the title decode: skip added-vocab check via id-range short-circuit Reverse map lookup for byte level decode Sep 15, 2026
@ArthurZucker ArthurZucker changed the title Reverse map lookup for byte level decode byte-level: index the char->byte table by codepoint instead of hashing Sep 15, 2026
@ArthurZucker
ArthurZucker merged commit 44e272d into huggingface:feat/train_encode_split Sep 15, 2026
14 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants