fix: correctly decode numpy UCS-4 arrays instead of treating as UTF-8 - #2386
Open
VirajMishra1 wants to merge 1 commit into
Open
VirajMishra1 wants to merge 1 commit into
VirajMishra1 wants to merge 1 commit into
Conversation
PyArrayUnicode passed numpy dtype='U' array bytes directly to
std::str::from_utf8(), but numpy stores Unicode strings as UCS-4
(UTF-32LE on little-endian systems), not UTF-8.
This caused:
- ASCII strings: silent data corruption (embedded null bytes)
- Non-ASCII strings: ValueError('invalid utf-8 sequence')
Fix: decode 4-byte chunks as UTF-32LE code points and collect to
String, properly handling the UCS-4 encoding numpy uses.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
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.
PyArrayUnicodein the Python bindings passes raw numpydtype='U'array bytes directly tostd::str::from_utf8(). But numpy stores Unicode strings as UCS-4 (UTF-32LE on little-endian), not UTF-8. This causes:"hello"becomes"h\0\0\0e\0\0\0l\0\0\0l\0\0\0o\0\0\0")ValueError('invalid utf-8 sequence')for any input containing accented characters, CJK, emoji, etc.The commented-out code directly below the broken path (using
PyUnicode_FromKindAndDatawithPyUnicode_4BYTE_KIND) was the correct approach but was replaced with thefrom_utf8call.Fix
Decode 4-byte chunks as UTF-32LE code points (
u32::from_le_bytes), filter null padding, convert viachar::from_u32, and collect toString. This correctly handles numpy's UCS-4 encoding for all Unicode inputs.Test
Added
test_numpy_unicode_ucs4inbindings/python/tests/bindings/test_tokenizer.pycovering ASCII, CJK, and emoji inputs through numpydtype='U'arrays.