Repository navigation
guard empty piece before exactMatchSearch in unigram PieceToId - #1325
Merged
Merged
Conversation
sambhusankar
approved these changes
Sep 8, 2026
1 task
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
While tracing why an empty token round-tripped to a real vocabulary id, I found
unigram::Model::PieceToIdforwardingpiece.size()straight intoDarts::DoubleArray::exactMatchSearch. As darts.h documents, a length of 0 is not "match zero bytes" but "the key is a zero-terminated C string", so the search abandons the length entirely and scanspiece.data()forward until it meets a NUL. For an empty piece that means it reads whatever lies at and afterdata(): a zero-length view onto live bytes spuriously matches the following key (an empty field fromabsl::StrSplitinspm_decode --input_format=piece, or a caller-suppliedabsl::string_viewslice, comes back as a non-<unk>id), and a view onto a non-terminated buffer runs off the end. I reproduced the latter directly against a darts trie under AddressSanitizer and it reports aheap-buffer-overflowREAD inside the C-string scan; the baseModelInterface::PieceToIdnever has this problem because it resolves empty pieces through its hash map.The root cause is passing an untrusted length of 0 to an API whose zero has special meaning, so the fix returns
unk_id_for an empty piece before the trie is touched. That matches the base-class contract and the existingPieceToId("")expectation, adds no work on the normal path, and leaves every non-empty lookup untouched. Left unfixed this is an out-of-bounds read reachable from the public decode surface, and a correctness bug that silently turns empty tokens into arbitrary vocabulary ids. The addedPieceToIdEmptyPieceTestfails on the current code (an empty view over"ab"returns 5) and passes with the change.