Skip to content
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

[Bugfix] Fix edge cases for MistralTokenizer #9625

Merged
merged 10 commits into from
Nov 1, 2024

Conversation

tjohnson31415
Copy link
Contributor

@tjohnson31415 tjohnson31415 commented Oct 23, 2024

We have encountered a couple of bugs when using --tokenizer-mode mistral with mistralai/Pixtral-12B-2409 (i.e. the V3-Tekken tokenizer) that cause the engine to crash with an error when certain tokens are generated. The exception is a KeyError when converting from strings to token ids, after converting from ids to string. Both bugs found occur becaue the code expects that each token id maps to a unique string and vice-versa, but the MistralTokenizer is byte-based and there are collisions between id and string due to the replacement character, �, replacing bytes of a partial UTF-8 codepoint.

One case we've seen is due to an empty string:

  File "/home/vllm/my-vllm/lib64/python3.12/site-packages/vllm/transformers_utils/tokenizers/mistral.py", line 223, in convert_tokens_to_string
    self.tokenizer._tekken_token2id_nospecial[t] + shift
  KeyError: b''

Which can be triggered with:

curl http://localhost:8000/v1/completions \
  -H "Content-Type: application/json" \
  -d '{
      "model": "mistralai/Pixtral-12B-2409",
      "prompt": "Repeat the phrase 'URGENCY🌶️'\nURGENCY🌶️\nURGENCY🌶️\n",
      "temperature": 0
  }'

The empty string is mapped from a token when the token id exceeds the len() of the tokenizer REF. With the Mistral Tokenizer, there is a mismatch in the length of the vLLM MistralTokenizer and the underlying Tekkenizer tokenizer:

>>> len(tokenizer)
130044

vs

>>> len(tokenizer.tokenizer.vocab())
131072

len(tokenizer) is computed as len(tokenizer._vocab) where _vocab is constructed as a Dict[str, int], i.e. text to id. The underlying Tekkenizer’s vocab() is a List[str]. The construction of the Dict is collapsing entries where the text matches. This occurs when the text contains the character replacing an incomplete codepoint:

>>> [(t, count) for t, count in collections.Counter(tokenizer.tokenizer.vocab()).items() if count > 1]
[('�', 606), (' �', 269), ('�다', 7), ('��', 101), ('ー�', 2), ('�்', 2), ('�i', 3), ('�്�', 4), (' 어�', 5), ('"�', 3), ('�ი', 3), ('�n', 2), ('�을', 3), ('�်�', 3), ('�ျ', 4), ('�ြ', 5), ('�ှ', 3), ('�్య', 3), ('�名', 2), ('�은', 4), ('�이', 3), ('�ွ', 3), (' 느�', 2), (' 바�', 2), ('�ng', 2), ('�니다', 2), ('�ို့', 2), ('�ံ', 2), ('�ան', 2), (' 나�', 3), (' 기�', 2)]

For the repro case above, it happens that the token id for CY is 130282 which is greater than 130044 and hence maps to an empty string. The '🌶️' is necessary in the repro to put bytes in the set of tokens being incrementally detokenized to go down the code path that maps from token strings back to ids here

The other crash we have seen is for a KeyError containing bytes:

  File "/home/vllm/my-vllm/lib64/python3.12/site-packages/vllm/transformers_utils/tokenizers/mistral.py", line 223, in convert_tokens_to_string
    self.tokenizer._tekken_token2id_nospecial[t] + shift
  KeyError: "Error in model execution: b'\\xe1\\x80\\x84\\xe1\\x80\\xba\\xef\\xbf\\xbd'"

Which can be triggered with:

curl http://localhost:8000/v1/completions \
  -H "Content-Type: application/json" \
  -d '{
      "model": "mistralai/Pixtral-12B-2409",
      "prompt": "ပုံပြင်လေးပြောပြပါ်\n",
      "temperature": 0
  }'

(The input is "Tell me a story\n" in Burmese.)

The cause of this one is when a token id is generated that has the replacement character as well as a valid codepoint. The stringified version of such a token will be like င်�. If these token strings go down the code path and are converted to bytes, the replacement character is replaced with its bytes and the full byte string, b'\xe1\x80\x84\xe1\x80\xba\xef\xbf\xbd' no longer maps to a token in the tokenizer. Tokens that stringify to a single are already handled with the fix in #8640.

FIX #9557

BEFORE SUBMITTING, PLEASE READ THE CHECKLIST BELOW AND FILL IN THE DESCRIPTION ABOVE


PR Checklist (Click to Expand)

Thank you for your contribution to vLLM! Before submitting the pull request, please ensure the PR meets the following criteria. This helps vLLM maintain the code quality and improve the efficiency of the review process.

PR Title and Classification

Only specific types of PRs will be reviewed. The PR title is prefixed appropriately to indicate the type of change. Please use one of the following:

  • [Bugfix] for bug fixes.
  • [CI/Build] for build or continuous integration improvements.
  • [Doc] for documentation fixes and improvements.
  • [Model] for adding a new model or improving an existing model. Model name should appear in the title.
  • [Frontend] For changes on the vLLM frontend (e.g., OpenAI API server, LLM class, etc.)
  • [Kernel] for changes affecting CUDA kernels or other compute kernels.
  • [Core] for changes in the core vLLM logic (e.g., LLMEngine, AsyncLLMEngine, Scheduler, etc.)
  • [Hardware][Vendor] for hardware-specific changes. Vendor name should appear in the prefix (e.g., [Hardware][AMD]).
  • [Misc] for PRs that do not fit the above categories. Please use this sparingly.

Note: If the PR spans more than one category, please include all relevant prefixes.

Code Quality

The PR need to meet the following code quality standards:

  • We adhere to Google Python style guide and Google C++ style guide.
  • Pass all linter checks. Please use format.sh to format your code.
  • The code need to be well-documented to ensure future contributors can easily understand the code.
  • Include sufficient tests to ensure the project to stay correct and robust. This includes both unit tests and integration tests.
  • Please add documentation to docs/source/ if the PR modifies the user-facing behaviors of vLLM. It helps vLLM user understand and utilize the new features or changes.

Adding or changing kernels

Each custom kernel needs a schema and one or more implementations to be registered with PyTorch.

  • Make sure custom ops are registered following PyTorch guidelines: Custom C++ and CUDA Operators and The Custom Operators Manual
  • Custom operations that return Tensors require meta-functions. Meta-functions should be implemented and registered in python so that dynamic dims can be handled automatically. See above documents for a description of meta-functions.
  • Use torch.libary.opcheck() to test the function registration and meta-function for any registered ops. See tests/kernels for examples.
  • When changing the C++ signature of an existing op, the schema must be updated to reflect the changes.
  • If a new custom type is needed, see the following document: Custom Class Support in PT2.

Notes for Large Changes

Please keep the changes as concise as possible. For major architectural changes (>500 LOC excluding kernel/data/config/test), we would expect a GitHub issue (RFC) discussing the technical design and justification. Otherwise, we will tag it with rfc-required and might not go through the PR.

What to Expect for the Reviews

The goal of the vLLM team is to be a transparent reviewing machine. We would like to make the review process transparent and efficient and make sure no contributor feel confused or frustrated. However, the vLLM team is small, so we need to prioritize some PRs over others. Here is what you can expect from the review process:

  • After the PR is submitted, the PR will be assigned to a reviewer. Every reviewer will pick up the PRs based on their expertise and availability.
  • After the PR is assigned, the reviewer will provide status update every 2-3 days. If the PR is not reviewed within 7 days, please feel free to ping the reviewer or the vLLM team.
  • After the review, the reviewer will put an action-required label on the PR if there are changes required. The contributor should address the comments and ping the reviewer to re-review the PR.
  • Please respond to all comments within a reasonable time frame. If a comment isn't clear or you disagree with a suggestion, feel free to ask for clarification or discuss the suggestion.

Thank You

Finally, thank you for taking the time to read these guidelines and for your interest in contributing to vLLM. Your contributions make vLLM a great tool for everyone!

Copy link

👋 Hi! Thank you for contributing to the vLLM project.
Just a reminder: PRs would not trigger full CI run by default. Instead, it would only run fastcheck CI which starts running only a small and essential subset of CI tests to quickly catch errors. You can run other CI tests on top of those by going to your fastcheck build on Buildkite UI (linked in the PR checks section) and unblock them. If you do not have permission to unblock, ping simon-mo or khluu to add you in our Buildkite org.

Once the PR is approved and ready to go, your PR reviewer(s) can run CI to test the changes comprehensively before merging.

To run CI, PR reviewers can do one of these:

  • Add ready label to the PR
  • Enable auto-merge.

🚀

@simon-mo
Copy link
Collaborator

@patrickvonplaten can you help take a look? thank you! 🙏

@prashantgupta24
Copy link
Contributor

I will be adding tests to it shortly!

Comment on lines 180 to 181
return self._vocab
# Convert to a Dict[str, int] to match protocol, but this is a lossy
# conversion. There may be multiple token ids that decode to the same
# string due to partial UTF-8 byte sequences being converted to �
return {token: idx for idx, token in enumerate(self._vocab)}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What is the advantage of doing this instead of doing:

self._vocab = {
    token: idx
    for idx, token in enumerate(tokenizer_.vocab())
}

in the init and just returning self._vocab? Seems like we don't have to recreate the dict every time no?

Copy link
Contributor

@prashantgupta24 prashantgupta24 Oct 24, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I believe that's because the conversion to a Dict[str, int] is a lossy conversion. This results in a vocab size that's less than what the actual vocab is. If you look at #9557 (comment), you will see that if the model tries to print something outside of this lossy vocab, it will result in an error

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If this is just for vocab_size though, that could just stored as a separate field.

Another option is to memoize this method with @functools.cache.

I am wondering though if there may be a better option that avoids string-encoding incomplete byte sequences altogether

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am wondering though if there may be a better option that avoids string-encoding incomplete byte sequences altogether

Yeah, I think there is a refactor that could happen here, but also wanted to create a quick fix. I'll need to spend some more time looking at how the tokenizers are used to propose a refactor.

@patrickvonplaten
Copy link
Contributor

Hey @tjohnson31415,

Thanks a lot for the PR, could you post an example of an LLM generation where mistral-nemo fails? I'm seeing a failure case here: #9557 (comment) but it does not include a model generation example.

It would be good to have an example where a model generation leads to a failure case and not just the convert_tokens_to_string function.

I'm not sure it's a good idea to ensure that the convert_tokens_to_string function never raises. It's definitely important that generations never fail so it would be amazing to see a failure case where pixtral or mistral-nemo generates ids that cannot be detokenized

@prashantgupta24
Copy link
Contributor

prashantgupta24 commented Oct 24, 2024

@patrickvonplaten I commented on the issue #9557 (comment)

Unfortunately I still don't have a simple way of reproducing the failures (apart from a custom prompt which we've been using internally but I have to confirm if I can share it), will keep on trying. It usually happens on load testing while sampling.

@tjohnson31415
Copy link
Contributor Author

@patrickvonplaten @prashantgupta24 I expanded on the PR description to give full repro examples going through v1/completions.

@patrickvonplaten
Copy link
Contributor

Checking now - sorry for the delay!

Copy link
Contributor

@patrickvonplaten patrickvonplaten left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Only managed now to look into it. I can reproduce the error and you are right in that I missed the edge case where a token is converted not only into a "a�" e.g. a non-complete unicode sequence including another character in the beginning!

Great catch!

The changes done to the def convert_tokens_to_string make a lot of sense to me.

The only thing I have still trouble understanding why we can't just save the created dict at init - I don't see how this would change anything (and it also worked in my experiments)

@patrickvonplaten
Copy link
Contributor

Thanks a ton @tjohnson31415 and @prashantgupta24 for providing the examples and fixing it!

Copy link
Member

@njhill njhill left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@njhill njhill added the ready ONLY add when PR is ready to merge/full CI is needed label Oct 30, 2024
… with API of other tokenizers

Signed-off-by: Travis Johnson <[email protected]>
@tjohnson31415
Copy link
Contributor Author

I did a little bit of refactoring,rebased onmain, and got the tests passing. The one remaining test failure in CI is due to a ReadTimeout fetching model files from HF Hub:

[2024-10-31T06:18:46Z] E               requests.exceptions.ReadTimeout: (ReadTimeoutError("HTTPSConnectionPool(host='huggingface.co', port=443): Read timed out. (read timeout=10)"), '(Request ID: b8e54c7f-6b55-406c-a321-047fe5e31227)')
...
[2024-10-31T06:18:46Z] E           OSError: We couldn't connect to 'https://huggingface.co' to load this file, couldn't find it in the cached files and it looks like facebook/opt-125m is not the path to a directory containing a file named config.json.
--
  | [2024-10-31T06:18:46Z] E           Checkout your internet connection or see how to run the library in offline mode at 'https://huggingface.co/docs/transformers/installation#offline-mode'.
  | [2024-10-31T06:18:46Z]
  | [2024-10-31T06:18:46Z] /usr/local/lib/python3.12/dist-packages/transformers/utils/hub.py:446: OSError
  | [2024-10-31T06:18:46Z] =============================== warnings summary ===============================

@njhill Is there a way to re-run just the failing test?


In updating the tests, I found another bug... The test_mistral_symbolic_languages actually overwrites prompt = "hi", so it wasn't actually testing what it was supposed to. When that line is removed the symbolic tests fail for mistralai/Mistral-Nemo-Instruct-2407. I'm still looking into this, but I think it is separate from the problems fixed in this PR.

@njhill njhill merged commit 1dd4cb2 into vllm-project:main Nov 1, 2024
55 checks passed
@tjohnson31415 tjohnson31415 deleted the fix-mixtral-tokenizer branch November 1, 2024 19:24
DarkLight1337 pushed a commit that referenced this pull request Nov 2, 2024
Signed-off-by: Travis Johnson <[email protected]>
Signed-off-by: Prashant Gupta <[email protected]>
Co-authored-by: Prashant Gupta <[email protected]>
Co-authored-by: Patrick von Platen <[email protected]>
lk-chen pushed a commit to lk-chen/vllm that referenced this pull request Nov 4, 2024
Signed-off-by: Travis Johnson <[email protected]>
Signed-off-by: Prashant Gupta <[email protected]>
Co-authored-by: Prashant Gupta <[email protected]>
Co-authored-by: Patrick von Platen <[email protected]>
lk-chen pushed a commit to lk-chen/vllm that referenced this pull request Nov 4, 2024
Signed-off-by: Travis Johnson <[email protected]>
Signed-off-by: Prashant Gupta <[email protected]>
Co-authored-by: Prashant Gupta <[email protected]>
Co-authored-by: Patrick von Platen <[email protected]>
Signed-off-by: Linkun Chen <[email protected]>
richardsliu pushed a commit to richardsliu/vllm that referenced this pull request Nov 4, 2024
Signed-off-by: Travis Johnson <[email protected]>
Signed-off-by: Prashant Gupta <[email protected]>
Co-authored-by: Prashant Gupta <[email protected]>
Co-authored-by: Patrick von Platen <[email protected]>
Signed-off-by: Richard Liu <[email protected]>
bigPYJ1151 pushed a commit to bigPYJ1151/vllm that referenced this pull request Nov 5, 2024
Signed-off-by: Travis Johnson <[email protected]>
Signed-off-by: Prashant Gupta <[email protected]>
Co-authored-by: Prashant Gupta <[email protected]>
Co-authored-by: Patrick von Platen <[email protected]>
DarkLight1337 pushed a commit that referenced this pull request Nov 5, 2024
Signed-off-by: Travis Johnson <[email protected]>
Signed-off-by: Prashant Gupta <[email protected]>
Co-authored-by: Prashant Gupta <[email protected]>
Co-authored-by: Patrick von Platen <[email protected]>
DarkLight1337 pushed a commit that referenced this pull request Nov 5, 2024
Signed-off-by: Travis Johnson <[email protected]>
Signed-off-by: Prashant Gupta <[email protected]>
Co-authored-by: Prashant Gupta <[email protected]>
Co-authored-by: Patrick von Platen <[email protected]>
hissu-hyvarinen pushed a commit to ROCm/vllm that referenced this pull request Nov 6, 2024
Signed-off-by: Travis Johnson <[email protected]>
Signed-off-by: Prashant Gupta <[email protected]>
Co-authored-by: Prashant Gupta <[email protected]>
Co-authored-by: Patrick von Platen <[email protected]>
JC1DA pushed a commit to JC1DA/vllm that referenced this pull request Nov 11, 2024
Signed-off-by: Travis Johnson <[email protected]>
Signed-off-by: Prashant Gupta <[email protected]>
Co-authored-by: Prashant Gupta <[email protected]>
Co-authored-by: Patrick von Platen <[email protected]>
Signed-off-by: Loc Huynh <[email protected]>
sumitd2 pushed a commit to sumitd2/vllm that referenced this pull request Nov 14, 2024
Signed-off-by: Travis Johnson <[email protected]>
Signed-off-by: Prashant Gupta <[email protected]>
Co-authored-by: Prashant Gupta <[email protected]>
Co-authored-by: Patrick von Platen <[email protected]>
Signed-off-by: Sumit Dubey <[email protected]>
KuntaiDu pushed a commit to KuntaiDu/vllm that referenced this pull request Nov 20, 2024
Signed-off-by: Travis Johnson <[email protected]>
Signed-off-by: Prashant Gupta <[email protected]>
Co-authored-by: Prashant Gupta <[email protected]>
Co-authored-by: Patrick von Platen <[email protected]>
mfournioux pushed a commit to mfournioux/vllm that referenced this pull request Nov 20, 2024
Signed-off-by: Travis Johnson <[email protected]>
Signed-off-by: Prashant Gupta <[email protected]>
Co-authored-by: Prashant Gupta <[email protected]>
Co-authored-by: Patrick von Platen <[email protected]>
Signed-off-by: Maxime Fournioux <[email protected]>
tlrmchlsmth pushed a commit to neuralmagic/vllm that referenced this pull request Nov 23, 2024
Signed-off-by: Travis Johnson <[email protected]>
Signed-off-by: Prashant Gupta <[email protected]>
Co-authored-by: Prashant Gupta <[email protected]>
Co-authored-by: Patrick von Platen <[email protected]>
Signed-off-by: Tyler Michael Smith <[email protected]>
sleepwalker2017 pushed a commit to sleepwalker2017/vllm that referenced this pull request Dec 13, 2024
Signed-off-by: Travis Johnson <[email protected]>
Signed-off-by: Prashant Gupta <[email protected]>
Co-authored-by: Prashant Gupta <[email protected]>
Co-authored-by: Patrick von Platen <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
ready ONLY add when PR is ready to merge/full CI is needed
Projects
None yet
Development

Successfully merging this pull request may close these issues.

[Bug]: MistralTokenizer Detokenization Issue
5 participants