Skip to content

Use a heap-based BPE merge for long pieces - #160

Open
Hexay wants to merge 1 commit into
openai:mainfrom
Hexay:heap-bpe-merge-upstream
Open

Hexay wants to merge 1 commit into
openai:mainfrom
Hexay:heap-bpe-merge-upstream

Conversation

@Hexay

@Hexay Hexay commented Nov 27, 2026

Copy link
Copy Markdown

_byte_pair_merge rescans every part after each merge, so a piece of n bytes costs O(n²). The pre-tokenizer regex keeps most pieces to a few bytes, but a run of whitespace or of a single letter is one piece, so a long run in a message makes rendering take minutes.

This ports _byte_pair_merge_large from openai/tiktoken and uses it for pieces of 100 bytes or more, as tiktoken does. Shorter pieces keep the existing path, so ordinary text is unaffected. The only change from tiktoken's code is a nested if in place of a let-chain, because this crate is on the 2021 edition.

encode_ordinary, release build, same machine:

Input Before After
64 KiB of spaces 1.35 s 0.01 s
128 KiB of spaces 9.68 s 0.03 s
64 KiB of a 1.37 s 0.01 s
128 KiB of a 10.30 s 0.02 s
512 KiB of spaces not timed (minutes) 0.14 s

Token counts are identical before and after for every row.

The added test checks the new merge against the existing one on about 150 pieces of 100 bytes or more (runs of spaces, newlines, one letter, a multi-byte character, and random letters over three alphabets) using the HarmonyGptOss vocabulary.

Related: #153 takes a different route to the same problem; this one reuses tiktoken's own implementation.

`_byte_pair_merge` rescans every part after each merge, so a piece of n
bytes costs O(n^2). The pre-tokenizer regex bounds most pieces to a few
bytes, but a run of whitespace or of one letter is a single piece.

Port `_byte_pair_merge_large` from openai/tiktoken and use it for pieces
of 100 bytes or more, as tiktoken does. Shorter pieces keep the existing
path.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 27, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-27T15:02:18.506270Z e3600be PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant