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
Merged
Show file tree
Hide file tree
Changes from 8 commits
Commits
Show all changes
66 commits
Select commit Hold shift + click to select a range
f64f664
WIP
patrickvonplaten Aug 21, 2024
99abde0
WIP
patrickvonplaten Aug 21, 2024
441628b
WIP
patrickvonplaten Aug 21, 2024
3d13b50
WIP
patrickvonplaten Aug 21, 2024
b2f2b2f
WIP
patrickvonplaten Aug 21, 2024
e2b4f29
Reformat
patrickvonplaten Aug 21, 2024
d6bb4d8
Up
patrickvonplaten Aug 21, 2024
3d046b6
Update vllm/entrypoints/chat_utils.py
patrickvonplaten Aug 21, 2024
cfbe3cd
Apply suggestions from code review
patrickvonplaten Aug 21, 2024
8c7d0cf
Apply suggestions from code review
patrickvonplaten Aug 21, 2024
fb092dc
Apply suggestions from code review
patrickvonplaten Aug 21, 2024
9e2df7b
Update vllm/entrypoints/openai/serving_chat.py
patrickvonplaten Aug 21, 2024
662e1ce
Apply suggestions from code review
patrickvonplaten Aug 21, 2024
a56425e
Update vllm/transformers_utils/detokenizer.py
patrickvonplaten Aug 21, 2024
a3744fe
Update vllm/transformers_utils/detokenizer.py
patrickvonplaten Aug 21, 2024
513b4f5
Update vllm/transformers_utils/detokenizer.py
patrickvonplaten Aug 21, 2024
6981440
Update vllm/transformers_utils/detokenizer.py
patrickvonplaten Aug 21, 2024
373bbe7
Apply suggestions from code review
patrickvonplaten Aug 21, 2024
bd00d7d
more format
patrickvonplaten Aug 21, 2024
1ae7b5b
More format
patrickvonplaten Aug 21, 2024
ba4d770
isort
patrickvonplaten Aug 21, 2024
59dd456
isort
patrickvonplaten Aug 21, 2024
73a8341
up
patrickvonplaten Aug 21, 2024
0221276
up
patrickvonplaten Aug 21, 2024
2dee65b
up
patrickvonplaten Aug 21, 2024
f32c3db
up
patrickvonplaten Aug 21, 2024
a7a282d
finish
patrickvonplaten Aug 21, 2024
5460ab6
finish
patrickvonplaten Aug 21, 2024
ba290a4
finish
patrickvonplaten Aug 21, 2024
1780de7
finish
patrickvonplaten Aug 21, 2024
e0e9de1
Merge branch 'main' into add_mistral_common
patrickvonplaten Aug 21, 2024
7034e3a
Update vllm/entrypoints/llm.py
patrickvonplaten Aug 21, 2024
4e543f8
yapf again
patrickvonplaten Aug 21, 2024
0a3ccb4
WIP
patrickvonplaten Aug 22, 2024
dd943da
Merge branch 'add_mistral_common' of https://github.com/patrickvonpla…
patrickvonplaten Aug 22, 2024
5dd4458
Apply suggestions from code review
patrickvonplaten Aug 22, 2024
5c469d6
WIP
patrickvonplaten Aug 22, 2024
9e6e239
WIP
patrickvonplaten Aug 22, 2024
18cff00
yapf again
patrickvonplaten Aug 22, 2024
f711795
yapf again
patrickvonplaten Aug 22, 2024
31a04a9
Up
patrickvonplaten Aug 22, 2024
7a02d3b
Up
patrickvonplaten Aug 22, 2024
b921956
WIP
patrickvonplaten Aug 22, 2024
ec3f035
WIP
patrickvonplaten Aug 22, 2024
d18dc1a
Up
patrickvonplaten Aug 22, 2024
908beed
finish
patrickvonplaten Aug 22, 2024
39a9234
WIP
patrickvonplaten Aug 22, 2024
911ec07
Merge branch 'add_mistral_common' of https://github.com/patrickvonpla…
patrickvonplaten Aug 22, 2024
002d0cf
WIP
patrickvonplaten Aug 22, 2024
ba25ce7
finish
patrickvonplaten Aug 22, 2024
4dbf270
WIP
patrickvonplaten Aug 22, 2024
e1a190c
Merge branch 'add_mistral_common' of https://github.com/patrickvonpla…
patrickvonplaten Aug 22, 2024
50296c5
WIP
patrickvonplaten Aug 22, 2024
cb48bfc
WIP
patrickvonplaten Aug 22, 2024
3d43014
WIP
patrickvonplaten Aug 22, 2024
1481229
WIP
patrickvonplaten Aug 22, 2024
4963015
finish
patrickvonplaten Aug 22, 2024
25ceeb1
finish
patrickvonplaten Aug 22, 2024
4e99ef4
WIP
patrickvonplaten Aug 24, 2024
91e5027
isort
patrickvonplaten Aug 24, 2024
61c1817
Trigger CI build
patrickvonplaten Aug 25, 2024
daf9a25
Trigger CI build
patrickvonplaten Aug 25, 2024
e3c8046
Trigger CI build
patrickvonplaten Aug 25, 2024
eba5658
Trigger CI build
patrickvonplaten Aug 27, 2024
ba08ee6
Trigger CI build
patrickvonplaten Aug 27, 2024
b905f1e
Trigger CI build
patrickvonplaten Aug 27, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions requirements-common.txt
Original file line number Diff line number Diff line change
Expand Up @@ -26,3 +26,4 @@ librosa # Required for audio processing
soundfile # Required for audio processing
gguf == 0.9.1
importlib_metadata
mistral_common >= 1.3.4
4 changes: 2 additions & 2 deletions vllm/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -238,10 +238,10 @@ def _init_multimodal_config(

def _verify_tokenizer_mode(self) -> None:
tokenizer_mode = self.tokenizer_mode.lower()
if tokenizer_mode not in ["auto", "slow"]:
if tokenizer_mode not in ["auto", "slow", "mistral"]:
raise ValueError(
f"Unknown tokenizer mode: {self.tokenizer_mode}. Must be "
"either 'auto' or 'slow'.")
"either 'auto', 'slow' or 'mistral'.")
self.tokenizer_mode = tokenizer_mode

