fix(py): make encode_with_unstable handle surrogates like encode (#541)#556
Open
LeSingh1 wants to merge 1 commit into
Open
fix(py): make encode_with_unstable handle surrogates like encode (#541)#556LeSingh1 wants to merge 1 commit into
LeSingh1 wants to merge 1 commit into
Conversation
…nai#541) encode and encode_ordinary already catch UnicodeEncodeError raised by the Rust BPE when the input string contains surrogate pairs / lone surrogates, then retry after a UTF-16 "surrogatepass" + "replace" round-trip. encode_with_unstable did not, so the same inputs that worked through encode raised UnicodeEncodeError here. Mirror the same try / except / repair pattern so the three encode paths agree on what inputs they accept.
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.
Closes #541.
Encoding.encodeandEncoding.encode_ordinaryalready catchUnicodeEncodeErrorraised by the Rust BPE when the input string contains surrogate pairs or lone surrogates, then retry after a UTF-16surrogatepass+replaceround-trip.Encoding.encode_with_unstabledid not, so the same inputs that worked throughencoderaisedUnicodeEncodeErrorhere.This PR mirrors the same try / except / repair pattern so the three encode paths agree on what inputs they accept.
Repro (against current main)
Verification
Added
test_encode_with_unstable_surrogate_pairsintests/test_encoding.py. The test fails onmainwith the exactUnicodeEncodeErrorquoted in #541 and passes on this branch. I confirmed locally:The new test cross-checks the stable prefix against
enc.encode(...)to ensure both paths agree on the resulting tokens, not just that no exception is raised.Scope
Single-file change in
tiktoken/core.py(8-line try / except wrap mirroringencode's) plus one regression test.