133 lines
4.0 kB
1"""Showing what the rules do, one step at a time.
2
3Constrained decoding is invisible from the results file: a well formed answer
4looks the same whether the rule shaped it or the model happened to get it
5right. This module makes the difference visible. At every step it reports the
6tokens the model scored highest, which of them the rule turned down, and which
7one was written in the end.
8
9Nothing here decides anything. The decoder hands over what it has already
10computed, and this only prints it, so a traced run and a silent one write the
11same answer.
12"""
13
14import json
15import sys
16from typing import Sequence
17
18from pydantic import BaseModel, ConfigDict, Field
19
20STOP_TEXT = "<end of turn>"
21NO_TEXT = "<no text>"
22_TAIL = 48
23
24
25def readable(piece: bytes, stop: bool) -> str:
26 """Describe what a token would write, short enough for one line.
27
28 Args:
29 piece: The bytes of the token, empty for an id the vocabulary does not
30 describe.
31 stop: Whether the id is one the model ends a turn with.
32
33 Returns:
34 A quoted rendering of the bytes, or a marker for a token writing none.
35 """
36 if stop:
37 return STOP_TEXT
38 if not piece:
39 return NO_TEXT
40 return json.dumps(piece.decode("utf-8", errors="replace"))
41
42
43class Candidate(BaseModel):
44 """One token the model wanted at one step.
45
46 Attributes:
47 token_id: The id the model scored.
48 text: What writing it would print.
49 score: The score the model gave it.
50 legal: Whether the rule accepts it here.
51 chosen: Whether it is the one the decoder acted on.
52 """
53
54 model_config = ConfigDict(frozen=True)
55
56 token_id: int
57 text: str
58 score: float
59 legal: bool = False
60 chosen: bool = False
61
62 @property
63 def status(self) -> str:
64 """Name what became of this token.
65
66 Returns:
67 "taken" for the one written, "allowed" for a legal token passed
68 over, "blocked" for one the rule refused.
69 """
70 if self.chosen:
71 return "taken"
72 return "allowed" if self.legal else "blocked"
73
74
75class Tracer(BaseModel):
76 """Reports every step of a generation on stderr.
77
78 Standard output stays clean, so a traced run can still be piped.
79
80 Attributes:
81 top_k: How many of the best-scoring tokens to show per step.
82 """
83
84 model_config = ConfigDict(frozen=True)
85
86 top_k: int = Field(default=5, gt=0)
87
88 def begin(self, label: str) -> None:
89 """Announce the generation that is starting.
90
91 Args:
92 label: What is being written, such as "choosing a function".
93 """
94 print(f"trace: {label}" if label else "trace:", file=sys.stderr)
95
96 def step(self, index: int, written: str, candidates: Sequence[Candidate]) -> None:
97 """Report one step: the answer so far, then the best-scoring tokens.
98
99 Args:
100 index: Which step this is, counted from zero.
101 written: The answer as it stands before this step.
102 candidates: The best-scoring tokens, best first.
103 """
104 print(f" step {index} so far {json.dumps(_tail(written))}", file=sys.stderr)
105 for candidate in candidates:
106 line = (
107 f" {candidate.status:<8}{candidate.score:9.2f}"
108 f" id {candidate.token_id:>7} {candidate.text}"
109 )
110 print(line, file=sys.stderr)
111
112 def end(self, answer: str, reason: str) -> None:
113 """Report how the generation finished.
114
115 Args:
116 answer: The text that was written.
117 reason: Why it stopped there.
118 """
119 print(f" done {json.dumps(answer)} ({reason})", file=sys.stderr)
120
121
122def _tail(written: str) -> str:
123 """Keep the end of a long answer, which is what the next step follows on.
124
125 Args:
126 written: The answer as it stands.
127
128 Returns:
129 The whole text, or its last characters behind an ellipsis.
130 """
131 if len(written) <= _TAIL:
132 return written
133 return f"...{written[-_TAIL:]}"