314 lines
12 kB
1"""The generation loop: the model chooses, but only among legal tokens.
2
3At every step the model scores every token of its vocabulary. Instead of taking
4the best one, the decoder walks the scores from best to worst and takes the
5first token whose bytes the rule accepts. So the rule decides what may be said,
6and the model still decides what is said.
7
8Walking a sorted list is what keeps this cheap: the first candidate is almost
9always legal, so the search stops immediately.
10
11What is generated is kept as token ids and read back with the decode of
12vocab.py, which is built from the vocabulary file. The SDK offers a decode of
13its own; it is never called.
14
15Where the answer ends is also the model's call. A rule that is satisfied may
16still allow more, as a list of names does when one name begins another. There
17the decoder offers the model a way out: the marker it ends a turn with, such as
18Qwen's <|im_end|>. That marker writes no text, so it can never be found in the
19vocabulary the way an ordinary token is; its id is handed to the decoder. Once
20the rule is satisfied and the model scores that id above every legal
21continuation, the answer is finished.
22"""
23
24from typing import Any, List, Optional, Tuple
25
26import numpy as np
27from numpy.typing import NDArray
28from pydantic import BaseModel, ConfigDict, Field
29
30from .grammar import Constraint
31from .trace import Candidate, Tracer, readable
32from .vocab import decode
33
34_BYTE_VALUES = 256
35
36
37class DecoderError(Exception):
38 """Raised when no legal token exists, or the answer never finishes."""
39
40
41class ConstrainedDecoder(BaseModel):
42 """Writes one answer, one token at a time, under one rule.
43
44 Attributes:
45 llm: The model, used for its scores and its tokenizer.
46 token_bytes: The bytes every token id stands for, indexed by id.
47 stop_ids: The ids this model ends a turn with, which it may pick once
48 the rule is satisfied. Empty leaves the rule alone in deciding.
49 max_new_tokens: How many tokens a single answer may take.
50 tracer: Where to report every step, or None to say nothing.
51 """
52
53 model_config = ConfigDict(arbitrary_types_allowed=True, frozen=True)
54
55 llm: Any
56 token_bytes: Tuple[bytes, ...]
57 stop_ids: Tuple[int, ...] = ()
58 max_new_tokens: int = Field(default=128, gt=0)
59 tracer: Optional[Tracer] = None
60
61 def generate(self, prompt: str, constraint: Constraint, label: str = "") -> str:
62 """Continue the prompt with text the rule accepts.
63
64 Args:
65 prompt: The text the model is asked to continue.
66 constraint: The rule the answer must follow.
67 label: What this generation is for, shown when tracing.
68
69 Returns:
70 The generated text, which the rule guarantees is well formed.
71
72 Raises:
73 DecoderError: If no legal token exists, or the answer is still
74 unfinished after max_new_tokens tokens.
75 """
76 context = [int(token_id) for token_id in self.llm.encode(prompt)[0].tolist()]
77 state = constraint.start()
78 written: List[int] = []
79 if self.tracer is not None:
80 self.tracer.begin(label)
81
82 for index in range(self.max_new_tokens):
83 if constraint.is_complete(state) and not _can_grow(constraint, state):
84 return self._finish(written, "the rule allows nothing more")
85
86 scores = np.asarray(self.llm.get_logits_from_input_ids(context), dtype=np.float64)
87 order = np.argsort(-scores)
88 chosen = self._best_legal_token(order, constraint, state)
89 stopping = constraint.is_complete(state) and self._would_rather_stop(order, chosen)
90 self._trace_step(index, written, scores, order, constraint, state, chosen, stopping)
91 if stopping:
92 return self._finish(written, "the model ended its turn")
93 if chosen is None:
94 self._trace_end(written, "no legal token was left")
95 raise DecoderError("no token of the vocabulary can continue the answer")
96
97 token_id, _, state = chosen
98 context.append(token_id)
99 written.append(token_id)
100
101 if not constraint.is_complete(state):
102 self._trace_end(written, f"the budget of {self.max_new_tokens} tokens ran out")
103 raise DecoderError(f"the answer was unfinished after {self.max_new_tokens} tokens")
104 return self._finish(written, f"the budget of {self.max_new_tokens} tokens ran out")
105
106 def _best_legal_token(
107 self,
108 order: NDArray[np.intp],
109 constraint: Constraint,
110 state: Any,
111 ) -> Optional[Tuple[int, bytes, Any]]:
112 """Find the best-scoring token the rule still accepts.
113
114 Args:
115 order: The token ids, best-scoring first.
116 constraint: The rule being enforced.
117 state: How far the answer has got.
118
119 Returns:
120 The token id, the bytes it writes and the progress after it, or
121 None if the whole vocabulary is illegal here.
122 """
123 for token_id in order:
124 piece = self._bytes_of(int(token_id))
125 if not piece:
126 continue
127 advanced = _consume(constraint, state, piece)
128 if advanced is not None:
129 return int(token_id), piece, advanced
130 return None
131
132 def _would_rather_stop(
133 self,
134 order: NDArray[np.intp],
135 chosen: Optional[Tuple[int, bytes, Any]],
136 ) -> bool:
137 """Tell whether the model prefers ending its turn to writing more.
138
139 Only asked once the rule is satisfied, so stopping is always allowed
140 here. Since the ids come best-scoring first, an ending marker met before
141 the chosen token is one the model wanted more.
142
143 Args:
144 order: The token ids, best-scoring first.
145 chosen: The best legal continuation, or None if there is none.
146
147 Returns:
148 True if the answer should end where it stands.
149 """
150 if not self.stop_ids:
151 return False
152 for token_id in order:
153 if int(token_id) in self.stop_ids:
154 return True
155 if chosen is not None and int(token_id) == chosen[0]:
156 return False
157 return chosen is None
158
159 def _finish(self, written: List[int], reason: str) -> str:
160 """Read the generated ids back as text, reporting why the answer ends.
161
162 Args:
163 written: The ids generated so far.
164 reason: Why the loop stopped.
165
166 Returns:
167 The generated text.
168 """
169 self._trace_end(written, reason)
170 return decode(self.token_bytes, written)
171
172 def _trace_step(
173 self,
174 index: int,
175 written: List[int],
176 scores: NDArray[np.float64],
177 order: NDArray[np.intp],
178 constraint: Constraint,
179 state: Any,
180 chosen: Optional[Tuple[int, bytes, Any]],
181 stopping: bool,
182 ) -> None:
183 """Report what the model wanted at this step and what the rule allowed.
184
185 Only the best-scoring few are described, since the rest are never
186 reached: the decoder takes the first legal token of the list. The token
187 actually acted on is always described too, however deep it sat, because
188 how far the rule had to dig is the whole point of watching.
189
190 Args:
191 index: Which step this is, counted from zero.
192 written: The ids generated so far.
193 scores: The score of every token id.
194 order: The token ids, best-scoring first.
195 constraint: The rule being enforced.
196 state: How far the answer has got.
197 chosen: The best legal continuation, or None if there is none.
198 stopping: Whether the answer ends here instead.
199 """
200 tracer = self.tracer
201 if tracer is None:
202 return
203
204 taken = self._acted_on(order, chosen, stopping)
205 shown = [int(token_id) for token_id in order[: tracer.top_k]]
206 if taken is not None and taken not in shown:
207 shown.append(taken)
208
209 candidates: List[Candidate] = []
210 for token_id in shown:
211 stop = token_id in self.stop_ids
212 candidates.append(
213 Candidate(
214 token_id=token_id,
215 text=readable(self._bytes_of(token_id), stop),
216 score=float(scores[token_id]),
217 legal=self._is_legal(token_id, stop, constraint, state),
218 chosen=token_id == taken,
219 )
220 )
221 tracer.step(index, decode(self.token_bytes, written), candidates)
222
223 def _acted_on(
224 self,
225 order: NDArray[np.intp],
226 chosen: Optional[Tuple[int, bytes, Any]],
227 stopping: bool,
228 ) -> Optional[int]:
229 """Name the token the step ends on, be it written or an ending marker.
230
231 Args:
232 order: The token ids, best-scoring first.
233 chosen: The best legal continuation, or None if there is none.
234 stopping: Whether the answer ends here instead of growing.
235
236 Returns:
237 The id acted on, or None if the step ends the answer badly.
238 """
239 if not stopping:
240 return chosen[0] if chosen is not None else None
241 return next((int(token_id) for token_id in order if int(token_id) in self.stop_ids), None)
242
243 def _is_legal(self, token_id: int, stop: bool, constraint: Constraint, state: Any) -> bool:
244 """Tell whether a token could be taken here, for the trace to show.
245
246 Args:
247 token_id: The id being described.
248 stop: Whether it is an ending marker.
249 constraint: The rule being enforced.
250 state: How far the answer has got.
251
252 Returns:
253 True if the decoder would be free to take it.
254 """
255 if stop:
256 return constraint.is_complete(state)
257 piece = self._bytes_of(token_id)
258 return bool(piece) and _consume(constraint, state, piece) is not None
259
260 def _trace_end(self, written: List[int], reason: str) -> None:
261 """Report the finished answer, if this run is being traced.
262
263 Args:
264 written: The ids generated so far.
265 reason: Why the loop stopped.
266 """
267 if self.tracer is not None:
268 self.tracer.end(decode(self.token_bytes, written), reason)
269
270 def _bytes_of(self, token_id: int) -> bytes:
271 """Return the bytes a token id writes.
272
273 Args:
274 token_id: The id to look up.
275
276 Returns:
277 Its bytes, or nothing for an id the vocabulary does not describe,
278 such as a conversation marker.
279 """
280 if token_id < len(self.token_bytes):
281 return self.token_bytes[token_id]
282 return b""
283
284
285def _consume(constraint: Constraint, state: Any, piece: bytes) -> Optional[Any]:
286 """Feed a whole token to the rule, byte by byte.
287
288 Args:
289 constraint: The rule being enforced.
290 state: How far the answer has got.
291 piece: The bytes the token would write.
292
293 Returns:
294 The progress after the token, or None if any of its bytes is illegal.
295 """
296 for byte in piece:
297 advanced = constraint.advance(state, byte)
298 if advanced is None:
299 return None
300 state = advanced
301 return state
302
303
304def _can_grow(constraint: Constraint, state: Any) -> bool:
305 """Tell whether a finished answer could still legally grow.
306
307 Args:
308 constraint: The rule being enforced.
309 state: How far the answer has got.
310
311 Returns:
312 True if any byte at all may still be written.
313 """
314 return any(constraint.advance(state, byte) is not None for byte in range(_BYTE_VALUES))