|
| 1 | +# SPDX-License-Identifier: Apache-2.0 |
| 2 | + |
| 3 | +import json |
| 4 | +import os |
| 5 | +from dataclasses import dataclass |
| 6 | +from typing import TYPE_CHECKING |
| 7 | + |
| 8 | +import torch |
| 9 | + |
| 10 | +from vllm.config import VllmConfig |
| 11 | +from vllm.logger import init_logger |
| 12 | +from vllm.transformers_utils.tokenizer_group import init_tokenizer_from_configs |
| 13 | +from vllm.utils import LazyLoader |
| 14 | +from vllm.v1.structured_output.backend_types import (StructuredOutputBackend, |
| 15 | + StructuredOutputGrammar, |
| 16 | + StructuredOutputOptions) |
| 17 | + |
| 18 | +if TYPE_CHECKING: |
| 19 | + import llguidance |
| 20 | + import llguidance.hf as llguidance_hf |
| 21 | + import llguidance.torch as llguidance_torch |
| 22 | +else: |
| 23 | + llguidance = LazyLoader("llguidance", globals(), "llguidance") |
| 24 | + llguidance_hf = LazyLoader("llguidance.hf", globals(), "llguidance.hf") |
| 25 | + llguidance_torch = LazyLoader("llguidance.torch", globals(), |
| 26 | + "llguidance.torch") |
| 27 | + |
| 28 | +logger = init_logger(__name__) |
| 29 | + |
| 30 | + |
| 31 | +class GuidanceBackend(StructuredOutputBackend): |
| 32 | + |
| 33 | + def __init__(self, vllm_config: VllmConfig): |
| 34 | + self.vllm_config = vllm_config |
| 35 | + tokenizer_group = init_tokenizer_from_configs( |
| 36 | + model_config=vllm_config.model_config, |
| 37 | + scheduler_config=vllm_config.scheduler_config, |
| 38 | + parallel_config=vllm_config.parallel_config, |
| 39 | + lora_config=vllm_config.lora_config) # type: ignore[arg-type] |
| 40 | + tokenizer_group.ping() |
| 41 | + self.vllm_config = vllm_config |
| 42 | + self.vocab_size = vllm_config.model_config.get_vocab_size() |
| 43 | + |
| 44 | + tokenizer = tokenizer_group.get_lora_tokenizer(None) |
| 45 | + self.ll_tokenizer = llguidance_hf.from_tokenizer(tokenizer, None) |
| 46 | + |
| 47 | + def compile_grammar(self, request_type: StructuredOutputOptions, |
| 48 | + grammar_spec: str) -> StructuredOutputGrammar: |
| 49 | + |
| 50 | + if request_type == StructuredOutputOptions.JSON: |
| 51 | + if isinstance(grammar_spec, dict): |
| 52 | + schema = json.dumps(grammar_spec) |
| 53 | + else: |
| 54 | + schema = str(grammar_spec) |
| 55 | + |
| 56 | + # TODO: make whitespace_flexible configurable |
| 57 | + compiler = llguidance.JsonCompiler(whitespace_flexible=False) |
| 58 | + self.serialized_grammar = compiler.compile(schema) |
| 59 | + elif request_type == StructuredOutputOptions.JSON_OBJECT: |
| 60 | + compiler = llguidance.JsonCompiler(whitespace_flexible=False) |
| 61 | + self.serialized_grammar = compiler.compile('{"type": "object"}') |
| 62 | + elif (request_type == StructuredOutputOptions.REGEX |
| 63 | + or request_type == StructuredOutputOptions.CHOICE): |
| 64 | + compiler = llguidance.RegexCompiler() |
| 65 | + self.serialized_grammar = compiler.compile(regex=grammar_spec) |
| 66 | + elif request_type == StructuredOutputOptions.GRAMMAR: |
| 67 | + if isinstance(grammar_spec, dict): |
| 68 | + self.serialized_grammar = json.dumps(grammar_spec) |
| 69 | + else: |
| 70 | + self.serialized_grammar = str(grammar_spec) |
| 71 | + else: |
| 72 | + logger.error( |
| 73 | + "Validation should have already occurred. Please file an issue." |
| 74 | + ) |
| 75 | + raise ValueError( |
| 76 | + f"grammar is not of valid supported types. ({request_type!s})") |
| 77 | + |
| 78 | + ll_interpreter = llguidance.LLInterpreter( |
| 79 | + self.ll_tokenizer, |
| 80 | + self.serialized_grammar, |
| 81 | + enable_backtrack=False, |
| 82 | + enable_ff_tokens=False, |
| 83 | + log_level=int(os.environ.get("LLGUIDANCE_LOG_LEVEL", "1")), |
| 84 | + ) |
| 85 | + |
| 86 | + return GuidanceGrammar( |
| 87 | + ll_interpreter=ll_interpreter, |
| 88 | + ll_tokenizer=self.ll_tokenizer, |
| 89 | + vocab_size=self.vocab_size, |
| 90 | + ) |
| 91 | + |
| 92 | + def allocate_token_bitmask(self, max_num_seqs: int): |
| 93 | + return llguidance_torch.allocate_token_bitmask( |
| 94 | + max_num_seqs, self.ll_tokenizer.vocab_size) |
| 95 | + |
| 96 | + |
| 97 | +@dataclass |
| 98 | +class GuidanceGrammar(StructuredOutputGrammar): |
| 99 | + |
| 100 | + ll_interpreter: llguidance.LLInterpreter |
| 101 | + ll_tokenizer: llguidance_hf.LLTokenizer |
| 102 | + vocab_size: int |
| 103 | + stopped: bool = False |
| 104 | + |
| 105 | + def accept_tokens(self, request_id: str, tokens: list[int]) -> bool: |
| 106 | + """Accepts a list of tokens and advances the FSM. |
| 107 | +
|
| 108 | + Returns True if the FSM was advanced successfully. |
| 109 | + Returns False if the FSM failed to advance. |
| 110 | + """ |
| 111 | + |
| 112 | + if self.stopped: |
| 113 | + return True |
| 114 | + |
| 115 | + for token in tokens: |
| 116 | + # TODO - Add jump decoding support in the future. |
| 117 | + # For now we turn this off when creating the LLInterpreter. |
| 118 | + #backtrack, ff_tokens = self.ll_interpreter.commit_token(token) |
| 119 | + self.ll_interpreter.commit_token(token) |
| 120 | + |
| 121 | + return True |
| 122 | + |
| 123 | + def fill_bitmask(self, bitmask: torch.Tensor, idx: int) -> None: |
| 124 | + if self.ll_interpreter.has_pending_stop(): |
| 125 | + # fill bitmask with eos token before is_terminated() return True |
| 126 | + eos_token = self.ll_tokenizer.eos_token |
| 127 | + bitmask[idx, :] = 0 |
| 128 | + bitmask[idx, eos_token // 32] = 1 << (eos_token % 32) |
| 129 | + self.stopped = True |
| 130 | + else: |
| 131 | + llguidance_torch.fill_next_token_bitmask(self.ll_interpreter, |
| 132 | + bitmask, idx) |
| 133 | + |
| 134 | + def is_terminated(self) -> bool: |
| 135 | + return self.stopped |
| 136 | + |
| 137 | + def reset(self): |
| 138 | + # This method may be not needed anymore? TODO |
| 139 | + pass |
0 commit comments