|
| 1 | +"""Cache for the compressed finite state machine.""" |
| 2 | +import logging |
| 3 | +from typing import List, Optional, Tuple, Union |
| 4 | + |
| 5 | +import torch |
| 6 | + |
| 7 | +from scratchpad.constrained import GrammarMatcher, RegexGuide |
| 8 | +from .bnf_cache import BNFCache |
| 9 | +from .fsm_cache import FSMCache |
| 10 | +from .jump_forward import JumpForwardCache, JumpForwardMap |
| 11 | + |
| 12 | +# from sglang.srt.managers.schedule_batch import Req |
| 13 | + |
| 14 | +logger = logging.getLogger(__name__) |
| 15 | + |
| 16 | +INIT_INCREMENTAL_DETOKENIZATION_OFFSET = 5 |
| 17 | + |
| 18 | + |
| 19 | +class XGrammarJump: |
| 20 | + pass |
| 21 | + |
| 22 | + |
| 23 | +class JumpHelper: |
| 24 | + data: Union[List, str] |
| 25 | + state: int |
| 26 | + suffix_ids: List[int] |
| 27 | + |
| 28 | + def __init__( |
| 29 | + self, data: Union[List, str] = "", state: int = -1, suffix_ids=[] |
| 30 | + ) -> None: |
| 31 | + self.data = data |
| 32 | + self.state = state |
| 33 | + self.suffix_ids = suffix_ids |
| 34 | + |
| 35 | + def can_jump(self): |
| 36 | + return len(self.data) > 0 |
| 37 | + |
| 38 | + |
| 39 | +class Grammar: |
| 40 | + grammar: Union[GrammarMatcher, Tuple[RegexGuide, int]] |
| 41 | + jump_map: Union[XGrammarJump, JumpForwardMap, None] |
| 42 | + |
| 43 | + def __init__( |
| 44 | + self, |
| 45 | + grammar: Union[GrammarMatcher, Tuple[RegexGuide, int]], |
| 46 | + jump_map: Union[XGrammarJump, JumpForwardMap, None], |
| 47 | + ) -> None: |
| 48 | + self.grammar = grammar |
| 49 | + self.jump_map = jump_map |
| 50 | + |
| 51 | + def accept_token(self, token: int): |
| 52 | + if isinstance(self.grammar, GrammarMatcher): |
| 53 | + assert self.grammar.accept_token(token) |
| 54 | + else: |
| 55 | + guide, state = self.grammar |
| 56 | + self.grammar = guide, guide.get_next_state(state, token) |
| 57 | + |
| 58 | + def try_jump(self, tokenizer) -> JumpHelper: |
| 59 | + if isinstance(self.jump_map, XGrammarJump): |
| 60 | + assert isinstance(self.grammar, GrammarMatcher) |
| 61 | + return JumpHelper(self.grammar.find_jump_forward_string()) |
| 62 | + elif isinstance(self.jump_map, JumpForwardMap): |
| 63 | + assert isinstance(self.grammar, Tuple) |
| 64 | + |
| 65 | + _, state = self.grammar |
| 66 | + jump_forward_bytes = self.jump_map.jump_forward_byte(state) |
| 67 | + if jump_forward_bytes is None or len(jump_forward_bytes) == 0: |
| 68 | + return JumpHelper() # can't jump |
| 69 | + |
| 70 | + # preprocess the jump forward string |
| 71 | + suffix_bytes = [] |
| 72 | + continuation_range = range(0x80, 0xC0) |
| 73 | + cur_state = state |
| 74 | + while ( |
| 75 | + len(jump_forward_bytes) |
| 76 | + and jump_forward_bytes[0][0] in continuation_range |
| 77 | + ): |
| 78 | + # continuation bytes |
| 79 | + byte_edge = jump_forward_bytes.pop(0) |
| 80 | + suffix_bytes.append(byte_edge[0]) |
| 81 | + cur_state = byte_edge[1] |
| 82 | + |
| 83 | + suffix_tokens = [f"<0x{hex(b)[2:].upper()}>" for b in suffix_bytes] |
| 84 | + suffix_ids = tokenizer.convert_tokens_to_ids(suffix_tokens) |
| 85 | + return JumpHelper(suffix_ids, cur_state, suffix_bytes) |
| 86 | + else: |
| 87 | + return JumpHelper() # can't jump |
| 88 | + |
| 89 | + def jump_forward_str_state(self, helper: JumpHelper) -> Tuple[str, int]: |
| 90 | + if isinstance(helper.data, str): |
| 91 | + return helper.data, -1 |
| 92 | + else: |
| 93 | + assert isinstance(self.jump_map, JumpForwardMap) |
| 94 | + return self.jump_map.jump_forward_symbol(helper.state) |
| 95 | + |
| 96 | + def jump_and_retokenize( |
| 97 | + self, old_output_ids: List[int], new_output_ids: List[int], next_state: int |
| 98 | + ): |
| 99 | + if isinstance(self.grammar, GrammarMatcher): |
| 100 | + k = 0 |
| 101 | + for i, old_id in enumerate(old_output_ids): |
| 102 | + if old_id == new_output_ids[i]: |
| 103 | + k = i + 1 |
| 104 | + else: |
| 105 | + break |
| 106 | + |
| 107 | + # rollback to the last token that is the same |
| 108 | + if k < len(old_output_ids): |
| 109 | + self.grammar.rollback(len(old_output_ids) - k) |
| 110 | + |
| 111 | + for i in range(k, len(new_output_ids)): |
| 112 | + assert self.grammar.accept_token(new_output_ids[i]) |
| 113 | + else: |
| 114 | + self.grammar = self.grammar[0], next_state |
| 115 | + |
| 116 | + def fill_vocab_mask(self, vocab_mask: torch.Tensor, vocab_size: int): |
| 117 | + if isinstance(self.grammar, GrammarMatcher): |
| 118 | + # Note that this bitmask is a bitset, not bool |
| 119 | + bitmask = self.grammar.find_next_token_bitmask() |
| 120 | + # Mask the tokens that are not allowed |
| 121 | + vocab_mask[ |
| 122 | + self.grammar.get_rejected_tokens_from_bitmask(bitmask, vocab_size) |
| 123 | + ] = 1 |
| 124 | + else: |
| 125 | + guide, state = self.grammar |
| 126 | + vocab_mask.fill_(1) |
| 127 | + vocab_mask[guide.get_next_instruction(state).tokens] = 0 |
| 128 | + |
| 129 | + |
| 130 | +class GrammarCache: |
| 131 | + grammar_cache: Union[BNFCache, FSMCache] |
| 132 | + jump_cache: Union[XGrammarJump, JumpForwardCache, None] |
| 133 | + |
| 134 | + def __init__( |
| 135 | + self, |
| 136 | + tokenizer_path, |
| 137 | + tokenizer_args_dict, |
| 138 | + skip_tokenizer_init=False, |
| 139 | + whitespace_patterns=None, |
| 140 | + backend=None, |
| 141 | + allow_jump=False, |
| 142 | + ): |
| 143 | + if backend == "xgrammar": |
| 144 | + self.grammar_cache = BNFCache( |
| 145 | + tokenizer_path=tokenizer_path, |
| 146 | + tokenizer_args_dict=tokenizer_args_dict, |
| 147 | + skip_tokenizer_init=skip_tokenizer_init, |
| 148 | + whitespace_patterns=whitespace_patterns, |
| 149 | + ) |
| 150 | + self.jump_cache = XGrammarJump() if allow_jump else None |
| 151 | + else: |
| 152 | + assert backend == "outlines" |
| 153 | + self.grammar_cache = FSMCache( |
| 154 | + tokenizer_path=tokenizer_path, |
| 155 | + tokenizer_args_dict=tokenizer_args_dict, |
| 156 | + skip_tokenizer_init=skip_tokenizer_init, |
| 157 | + constrained_json_whitespace_pattern=whitespace_patterns, |
| 158 | + enable=True, |
| 159 | + ) |
| 160 | + self.jump_cache = JumpForwardCache() if allow_jump else None |
| 161 | + |
| 162 | + def query(self, key: Tuple[str, str], vocab_size: int) -> Grammar: |
| 163 | + if isinstance(self.grammar_cache, BNFCache): |
| 164 | + assert not isinstance(self.jump_cache, JumpForwardCache) |
| 165 | + return Grammar(self.grammar_cache.query(key, vocab_size), self.jump_cache) |
| 166 | + else: |
| 167 | + jump_map = None |
| 168 | + guide, regex = self.grammar_cache.query(key) |
| 169 | + if isinstance(self.jump_cache, JumpForwardCache): |
| 170 | + jump_map = self.jump_cache.query(regex) |
| 171 | + return Grammar((guide, 0), jump_map) |
| 172 | + |
| 173 | + def reset(self): |
| 174 | + if isinstance(self.grammar_cache, FSMCache): |
| 175 | + self.grammar_cache.reset() |
| 176 | + if isinstance(self.jump_cache, JumpForwardCache): |
| 177 | + self.jump_cache.reset() |
0 commit comments