def _verify_embedding_mode(self) -> None:
Expand Down
2 changes: 1 addition & 1 deletion vllm/engine/arg_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -197,7 +197,7 @@ def add_cli_args(parser: FlexibleArgumentParser) -> FlexibleArgumentParser:
'--tokenizer-mode',
type=str,
default=EngineArgs.tokenizer_mode,
choices=['auto', 'slow'],
choices=['auto', 'slow', 'mistral'],
help='The tokenizer mode.\n\n* "auto" will use the '
'fast tokenizer if available.\n* "slow" will '
'always use the slow tokenizer.')
Expand Down
32 changes: 23 additions & 9 deletions vllm/entrypoints/chat_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,16 @@
from dataclasses import dataclass
from functools import lru_cache
from pathlib import Path
from typing import (Any, Awaitable, Iterable, List, Literal, Optional, Tuple,
Union)
from typing import (
Any,
Awaitable,
Iterable,
List,
Literal,
Optional,
Tuple,
Union,
)

# yapf conflicts with isort for this block
# yapf: disable
Expand All @@ -21,9 +29,11 @@
from vllm.config import ModelConfig
from vllm.logger import init_logger
from vllm.multimodal import MultiModalDataDict
from vllm.multimodal.utils import (async_get_and_parse_audio,
async_get_and_parse_image)
from vllm.transformers_utils.tokenizer import AnyTokenizer
from vllm.multimodal.utils import (
async_get_and_parse_audio,
async_get_and_parse_image,
)
from vllm.transformers_utils.tokenizer import AnyTokenizer, AnyHFTokenizer

logger = init_logger(__name__)

Expand Down Expand Up @@ -56,6 +66,7 @@ class CustomChatCompletionContentPartParam(TypedDict, total=False):

class CustomChatCompletionMessageParam(TypedDict, total=False):
"""Enables custom roles in the Chat Completion API."""

role: Required[str]
"""The role of the message's author."""

Expand Down Expand Up @@ -87,7 +98,7 @@ class ChatMessageParseResult:


