[Mistral Grammar] Support Grammar Factory (#38150)
Signed-off-by: juliendenize <julien.denize@mistral.ai>
This commit is contained in:
+17
-11
@@ -153,6 +153,10 @@ class RequestOutputKind(Enum):
|
||||
FINAL_ONLY = 2
|
||||
|
||||
|
||||
def _is_non_tekken_mistral(tokenizer: TokenizerLike) -> bool:
|
||||
return is_mistral_tokenizer(tokenizer) and not tokenizer.is_tekken
|
||||
|
||||
|
||||
class SamplingParams(
|
||||
PydanticMsgspecMixin,
|
||||
msgspec.Struct,
|
||||
@@ -801,16 +805,17 @@ class SamplingParams(
|
||||
# xgrammar with no fallback
|
||||
validate_xgrammar_grammar(self)
|
||||
elif backend.startswith("guidance"):
|
||||
if _is_non_tekken_mistral(tokenizer=tokenizer):
|
||||
raise ValueError(
|
||||
"Non-tekken Mistral tokenizers are not supported for the 'guidance'"
|
||||
" structured output backend. Please either use a more recent "
|
||||
"Mistral model, the ['xgrammar', 'outlines'] "
|
||||
"backends or tokenizer_mode='hf' instead."
|
||||
)
|
||||
# TODO: ideally we would have the LLTokenizer here as Lark syntax
|
||||
# allows <|special_token|> and similar, see
|
||||
# https://github.com/guidance-ai/llguidance/blob/main/docs/syntax.md#special-tokens
|
||||
# Without tokenizer these are disallowed in grammars.
|
||||
if is_mistral_tokenizer(tokenizer):
|
||||
raise ValueError(
|
||||
"Mistral tokenizer is not supported for the 'guidance' "
|
||||
"structured output backend. Please use ['xgrammar', 'outlines'] "
|
||||
"backends or tokenizer_mode='hf' instead."
|
||||
)
|
||||
validate_guidance_grammar(self, tokenizer=None)
|
||||
elif backend == "outlines":
|
||||
# outlines backend
|
||||
@@ -839,19 +844,20 @@ class SamplingParams(
|
||||
# or includes some jsonschema feature(s) that
|
||||
# are not supported in xgrammar.
|
||||
|
||||
skip_guidance = _is_non_tekken_mistral(tokenizer)
|
||||
|
||||
# Check if schema has features unsupported by guidance
|
||||
so_params = self.structured_outputs
|
||||
skip_guidance = False
|
||||
if so_params.json:
|
||||
if not skip_guidance and so_params.json:
|
||||
if isinstance(so_params.json, str):
|
||||
schema = json_mod.loads(so_params.json)
|
||||
else:
|
||||
schema = so_params.json
|
||||
skip_guidance = has_guidance_unsupported_json_features(schema)
|
||||
|
||||
if is_mistral_tokenizer(tokenizer) or skip_guidance:
|
||||
# Fall back to outlines if the tokenizer is Mistral
|
||||
# or if schema contains features unsupported by guidance
|
||||
if skip_guidance:
|
||||
# Fall back to outlines if the tokenizer is non-tekken Mistral or
|
||||
# the schema contains features unsupported by guidance
|
||||
validate_structured_output_request_outlines(self)
|
||||
self.structured_outputs._backend = "outlines"
|
||||
else:
|
||||
|
||||
@@ -1,9 +1,12 @@
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
||||
from collections.abc import Sequence
|
||||
from functools import cached_property
|
||||
from pathlib import Path
|
||||
from typing import TYPE_CHECKING, Any, cast, overload
|
||||
|
||||
from mistral_common.guidance.grammar_factory import GrammarFactory
|
||||
from mistral_common.guidance.tokenizer import from_mistral_tokenizer
|
||||
from mistral_common.protocol.instruct.request import (
|
||||
ChatCompletionRequest as MistralChatCompletionRequest,
|
||||
)
|
||||
@@ -45,6 +48,7 @@ except ImportError:
|
||||
)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
import llguidance
|
||||
from transformers import BatchEncoding
|
||||
|
||||
logger = init_logger(__name__)
|
||||
@@ -574,3 +578,24 @@ class MistralTokenizer(TokenizerLike):
|
||||
]
|
||||
|
||||
return tokens
|
||||
|
||||
@property
|
||||
def supports_grammar(self) -> bool:
|
||||
return GrammarFactory.is_supported(self.mistral)
|
||||
|
||||
@cached_property
|
||||
def grammar_factory(self) -> GrammarFactory:
|
||||
if not self.supports_grammar:
|
||||
raise AttributeError(
|
||||
"This tokenizer does not support `grammar_factory`. "
|
||||
"This is only supported for tekken tokenizers with "
|
||||
"version >= 11."
|
||||
)
|
||||
# Cache grammar factory to avoid creating a llguidance tokenizer at every usage.
|
||||
return GrammarFactory(self.mistral)
|
||||
|
||||
@cached_property
|
||||
def llg_tokenizer(self) -> "llguidance.LLTokenizer":
|
||||
if not self.is_tekken:
|
||||
raise ValueError("`llg_tokenizer` is only supported for Tekkenizers.")
|
||||
return from_mistral_tokenizer(self.mistral)
|
||||
|
||||
@@ -10,6 +10,18 @@ from typing import Any
|
||||
|
||||
import ijson
|
||||
import regex as re
|
||||
from mistral_common.protocol.instruct.tool_calls import (
|
||||
NamedToolChoice as MistralNamedToolChoice,
|
||||
)
|
||||
from mistral_common.protocol.instruct.tool_calls import (
|
||||
Tool as MistralTool,
|
||||
)
|
||||
from mistral_common.protocol.instruct.tool_calls import (
|
||||
ToolChoice as MistralToolChoice,
|
||||
)
|
||||
from mistral_common.protocol.instruct.tool_calls import (
|
||||
ToolChoiceEnum as MistralToolChoiceEnum,
|
||||
)
|
||||
from pydantic import Field
|
||||
|
||||
from vllm.entrypoints.openai.chat_completion.protocol import (
|
||||
@@ -25,6 +37,7 @@ from vllm.entrypoints.openai.engine.protocol import (
|
||||
)
|
||||
from vllm.entrypoints.openai.responses.protocol import ResponsesRequest
|
||||
from vllm.logger import init_logger
|
||||
from vllm.sampling_params import StructuredOutputsParams
|
||||
from vllm.tokenizers import TokenizerLike
|
||||
from vllm.tool_parsers.abstract_tool_parser import (
|
||||
Tool,
|
||||
@@ -36,6 +49,8 @@ logger = init_logger(__name__)
|
||||
|
||||
ALPHANUMERIC = ascii_letters + digits
|
||||
|
||||
_DEFAULT_JSON_SCHEMA = {"anyOf": [{"type": "object"}, {"type": "array"}]}
|
||||
|
||||
|
||||
class StreamingState(Enum):
|
||||
"""Enum for tracking the current streaming parsing state."""
|
||||
@@ -80,6 +95,9 @@ class MistralToolParser(ToolParser):
|
||||
Used when --enable-auto-tool-choice --tool-call-parser mistral are all set
|
||||
"""
|
||||
|
||||
# Used to generate correct grammar in `adjust_request`
|
||||
model_can_reason: bool = False
|
||||
|
||||
def __init__(self, tokenizer: TokenizerLike, tools: list[Tool] | None = None):
|
||||
super().__init__(tokenizer, tools)
|
||||
|
||||
@@ -115,18 +133,124 @@ class MistralToolParser(ToolParser):
|
||||
def adjust_request(
|
||||
self, request: ChatCompletionRequest | ResponsesRequest
|
||||
) -> ChatCompletionRequest | ResponsesRequest:
|
||||
request = super().adjust_request(request)
|
||||
so_non_supported_attributes = [
|
||||
"regex",
|
||||
"choice",
|
||||
"grammar",
|
||||
# whitespace_pattern is not a constraint type but an option;
|
||||
# Mistral grammar factory does not support it.
|
||||
"whitespace_pattern",
|
||||
"structural_tag",
|
||||
]
|
||||
any_so_non_supported_active = request.structured_outputs is not None and any(
|
||||
getattr(request.structured_outputs, attribute) is not None
|
||||
for attribute in so_non_supported_attributes
|
||||
)
|
||||
response_format_non_supported_active = (
|
||||
isinstance(request, ResponsesRequest)
|
||||
or request.response_format is not None
|
||||
and request.response_format.type == "structural_tag"
|
||||
)
|
||||
|
||||
if (
|
||||
not is_mistral_tokenizer(self.model_tokenizer)
|
||||
and request.tools
|
||||
and request.tool_choice != "none"
|
||||
or isinstance(request, ResponsesRequest)
|
||||
or not self.model_tokenizer.supports_grammar
|
||||
or any_so_non_supported_active
|
||||
or response_format_non_supported_active
|
||||
):
|
||||
# Do not skip special tokens when using chat template
|
||||
# with Mistral parser as TOOL_CALL token is needed
|
||||
# for tool detection.
|
||||
# Note: we don't want skip_special_tokens=False
|
||||
# with MistralTokenizer as it is incompatible
|
||||
request.skip_special_tokens = False
|
||||
request = super().adjust_request(request)
|
||||
if request.tools and request.tool_choice != "none":
|
||||
# Do not skip special tokens when using chat template
|
||||
# with Mistral parser as TOOL_CALL token is needed
|
||||
# for tool detection.
|
||||
# Note: we don't want skip_special_tokens=False
|
||||
# with MistralTokenizer as it is incompatible
|
||||
request.skip_special_tokens = False
|
||||
return request
|
||||
|
||||
json_schema: dict[str, Any] | None = None
|
||||
if request.structured_outputs is not None:
|
||||
if request.structured_outputs.json_object is not None:
|
||||
json_schema = _DEFAULT_JSON_SCHEMA
|
||||
elif request.structured_outputs.json is not None:
|
||||
if isinstance(request.structured_outputs.json, str):
|
||||
json_schema = json.loads(request.structured_outputs.json)
|
||||
else:
|
||||
json_schema = request.structured_outputs.json
|
||||
else:
|
||||
raise ValueError(
|
||||
"Unsupported request.structured_outputs for MistralToolParser. "
|
||||
"Only `json` and `json_object` are supported."
|
||||
)
|
||||
elif (
|
||||
request.response_format is not None
|
||||
and request.response_format.type != "text"
|
||||
):
|
||||
if request.response_format.type == "json_object":
|
||||
json_schema = _DEFAULT_JSON_SCHEMA
|
||||
elif request.response_format.type == "json_schema":
|
||||
if request.response_format.json_schema is not None:
|
||||
json_schema = request.response_format.json_schema.json_schema
|
||||
else:
|
||||
json_schema = _DEFAULT_JSON_SCHEMA
|
||||
else:
|
||||
raise ValueError(
|
||||
"MistralToolParser only accepts `text`, `json_object` or "
|
||||
f"`json_schema`, got {request.response_format=}"
|
||||
)
|
||||
# Structured Outputs will be defined.
|
||||
request.response_format = None
|
||||
|
||||
grammar_factory = self.model_tokenizer.grammar_factory
|
||||
|
||||
# TODO: Once unified parser, improve this.
|
||||
# The issue is figuring out when a model is a reasoning one or not.
|
||||
template = grammar_factory.select_jinja_template(
|
||||
reasoning=self.model_can_reason
|
||||
)
|
||||
|
||||
tools = (
|
||||
[
|
||||
MistralTool.from_openai(openai_tool=tool.model_dump())
|
||||
for tool in request.tools
|
||||
]
|
||||
if request.tools is not None
|
||||
else None
|
||||
)
|
||||
|
||||
tool_choice: MistralToolChoice
|
||||
match request.tool_choice:
|
||||
case "none" | "auto" | "required":
|
||||
tool_choice = MistralToolChoiceEnum(request.tool_choice)
|
||||
case None:
|
||||
tool_choice = MistralToolChoiceEnum.auto
|
||||
# _ == Named tool choice
|
||||
case _:
|
||||
tool_choice = MistralNamedToolChoice.model_validate(
|
||||
{
|
||||
"type": "function",
|
||||
"function": {"name": request.tool_choice.function.name},
|
||||
}
|
||||
)
|
||||
|
||||
# Rendering grammar is cached in mistral-common given tools, template and mode.
|
||||
match tool_choice, json_schema is not None:
|
||||
case MistralToolChoiceEnum.none, True:
|
||||
lark_grammar = grammar_factory.get_lark_for_json_schema(
|
||||
template=template, json_schema=json_schema
|
||||
)
|
||||
case _, _:
|
||||
lark_grammar = grammar_factory.get_lark_from_jinja(
|
||||
template=template,
|
||||
mode=tool_choice,
|
||||
tools=tools,
|
||||
json_schema=json_schema,
|
||||
parallel_tool_calls=request.parallel_tool_calls,
|
||||
json_only=False,
|
||||
)
|
||||
|
||||
request.structured_outputs = StructuredOutputsParams(grammar=lark_grammar)
|
||||
return request
|
||||
|
||||
def extract_tool_calls(
|
||||
|
||||
@@ -12,6 +12,7 @@ import torch
|
||||
from vllm.logger import init_logger
|
||||
from vllm.sampling_params import SamplingParams
|
||||
from vllm.utils.import_utils import LazyLoader
|
||||
from vllm.utils.mistral import is_mistral_tokenizer
|
||||
from vllm.v1.structured_output.backend_types import (
|
||||
StructuredOutputBackend,
|
||||
StructuredOutputGrammar,
|
||||
@@ -92,9 +93,12 @@ class GuidanceBackend(StructuredOutputBackend):
|
||||
self.vllm_config.structured_outputs_config.disable_additional_properties
|
||||
)
|
||||
|
||||
self.ll_tokenizer = llguidance_hf.from_tokenizer(
|
||||
self.tokenizer, max(self.vocab_size, len(self.tokenizer))
|
||||
)
|
||||
if is_mistral_tokenizer(self.tokenizer):
|
||||
self.ll_tokenizer = self.tokenizer.llg_tokenizer
|
||||
else:
|
||||
self.ll_tokenizer = llguidance_hf.from_tokenizer(
|
||||
self.tokenizer, max(self.vocab_size, len(self.tokenizer))
|
||||
)
|
||||
|
||||
def compile_grammar(
|
||||
self, request_type: StructuredOutputOptions, grammar_spec: str
|
||||
|
||||
Reference in New Issue
Block a user