|
| 1 | +"""Base classes for grammar-constrained decoding backends.""" |
| 2 | + |
| 3 | +import concurrent.futures as futures |
| 4 | +import logging |
| 5 | +from concurrent.futures import ThreadPoolExecutor |
| 6 | +from typing import Any |
| 7 | + |
| 8 | +import numpy as np |
| 9 | + |
| 10 | +from sgl_jax.srt.server_args import ServerArgs |
| 11 | + |
| 12 | +logger = logging.getLogger(__name__) |
| 13 | + |
| 14 | + |
| 15 | +class BaseGrammarObject: |
| 16 | + """Base class for grammar objects that maintain state during generation.""" |
| 17 | + |
| 18 | + def __init__(self): |
| 19 | + self.finished = False |
| 20 | + |
| 21 | + def accept_token(self, token: int): |
| 22 | + raise NotImplementedError() |
| 23 | + |
| 24 | + def allocate_vocab_mask(self, vocab_size: int, batch_size: int): |
| 25 | + raise NotImplementedError() |
| 26 | + |
| 27 | + def fill_vocab_mask(self, vocab_mask: np.ndarray, idx: int): |
| 28 | + raise NotImplementedError() |
| 29 | + |
| 30 | + def is_terminated(self) -> bool: |
| 31 | + raise NotImplementedError() |
| 32 | + |
| 33 | + def copy(self): |
| 34 | + raise NotImplementedError() |
| 35 | + |
| 36 | + |
| 37 | +class BaseGrammarBackend: |
| 38 | + """Base class for grammar backends with async compilation support.""" |
| 39 | + |
| 40 | + def __init__(self, num_threads: int = 4): |
| 41 | + """Initialize the grammar backend. |
| 42 | +
|
| 43 | + Args: |
| 44 | + num_threads: Number of threads for async grammar compilation. |
| 45 | + """ |
| 46 | + self.executor = ThreadPoolExecutor(max_workers=num_threads) |
| 47 | + self.cache: dict[tuple[str, str], Any] = {} |
| 48 | + |
| 49 | + def get_cached_or_future_value(self, key: tuple[str, str]) -> tuple[Any, bool]: |
| 50 | + """Get a cached grammar object or submit async compilation. |
| 51 | +
|
| 52 | + Args: |
| 53 | + key: Tuple of (constraint_type, constraint_string) |
| 54 | + e.g., ("json", schema_str) or ("regex", pattern) |
| 55 | +
|
| 56 | + Returns: |
| 57 | + Tuple of (grammar_object or Future, cache_hit: bool) |
| 58 | + """ |
| 59 | + if key in self.cache: |
| 60 | + value = self.cache[key] |
| 61 | + # Check if it's a completed grammar or still a Future |
| 62 | + if isinstance(value, futures.Future): |
| 63 | + return value, False # Still compiling |
| 64 | + else: |
| 65 | + return value, True # Cache hit |
| 66 | + |
| 67 | + # Not in cache, submit async compilation |
| 68 | + key_type, key_string = key |
| 69 | + future = self.executor.submit(self._dispatch, key_type, key_string) |
| 70 | + self.cache[key] = future |
| 71 | + return future, False |
| 72 | + |
| 73 | + def set_cache(self, key: tuple[str, str], value: BaseGrammarObject): |
| 74 | + """Store a compiled grammar in the cache. |
| 75 | +
|
| 76 | + Args: |
| 77 | + key: Cache key |
| 78 | + value: Compiled grammar object |
| 79 | + """ |
| 80 | + self.cache[key] = value |
| 81 | + |
| 82 | + def _dispatch(self, key_type: str, key_string: str) -> BaseGrammarObject: |
| 83 | + """Dispatch grammar creation based on type. |
| 84 | +
|
| 85 | + Args: |
| 86 | + key_type: Type of constraint ("json", "regex", "ebnf", "structural_tag") |
| 87 | + key_string: Constraint string (JSON schema, regex pattern, etc.) |
| 88 | +
|
| 89 | + Returns: |
| 90 | + Compiled grammar object |
| 91 | + """ |
| 92 | + if key_type == "json": |
| 93 | + return self.dispatch_json(key_string) |
| 94 | + elif key_type == "regex": |
| 95 | + return self.dispatch_regex(key_string) |
| 96 | + elif key_type == "ebnf": |
| 97 | + return self.dispatch_ebnf(key_string) |
| 98 | + elif key_type == "structural_tag": |
| 99 | + return self.dispatch_structural_tag(key_string) |
| 100 | + else: |
| 101 | + raise ValueError(f"Unknown constraint type: {key_type}") |
| 102 | + |
| 103 | + def dispatch_json(self, key_string: str) -> BaseGrammarObject: |
| 104 | + """Create a grammar from JSON schema. |
| 105 | +
|
| 106 | + Args: |
| 107 | + key_string: JSON schema string |
| 108 | +
|
| 109 | + Returns: |
| 110 | + Grammar object |
| 111 | + """ |
| 112 | + raise NotImplementedError() |
| 113 | + |
| 114 | + def dispatch_regex(self, key_string: str) -> BaseGrammarObject: |
| 115 | + """Create a grammar from regex pattern. |
| 116 | +
|
| 117 | + Args: |
| 118 | + key_string: Regex pattern string |
| 119 | +
|
| 120 | + Returns: |
| 121 | + Grammar object |
| 122 | + """ |
| 123 | + raise NotImplementedError() |
| 124 | + |
| 125 | + def dispatch_ebnf(self, key_string: str) -> BaseGrammarObject: |
| 126 | + """Create a grammar from EBNF definition. |
| 127 | +
|
| 128 | + Args: |
| 129 | + key_string: EBNF grammar string |
| 130 | +
|
| 131 | + Returns: |
| 132 | + Grammar object |
| 133 | + """ |
| 134 | + raise NotImplementedError() |
| 135 | + |
| 136 | + def dispatch_structural_tag(self, key_string: str) -> BaseGrammarObject: |
| 137 | + """Create a grammar from structural tag configuration. |
| 138 | +
|
| 139 | + Args: |
| 140 | + key_string: JSON string of structural tag config |
| 141 | +
|
| 142 | + Returns: |
| 143 | + Grammar object |
| 144 | + """ |
| 145 | + raise NotImplementedError() |
| 146 | + |
| 147 | + def shutdown(self): |
| 148 | + """Shutdown the thread pool executor.""" |
| 149 | + self.executor.shutdown(wait=False) |
| 150 | + |
| 151 | + |
| 152 | +# Sentinel object for invalid/failed grammar compilation |
| 153 | +INVALID_GRAMMAR_OBJ = BaseGrammarObject() |
| 154 | + |
| 155 | + |
| 156 | +def create_grammar_backend( |
| 157 | + server_args: ServerArgs, |
| 158 | + tokenizer, |
| 159 | + vocab_size: int, |
| 160 | + eos_token_ids: set | None = None, |
| 161 | +) -> BaseGrammarBackend | None: |
| 162 | + name = server_args.grammar_backend |
| 163 | + |
| 164 | + if name == "llguidance": |
| 165 | + from sgl_jax.srt.constrained.llguidance_backend import GuidanceBackend |
| 166 | + |
| 167 | + grammar_backend = GuidanceBackend( |
| 168 | + tokenizer=tokenizer, |
| 169 | + num_threads=4, |
| 170 | + n_vocab=vocab_size, |
| 171 | + any_whitespace=not server_args.constrained_json_disable_any_whitespace, |
| 172 | + whitespace_pattern=server_args.constrained_json_whitespace_pattern, |
| 173 | + ) |
| 174 | + elif name == "none": |
| 175 | + return None |
| 176 | + else: |
| 177 | + raise ValueError(f"Invalid grammar backend: {name}") |
| 178 | + |
| 179 | + return grammar_backend |
0 commit comments