def load_chat_template(
chat_template: Optional[Union[Path, str]]) -> Optional[str]:
chat_template: Optional[Union[Path, str]]) -> Optional[str]:
if chat_template is None:
return None
try:
Expand All @@ -113,8 +124,11 @@ def load_chat_template(


@lru_cache(maxsize=None)
def _mm_token_str(model_config: ModelConfig, tokenizer: AnyTokenizer,
modality: Literal["image", "audio"]) -> Optional[str]:
def _mm_token_str(
model_config: ModelConfig,
tokenizer: AnyHFTokenizer,
modality: Literal["image", "audio"],
) -> Optional[str]:
# TODO: Let user specify how to insert image tokens into prompt
# (similar to chat template)
if modality == "image":
Expand Down Expand Up @@ -259,7 +273,7 @@ def parse_chat_messages(


def apply_chat_template(
tokenizer: AnyTokenizer,
tokenizer: AnyHFTokenizer,
conversation: List[ConversationMessage],
chat_template: Optional[str],
*,
Expand Down
83 changes: 52 additions & 31 deletions vllm/entrypoints/llm.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,22 +5,29 @@

from vllm.engine.arg_utils import EngineArgs
from vllm.engine.llm_engine import LLMEngine
from vllm.entrypoints.chat_utils import (ChatCompletionMessageParam,
apply_chat_template,
parse_chat_messages)
from vllm.entrypoints.chat_utils import (
ChatCompletionMessageParam,
apply_chat_template,
parse_chat_messages,
)
patrickvonplaten marked this conversation as resolved.
Show resolved Hide resolved
from vllm.inputs import PromptInputs, TextPrompt, TokensPrompt
from vllm.inputs.parse import parse_and_batch_prompt
from vllm.logger import init_logger
from vllm.lora.request import LoRARequest
from vllm.model_executor.guided_decoding import (
GuidedDecodingRequest, get_local_guided_decoding_logits_processor)
GuidedDecodingRequest,
get_local_guided_decoding_logits_processor,
)
from vllm.model_executor.guided_decoding.guided_fields import LLMGuidedOptions
from vllm.outputs import EmbeddingRequestOutput, RequestOutput
from vllm.pooling_params import PoolingParams
from vllm.prompt_adapter.request import PromptAdapterRequest
from vllm.sampling_params import SamplingParams
from vllm.transformers_utils.tokenizer import (AnyTokenizer,
get_cached_tokenizer)
from vllm.transformers_utils.tokenizer import (
AnyTokenizer,
get_cached_tokenizer,
MistralTokenizer,
)
from vllm.transformers_utils.tokenizer_group import TokenizerGroup
from vllm.usage.usage_lib import UsageContext
from vllm.utils import Counter, deprecate_kwargs
Expand Down Expand Up @@ -131,14 +138,14 @@ def __init__(
disable_custom_all_reduce: bool = False,
**kwargs,
) -> None:
'''
"""
LLM constructor.

Note: if enforce_eager is unset (enforce_eager is None)
it defaults to False for decoder-only models and True
for encoder/decoder models, since encoder/decoder models
do not currently support CUDAGraph.
'''
"""

if "disable_log_stats" not in kwargs:
kwargs["disable_log_stats"] = True
Expand Down Expand Up @@ -273,15 +280,15 @@ def generate(
def generate(
self,
prompts: Union[Union[PromptInputs, Sequence[PromptInputs]],
Optional[Union[str, List[str]]]] = None,
Optional[Union[str, List[str]]], ] = None,
sampling_params: Optional[Union[SamplingParams,
Sequence[SamplingParams]]] = None,
prompt_token_ids: Optional[Union[List[int], List[List[int]]]] = None,
use_tqdm: bool = True,
lora_request: Optional[Union[List[LoRARequest], LoRARequest]] = None,
prompt_adapter_request: Optional[PromptAdapterRequest] = None,
guided_options_request: Optional[Union[LLMGuidedOptions,
GuidedDecodingRequest]] = None
GuidedDecodingRequest]] = None,
) -> List[RequestOutput]:
"""Generates the completions for the input prompts.

Expand Down Expand Up @@ -340,7 +347,8 @@ def generate(
params=sampling_params,
lora_request=lora_request,
prompt_adapter_request=prompt_adapter_request,
guided_options=guided_options_request)
guided_options=guided_options_request,
)

outputs = self._run_engine(use_tqdm=use_tqdm)
return LLMEngine.validate_outputs(outputs, RequestOutput)
Expand Down Expand Up @@ -374,7 +382,7 @@ def chat(
lora_request: LoRA request to use for generation, if any.
chat_template: The template to use for structuring the chat.
If not provided, the model's default chat template will be used.
add_generation_template: If True, adds a generation template
add_generation_template: If True, adds a generation template
patrickvonplaten marked this conversation as resolved.
Show resolved Hide resolved
to each message.

Returns:
Expand All @@ -383,20 +391,29 @@ def chat(
"""

tokenizer = self.get_tokenizer()
model_config = self.llm_engine.get_model_config()

conversations, _ = parse_chat_messages(messages, model_config,
tokenizer)
if isinstance(tokenizer, MistralTokenizer):
prompt_token_ids = tokenizer.encode_messages(messages)
prompts = None
else:
model_config = self.llm_engine.get_model_config()

conversations, _ = parse_chat_messages(messages, model_config,
tokenizer)

prompts = apply_chat_template(
tokenizer,
conversations,
chat_template=chat_template,
add_generation_template=add_generation_template)
prompts = apply_chat_template(
tokenizer,
conversations,
chat_template=chat_template,
add_generation_template=add_generation_template,
)

prompt_token_ids = None

return self.generate(
prompts,
prompts, # type: ignore[arg-type]
sampling_params,
prompt_token_ids=prompt_token_ids,
use_tqdm=use_tqdm,
lora_request=lora_request,
)
Expand Down Expand Up @@ -484,7 +501,7 @@ def encode(
def encode(
self,
prompts: Union[Union[PromptInputs, Sequence[PromptInputs]],
Optional[Union[str, List[str]]]] = None,
Optional[Union[str, List[str]]], ] = None,
pooling_params: Optional[Union[PoolingParams,
Sequence[PoolingParams]]] = None,
prompt_token_ids: Optional[Union[List[int], List[List[int]]]] = None,
Expand Down Expand Up @@ -564,8 +581,8 @@ def _convert_v1_inputs(
if prompts is not None:
num_requests = len(prompts)
if prompt_token_ids is not None:
if (num_requests is not None
and num_requests != len(prompt_token_ids)):
if num_requests is not None and num_requests != len(
prompt_token_ids):
raise ValueError("The lengths of prompts and prompt_token_ids "
"must be the same.")

Expand Down Expand Up @@ -593,7 +610,7 @@ def _validate_and_add_requests(
self,
inputs: Union[PromptInputs, Sequence[PromptInputs]],
params: Union[SamplingParams, Sequence[SamplingParams], PoolingParams,
Sequence[PoolingParams]],
Sequence[PoolingParams], ],
lora_request: Optional[Union[Sequence[LoRARequest], LoRARequest]],
prompt_adapter_request: Optional[PromptAdapterRequest],
guided_options: Optional[GuidedDecodingRequest] = None,
Expand Down Expand Up @@ -648,17 +665,21 @@ def _add_request(
)

def _add_guided_processor(
self,
params: SamplingParams,
guided_options: Optional[GuidedDecodingRequest] = None):
self,
params: SamplingParams,
guided_options: Optional[GuidedDecodingRequest] = None,
):
if guided_options:
if guided_options.guided_decoding_backend is None:
decoding_config = self.llm_engine.get_decoding_config()
guided_options.guided_decoding_backend = (
decoding_config.guided_decoding_backend)
guided_logits_processor = get_local_guided_decoding_logits_processor( #noqa
guided_options.guided_decoding_backend, guided_options,
self.get_tokenizer())
guided_logits_processor = (
get_local_guided_decoding_logits_processor( # noqa
guided_options.guided_decoding_backend,
guided_options,
self.get_tokenizer(),
))
patrickvonplaten marked this conversation as resolved.
Show resolved Hide resolved
if guided_logits_processor:
if params.logits_processors is None:
params.logits_processors = []
Expand Down
Loading
Loading