Fix generation of multi-token unicode characters #738
Merged
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.
This PR fixes generation of unicode strings that can only be represented by sequences of multiple tokens (closes #725).
Currently, outlines will prevent any such characters from being generated at all, even with
'.*'
regex. This creates a major problem when generating text in non-latin languages, or generating special characters like emojis.This PR addresses this problem by converting character-level regex FSMs to byte-level FSMs. More precisely, it augments the FSM by adding byte-by-byte transitions that can be triggered by sub-character tokens generated by the LLM. The full-character transitions are kept as-is, so the performance of generation for normal tokens isn't impacted.
I considered other design choices, including keeping the logic of dealing with such tokens in the
RegexGuide
class. I don't think it can work at least for GPT2-like tokenizers (which includes gpt2, phi, qwen and other models). Such tokenizers have tokens that combine full utf8 characters followed by parts of the next character (for example,b'\x20\xf0'
), and deciding whether to accept such tokens requires walking the FSM.