|
| 1 | +# SPDX-License-Identifier: Apache-2.0 |
| 2 | +import json |
| 3 | +import os |
| 4 | +from typing import Any, List, Type, Union |
| 5 | + |
| 6 | +import llguidance # type: ignore[import-untyped] |
| 7 | +import llguidance.hf |
| 8 | +import numpy as np |
| 9 | +import torch |
| 10 | +from pydantic import BaseModel |
| 11 | +from transformers import PreTrainedTokenizerBase |
| 12 | + |
| 13 | +from vllm.model_executor.guided_decoding.guidance_utils import ( |
| 14 | + LLInterpreterResponse) |
| 15 | + |
| 16 | + |
| 17 | +class GuidanceLogitsProcessor: |
| 18 | + """Base Guidance Logits Processor""" |
| 19 | + |
| 20 | + cached_tokenizers: dict[str, Any] = {} |
| 21 | + |
| 22 | + def __init__( |
| 23 | + self, |
| 24 | + mode: str, |
| 25 | + guide: Union[dict, Type[BaseModel], str], |
| 26 | + tokenizer: PreTrainedTokenizerBase, |
| 27 | + whitespace_pattern: Union[str, None] = None, |
| 28 | + ) -> None: |
| 29 | + """Base Guidance Logits Processor |
| 30 | +
|
| 31 | + Args: |
| 32 | + mode (str) |
| 33 | + guided generation mode. |
| 34 | + Must be one of "json", "regex", "choice", "grammar" |
| 35 | + guide (Union[dict, Type[BaseModel], str]) |
| 36 | + guide for guided generation |
| 37 | + tokenizer (PreTrainedTokenizerBase) |
| 38 | + model's tokenizer |
| 39 | + whitespace_pattern (Union[str, None], optional) |
| 40 | + Json-string to indicate pattern to use \ |
| 41 | + for JSON syntactic whitespace |
| 42 | + Example: '{"whitespace_flexible":true}' |
| 43 | + """ |
| 44 | + self.mode = mode |
| 45 | + self.guide = guide |
| 46 | + self.tokenizer = tokenizer |
| 47 | + self.tokenizer_name = tokenizer.name_or_path |
| 48 | + self.whitespace_pattern = whitespace_pattern |
| 49 | + |
| 50 | + self.is_stopped = False |
| 51 | + self.pending_ff_tokens: list[int] = [] |
| 52 | + self.new_sampling = False |
| 53 | + self.initialized = False |
| 54 | + |
| 55 | + def _initialize(self): |
| 56 | + if self.initialized: |
| 57 | + return |
| 58 | + |
| 59 | + if self.mode.lower() == "json": |
| 60 | + if isinstance(self.guide, dict): |
| 61 | + schema = json.dumps(self.guide) |
| 62 | + elif isinstance(self.guide, BaseModel): |
| 63 | + schema = json.dumps(self.guide.model_json_schema()) |
| 64 | + else: |
| 65 | + schema = str(self.guide) |
| 66 | + |
| 67 | + whitespaces_config = {} |
| 68 | + if isinstance(self.whitespace_pattern, str): |
| 69 | + whitespaces_config = json.loads(self.whitespace_pattern) |
| 70 | + |
| 71 | + whitespace_flexible = whitespaces_config.get( |
| 72 | + "whitespace_flexible", False) |
| 73 | + compiler = llguidance.JsonCompiler( |
| 74 | + whitespace_flexible=whitespace_flexible) |
| 75 | + self.serialized_grammar = compiler.compile(schema) |
| 76 | + elif self.mode.lower() in ["regex", "choice"]: |
| 77 | + compiler = llguidance.RegexCompiler() |
| 78 | + self.serialized_grammar = compiler.compile(regex=self.guide) |
| 79 | + elif self.mode.lower() == "grammar": |
| 80 | + serialized_grammar = self.guide |
| 81 | + if isinstance(self.guide, dict): |
| 82 | + serialized_grammar = json.dumps(self.guide) |
| 83 | + self.serialized_grammar = serialized_grammar |
| 84 | + |
| 85 | + ll_tokenizer = self.cached_tokenizers.get(self.tokenizer.name_or_path, |
| 86 | + None) |
| 87 | + if ll_tokenizer is None: |
| 88 | + ll_tokenizer = llguidance.hf.from_tokenizer(self.tokenizer, None) |
| 89 | + self.cached_tokenizers[self.tokenizer.name_or_path] = ll_tokenizer |
| 90 | + self.ll_tokenizer = ll_tokenizer |
| 91 | + self.ll_interpreter = llguidance.LLInterpreter( |
| 92 | + self.ll_tokenizer, |
| 93 | + self.serialized_grammar, |
| 94 | + enable_backtrack=False, |
| 95 | + enable_ff_tokens=False, |
| 96 | + log_level=int(os.environ.get("LLGUIDANCE_LOG_LEVEL", "1")), |
| 97 | + ) |
| 98 | + |
| 99 | + self.initialized = True |
| 100 | + |
| 101 | + def __call__( |
| 102 | + self, |
| 103 | + input_ids: List[int], |
| 104 | + scores: torch.Tensor, |
| 105 | + ) -> torch.Tensor: |
| 106 | + # we initialize the guidance model here |
| 107 | + # to avoid pickling ll_tokenizer and ll_interpreter |
| 108 | + self._initialize() |
| 109 | + |
| 110 | + if self.is_stopped: |
| 111 | + return scores |
| 112 | + |
| 113 | + if self.new_sampling and len(input_ids) > 0: |
| 114 | + backtrack, ff_tokens = self.ll_interpreter.commit_token( |
| 115 | + input_ids[-1]) |
| 116 | + if len(ff_tokens) > 0 and backtrack == 0: |
| 117 | + # first token is last generated token |
| 118 | + ff_tokens = ff_tokens[1:] |
| 119 | + self.pending_ff_tokens.extend(ff_tokens) |
| 120 | + self.new_sampling = False |
| 121 | + |
| 122 | + if len(self.pending_ff_tokens) > 0: |
| 123 | + # if we have pending fast-forward tokens, |
| 124 | + # just return them immediately |
| 125 | + ff_token = self.pending_ff_tokens.pop(0) |
| 126 | + scores.add_(-scores) |
| 127 | + scores[ff_token] = 200.0 |
| 128 | + return scores |
| 129 | + |
| 130 | + mask, resp = self.ll_interpreter.compute_mask() |
| 131 | + r = LLInterpreterResponse.model_validate_json(resp) |
| 132 | + |
| 133 | + if r.stop: |
| 134 | + mask = np.zeros(scores.shape[-1], dtype=np.uint8) |
| 135 | + if self.ll_tokenizer.eos_token is not None: |
| 136 | + mask[self.ll_tokenizer.eos_token] = 200 |
| 137 | + self.is_stopped = True |
| 138 | + elif mask is None: |
| 139 | + # NOTE: mask should not be None unless r.stop is True |
| 140 | + # However, we are handling this case just in case |
| 141 | + # llguidance allows free-style generation |
| 142 | + mask = np.zeros(scores.shape[-1], dtype=np.uint8) |
| 143 | + else: |
| 144 | + mask = np.frombuffer(mask, dtype=np.uint8) |
| 145 | + |
| 146 | + # Force all invalid tokens to have 0 value |
| 147 | + scores.add_(-torch.min(scores)) |
| 148 | + zero_indices = np.where(mask == 0)[0] |
| 149 | + scores[zero_indices] = 0.0 |
| 150 | + non_zero_indices = np.nonzero(mask)[0] |
| 151 | + scores[non_zero_indices] += 200.0 |
| 152 | + # set special tokens not in vocab to 0 |
| 153 | + scores[mask.shape[0]:] = 0.0 |
| 154 | + self.new_sampling = True |
| 155 | + |
| 156 | + return scores |
0 commit comments