Skip to content

tokenizers.js ignores byte_fallback for Unigram models #26

Description

@sodiumplus3

Feature request

tokenizers.js appears to ignore byte_fallback for Unigram models.

Some SentencePiece / Unigram tokenizers include the following configuration in tokenizer.json:

{
  "type": "Unigram",
  "byte_fallback": true
}

However, the current JavaScript implementation seems to fall back to a single <unk> token for out-of-vocabulary characters, instead of expanding them into UTF-8 byte tokens such as <0xXX>.

For example, if 🍣 is not in the vocab, I would expect it to be encoded as:

<0xF0> <0x9F> <0x8D> <0xA3>

rather than as a single token.

It looks like byte_fallback is not initialized or used for Unigram models in the same way as it is for BPE models, and OOV handling in the Unigram lattice path currently falls back to <unk>.

Would you consider supporting byte_fallback for Unigram models as a compatibility feature with SentencePiece / HuggingFace tokenizers?

Motivation

This matters because some exported tokenizer configs explicitly set byte_fallback=true.

For those models, tokenizers.js can currently produce different tokenization results from the Python / Rust implementations when the input contains OOV characters. This can lead to different token IDs being passed to the model for the same input text.

The intended use case is to make tokenizers.js compatible with Unigram tokenizer files that rely on byte fallback behavior, especially for multilingual or SentencePiece-based models where unknown Unicode characters should be represented as byte tokens instead of <unk>.

Your contribution

I have a draft implementation that adds byte fallback handling for Unigram models.

Since this changes the tokenization output for OOV characters when byte_fallback=true, I wanted to confirm the intended direction before opening a PR. If this behavior is considered desirable, I would be happy to submit a PR with the implementation and tests.

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type

    Fields

    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions