8000 Fix UTF-8 handling with grammars by jsoma · Pull Request #1415 · abetlen/llama-cpp-python · GitHub
[go: up one dir, main page]

Skip to content

Fix UTF-8 handling with grammars #1415

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 30, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
8000
Diff view
Diff view
16 changes: 5 additions & 11 deletions llama_cpp/llama_grammar.py
Original file line number Diff line number Diff line change
Expand Up @@ -556,17 +556,11 @@ def add_rule(
# }
def decode_utf8(src: const_char_p) -> Tuple[int, const_char_p]:
"""Decodes a UTF-8 character from the source string."""
lookup = (1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 3, 4)
first_byte = ord(src[0]) # type: int
highbits = first_byte >> 4 # type: int
len = lookup[highbits] # type: int
mask = (1 << (8 - len)) - 1 # type: int
value = first_byte & mask # type: int
end = src + len # type: const_char_p # may overrun!
pos = src + 1 # type: const_char_p
while pos < end and pos[0]:
value = (value << 6) + (ord(pos[0]) & 0x3F)
pos += 1
# Get the codepoint of the first character
value = ord(src[0])
# Move the pointer ahead one character
pos = src + 1

return value, pos


Expand Down
0