Skip to content

TiktokenTokenizer: GetIndexByTokenCount and EncodeToIds(maxTokenCount) can return a prefix that needs one more token than the budget #7983

Backlog

Description

@krwq

System Information (please complete the following information):

  • OS & Version: Windows x64
  • ML.NET Version: Microsoft.ML.Tokenizers 3.0.0 with Microsoft.ML.Tokenizers.Data.O200kBase 3.0.0. The same code is on main (5b72b4c) and has been there since ML.NET 4.0 (Introducing CodeGen Tokenizer #7139).
  • .NET Version: .NET 10.0

Describe the bug
GetIndexByTokenCount(text, n, ...) and EncodeToIds(text, n, out _, out charsConsumed) can return a prefix that needs n + 1 tokens when it's encoded on its own, while the reported count is n. Encoding a long text in chunks that each continue from charsConsumed then corrupts a character.

It happens where every token spans two characters, so no token ends on a character boundary. Repeated Khmer or Georgian letters are an example, and there it hits half of all budgets. In real text it's rare: 1 of 1,905 budgets on a Georgian Wikipedia extract and 2 of 3,546 on a Khmer one.

To Reproduce

  1. Reference Microsoft.ML.Tokenizers 3.0.0 and Microsoft.ML.Tokenizers.Data.O200kBase 3.0.0.
  2. Run the code below.
  3. It prints 3 2 3: the returned index is reported as 2 tokens, but that prefix needs 3. Then it prints False: decoding the chunked ids doesn't give the original text back.

Expected behavior
The returned prefix fits the budget (CountTokens(text.AsSpan(0, index)) <= n), and encoding in chunks that continue from charsConsumed gives the original text back when decoded. GetIndexByTokenCountFromEnd was never over budget in the same runs.

Screenshots, Code, Sample Projects

var tok = TiktokenTokenizer.CreateForEncoding("o200k_base");
string text = new string('\u179A', 600); // Khmer letter RO, repeated

int index = tok.GetIndexByTokenCount(text, 2, out _, out int reported);
Console.WriteLine($"{index} {reported} {tok.CountTokens(text.AsSpan(0, index))}"); // prints "3 2 3"

var ids = new List<int>();
for (int start = 0; start < text.Length;)
{
    ids.AddRange(tok.EncodeToIds(text.AsSpan(start), 50, out _, out int consumed));
    start += consumed;
}
Console.WriteLine(tok.Decode(ids) == text); // prints "False"

Additional context
Cause: when the next token shares a character with the current one, EncodeToIdsResult (TiktokenTokenizer.cs#L483-L515) keeps the tokens that start before the current token ends. In a chain, the token after that starts inside the following character, so the group stops there. charsConsumed then covers a character whose last bytes belong to a token that wasn't returned.

A fix could re-encode the cut piece on its own and back off until it fits. Just extending the group through the whole chain would avoid going over, but it returns empty chunks on such chains, the trap the rust-gems README describes.

Found while looking into #7336.

Drafted with AI assistance.

Activity

  1. added
    bug
    area-Tokenizers
    on Dec 4, 2026
  2. added
    untriaged
    on Dec 4, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-Tokenizersbuguntriaged

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions