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

[Model] Add Mistral Tokenization to improve robustness and chat encoding #7739

Merged
merged 66 commits into from
Aug 27, 2024

Conversation

patrickvonplaten
Copy link
Contributor

@patrickvonplaten patrickvonplaten commented Aug 21, 2024

Add official MistralTokenizer

The official mistral models (from https://huggingface.co/mistralai) are not fully tested with HF tokenizers and
we it tends to happen that there are encoding / decoder and especially chat encoding problems.

Mistral models are only fully tested with https://github.com/mistralai/mistral-common which provides a robust
and simple API for encoding and chat encoding. It is designed in a very similar fashion as openai chat completion
design and therefore simplifies the logic for Mistral models in vllm/entrypoints/openai/serving_chat.py significantly.

Important: This PR is fully backwards compatible. By default Mistral models will still use Hugging Face tokenizers, however a warning is thrown when official Mistral models (those from https://huggingface.co/mistralai) are used to instead pass --tokenizer-mode="mistral".

The PR has been tested to work on both Tekkenizer and SPM models of Mistral. Both for offline inference and serve:

Offline Batched Inference

Completion

from vllm import LLM, SamplingParams

prompts = [
    "Hello, my name is",
    "The president of the United States is",
    "The capital of France is",
    "The future of AI is",
]
sampling_params = SamplingParams(temperature=0.8, top_p=0.95)

for model in ["mistralai/Mistral-Nemo-Base-2407"]:  # or "mistralai/Mistral-7B-Instruct-v0.3"
    llm = LLM(model=model, tokenizer_mode="mistral", max_model_len=8192)

    outputs = llm.generate(prompts, sampling_params)

    print(outputs)

    # Print the outputs.
    for output in outputs:
        prompt = output.prompt
        generated_text = output.outputs[0].text
        print(f"Prompt: {prompt!r}, Generated text: {generated_text!r}")

Chat

from vllm import LLM, SamplingParams

sampling_params = SamplingParams(temperature=0.8, top_p=0.95)

for model in ["mistralai/Mistral-Nemo-Base-2407"]: # or "mistralai/Mistral-7B-Instruct-v0.3"
    llm = LLM(model=model, tokenizer_mode="mistral", max_model_len=8192)

    prompt1 = "Explain the concept of entropy."
    messages = [
        {
            "role": "system",
            "content": "You are a helpful assistant"
        },
        {
            "role": "user",
            "content": prompt1
        },
    ]
    outputs = llm.chat(messages)

    print(outputs)

Server

Also both completion and chat completion server work when runnnig:

vllm serve mistralai/Mistral-Nemo-Instruct-2407 --tokenizer_mode mistral --max_model_len 8192

E.g. with:

curl http://slurm-reserved-114-002:8000/v1/chat/completions \
-H "Content-Type: application/json" \
-d '{
"model": "mistralai/Mistral-Nemo-Instruct-2407",
"messages": [
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Who won the world series in 2020?"}
]
}'

TODO:

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.

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!

@patrickvonplaten patrickvonplaten changed the title Add mistral common Add mistral common for tokenization Aug 21, 2024
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 consists a small and essential subset of CI tests to quickly catch errors. You can run other CI tests on top of default ones by unblocking the steps in your fast-check build on Buildkite UI.

Once the PR is approved and ready to go, please make sure to run full CI as it is required to merge (or just use auto-merge).

To run full CI, you can do one of these:

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

🚀

@patrickvonplaten patrickvonplaten changed the title Add mistral common for tokenization [Model] Add official Mistral Tokenization to improve robustness and chat encoding Aug 21, 2024
@Inktomi93
Copy link

@patrickvonplaten Just a thing to note: this pull request seems to break the ability to load model files outside of the HuggingFace Cache (i.e., a model saved to a different directory). Is this intended? If not, is there any way it could be adjusted to accept the mistral tokenizer manually via a directory or another model path?
Also if I download a GPTQ quant of a mistral model (Just using GPTQ as an example. The model doesn't seem to load properly, so it also seems like it would benefit from being able to specify the tokenizer directory for the Mistral Tokenizer.
For context on this, I download the mistral models to a separate directory so that I don't have to deal with the Consolidated safetensor files clogging up my disk. So having the option to load from a local directory outside of the HF Hub would be appreciated.

This makes sense - you mean loading a Mistral model from a local directory that has both downloaded HF models and the mistral tokenizer no?

Correct, so normally when I run vllm I launch it with:

vllm serve /home/inktomi/text-generation-webui/models/Mistral-7B-Instruct-v0.3

or

vllm serve /home/inktomi/text-generation-webui/models/Mistral-7B-Instruct-v0.3-GPTQ

When I specify --tokenizer-mode mistral when launching this way, it will throw an hf-hub error since the model it is loading isn't a repo.

@patrickvonplaten
Copy link
Contributor Author

Union[str, List[int]]

Just fixed it - could you try again with newest commit? Think it should work now :-)

@patrickvonplaten
Copy link
Contributor Author

It'd be great if we could give apply_chat_template a new API here in that it returns a string and also optionally a list of ints.

That make sense to me. You can change the interface to return Union[str, List[int]]

Cool, just changed the interface to return Union[str, List[int]]. Tests seem to be passing as well for me locally

@Inktomi93
Copy link

Union[str, List[int]]

Just fixed it - could you try again with newest commit? Think it should work now :-)

Built with the updates and it works perfectly. Thank you!

@Inktomi93
Copy link

@patrickvonplaten After some testing, for some reason when using Mistral-Nemo-Instruct-2407 and using the mistral tokenizer mode I get the following error "POST /v1/chat/completions HTTP/1.1" 400 Bad Request when attempting to send a request.
But when I load up Mistral-7B-Instruct-v0.3 it performs normally without issue. In my directory I have tekken.json. Is there something I should adjust?

@patrickvonplaten
Copy link
Contributor Author

patrickvonplaten commented Aug 24, 2024

@patrickvonplaten After some testing, for some reason when using Mistral-Nemo-Instruct-2407 and using the mistral tokenizer mode I get the following error "POST /v1/chat/completions HTTP/1.1" 400 Bad Request when attempting to send a request. But when I load up Mistral-7B-Instruct-v0.3 it performs normally without issue. In my directory I have tekken.json. Is there something I should adjust?

Thanks a bunch for testing it out again!!

I think it should be fixed in this commit: 4e99ef4 . Can you pull again and give it a try?

We usually don't allow to decode special tokens with Mistral's Nemo's tokenizer, but it seems like this is sometimes necessary for VLLM (e.g. when decoding the chat template). Changed the default policy now to ignore special tokens so that this error doesn't happen anymore. The following now works for me just fine:

vllm serve ./mistral_nemo_instruct --max_model_len 8192 --tokenizer_mode "mistral"

with ll mistral_nemo_instruct giving:

-rw-rw---- 1 root root  623 Aug 24 11:10 config.json
-rw-rw---- 1 root root 4.6G Aug 24 11:11 model-00001-of-00005.safetensors
-rw-rw---- 1 root root 4.6G Aug 24 11:11 model-00002-of-00005.safetensors
-rw-rw---- 1 root root 4.6G Aug 24 11:11 model-00003-of-00005.safetensors
-rw-rw---- 1 root root 4.6G Aug 24 11:11 model-00004-of-00005.safetensors
-rw-rw---- 1 root root 4.6G Aug 24 11:11 model-00005-of-00005.safetensors
-rw-rw---- 1 root root  30K Aug 24 11:11 model.safetensors.index.json
-rw-rw---- 1 root root  15M Aug 24 11:11 tekken.json

@Inktomi93
Copy link

@patrickvonplaten After some testing, for some reason when using Mistral-Nemo-Instruct-2407 and using the mistral tokenizer mode I get the following error "POST /v1/chat/completions HTTP/1.1" 400 Bad Request when attempting to send a request. But when I load up Mistral-7B-Instruct-v0.3 it performs normally without issue. In my directory I have tekken.json. Is there something I should adjust?

Thanks a bunch for testing it out again!!

I think it should be fixed in this commit: 4e99ef4 . Can you pull again and give it a try?

We usually don't allow to decode special tokens with Mistral's Nemo's tokenizer, but it seems like this is sometimes necessary for VLLM (e.g. when decoding the chat template). Changed the default policy now to ignore special tokens so that this error doesn't happen anymore. The following now works for me just fine:

vllm serve ./mistral_nemo_instruct --max_model_len 8192 --tokenizer_mode "mistral"

with ll mistral_nemo_instruct giving:

-rw-rw---- 1 root root  623 Aug 24 11:10 config.json
-rw-rw---- 1 root root 4.6G Aug 24 11:11 model-00001-of-00005.safetensors
-rw-rw---- 1 root root 4.6G Aug 24 11:11 model-00002-of-00005.safetensors
-rw-rw---- 1 root root 4.6G Aug 24 11:11 model-00003-of-00005.safetensors
-rw-rw---- 1 root root 4.6G Aug 24 11:11 model-00004-of-00005.safetensors
-rw-rw---- 1 root root 4.6G Aug 24 11:11 model-00005-of-00005.safetensors
-rw-rw---- 1 root root  30K Aug 24 11:11 model.safetensors.index.json
-rw-rw---- 1 root root  15M Aug 24 11:11 tekken.json

Everything works properly now. It was tested with both types of tokenizers and could send chats successfully. Thank you so much for putting this together, Being able to use the Mistral Common and tokenizer directly has been something on my wishlist for a long time.

@simon-mo simon-mo added the ready ONLY add when PR is ready to merge/full CI is needed label Aug 26, 2024
@simon-mo simon-mo enabled auto-merge (squash) August 26, 2024 23:27
@patrickvonplaten
Copy link
Contributor Author

To me it looks like the failing test is unrelated:

--
  | [2024-08-26T23:55:48Z] Traceback (most recent call last):
  | [2024-08-26T23:55:48Z]   File "/usr/local/lib/python3.10/dist-packages/uvicorn/server.py", line 162, in startup
  | [2024-08-26T23:55:48Z]     server = await loop.create_server(
  | [2024-08-26T23:55:48Z]   File "/usr/lib/python3.10/asyncio/base_events.py", line 1519, in create_server
  | [2024-08-26T23:55:48Z]     raise OSError(err.errno, 'error while attempting '
  | [2024-08-26T23:55:48Z] OSError: [Errno 98] error while attempting to bind on address ('0.0.0.0', 32899): address already in use
  | [2024-08-26T23:55:48Z]
  | [2024-08-26T23:55:48Z] During handling of the above exception, another exception occurred:
  | [2024-08-26T23:55:48Z]
  | [2024-08-26T23:55:48Z] Traceback (most recent call last):
  | [2024-08-26T23:55:48Z]   File "/usr/local/lib/python3.10/dist-packages/uvicorn/server.py", line 69, in serve
  | [2024-08-26T23:55:48Z]     await self._serve(sockets)
  | [2024-08-26T23:55:48Z]   File "/usr/local/lib/python3.10/dist-packages/uvicorn/server.py", line 84, in _serve
  | [2024-08-26T23:55:48Z]     await self.startup(sockets=sockets)
  | [2024-08-26T23:55:48Z]   File "/usr/local/lib/python3.10/dist-packages/uvicorn/server.py", line 172, in startup
  | [2024-08-26T23:55:48Z]     sys.exit(1)
  | [2024-08-26T23:55:48Z] SystemExit: 1
  | [2024-08-26T23:55:48Z]

Any tips on how to move forward here @simon-mo ?

@simon-mo simon-mo merged commit 6fc4e6e into vllm-project:main Aug 27, 2024
64 checks passed
triple-Mu pushed a commit to triple-Mu/vllm_official that referenced this pull request Sep 4, 2024
Jeffwan pushed a commit to aibrix/vllm that referenced this pull request Sep 19, 2024
Alvant pushed a commit to compressa-ai/vllm that referenced this pull request Oct 26, 2024
Comment on lines +143 to +147
assert isinstance(prompt, list) and isinstance(
prompt[0], int
), "Prompt has to be either a string or a list of token ids"
prompt_inputs = TextTokensPrompt(
prompt=tokenizer.decode(prompt), prompt_token_ids=prompt)
Copy link
Member

Choose a reason for hiding this comment

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

I'm currently working on refactoring some of the chat API code. @patrickvonplaten is there a particular reason why self._tokenize_prompt_input doesn't work on the prompt tokens outputted by mistral tokenizer?

KuntaiDu pushed a commit to KuntaiDu/vllm that referenced this pull request Nov 20, 2024
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.

5 participants