infr_server/logprobs.rs
1//! The OpenAI `logprobs` reply fields: the wire shape of each generated token's log probability,
2//! and [`LogprobStops`], which keeps each token's entry with the text it produced while stop
3//! sequences are cut from that text.
4
5use std::collections::VecDeque;
6
7use infr_engine::TokenLogprob;
8use serde::Serialize;
9
10use crate::StopMatcher;
11
12/// OpenAI's `choice.logprobs` / `choice.delta.logprobs`.
13#[derive(Debug, Clone, Serialize)]
14pub struct ChatLogprobs {
15 pub content: Vec<ChatTokenLogprob>,
16}
17
18/// One token's entry in [`ChatLogprobs::content`]. `id` is a llama.cpp-style extension; OpenAI
19/// clients ignore unknown fields.
20#[derive(Debug, Clone, Serialize)]
21pub struct ChatTokenLogprob {
22 pub id: u32,
23 pub token: String,
24 pub bytes: Vec<u8>,
25 pub logprob: f32,
26 pub top_logprobs: Vec<ChatTokenLogprobAlt>,
27}
28
29#[derive(Debug, Clone, Serialize)]
30pub struct ChatTokenLogprobAlt {
31 pub id: u32,
32 pub token: String,
33 pub bytes: Vec<u8>,
34 pub logprob: f32,
35}
36
37impl ChatLogprobs {
38 /// The wire shape for a run of generated tokens. Text and bytes come from the backend that
39 /// filled the [`TokenLogprob`](infr_engine::TokenLogprob) entries in.
40 pub fn from_tokens(tokens: &[infr_engine::TokenLogprob]) -> Self {
41 Self {
42 content: tokens
43 .iter()
44 .map(|t| ChatTokenLogprob {
45 id: t.token,
46 token: t.text.clone(),
47 bytes: t.bytes.clone(),
48 logprob: t.logprob,
49 top_logprobs: t
50 .top
51 .iter()
52 .map(|a| ChatTokenLogprobAlt {
53 id: a.token,
54 token: a.text.clone(),
55 bytes: a.bytes.clone(),
56 logprob: a.logprob,
57 })
58 .collect(),
59 })
60 .collect(),
61 }
62 }
63}
64
65/// A [`StopMatcher`] that carries each token's log probability along with the text it produced, so
66/// the entries a reply reports are exactly those of the tokens whose text it returns. Shared by the
67/// chat route and `/v1/completions`.
68///
69/// Text arrives as the decoder releases it: one piece and the entries of every token since the
70/// previous piece (a character split across tokens, or a special token the stream skips, adds no
71/// piece of its own). Such a group is the unit entries are attached to; this never assumes a
72/// token's own bytes add up to the streamed text.
73///
74/// The rule: an entry is reported when its token's text is at least partly returned. A token whose
75/// text a stop sequence cut in the middle keeps its entry, which still describes the whole sampled
76/// token, as every entry does; the tokens of the stop sequence itself, and any after it, have none.
77/// Entries pushed with no text cover nothing returned and are dropped.
78#[derive(Debug, Default)]
79pub struct LogprobStops {
80 stops: StopMatcher,
81 /// Text the matcher released that has not been handed out: the released head of a token group
82 /// whose tail the matcher still holds.
83 released: String,
84 /// The groups covering `released` followed by what the matcher holds, oldest first.
85 groups: VecDeque<Group>,
86}
87
88#[derive(Debug)]
89struct Group {
90 /// Bytes of this group's text not yet handed out.
91 len: usize,
92 logprobs: Vec<TokenLogprob>,
93}
94
95/// Text that is now safe to send, with the entries of the tokens it belongs to.
96#[derive(Debug, Default, PartialEq)]
97pub struct TokenText {
98 pub text: String,
99 pub logprobs: Vec<TokenLogprob>,
100}
101
102impl LogprobStops {
103 pub fn new(stops: Vec<String>) -> Self {
104 Self {
105 stops: StopMatcher::new(stops),
106 ..Self::default()
107 }
108 }
109
110 /// A stop sequence has fired: generation must halt and no further text may be emitted.
111 pub fn hit(&self) -> bool {
112 self.stops.hit()
113 }
114
115 /// Feed one decoded piece and the entries of the tokens that produced it. Returns the text now
116 /// safe to send, split where it changes group so a caller can keep a delta from splitting a
117 /// token. A group with entries is handed out whole, so its text waits while the matcher holds
118 /// any of it; text without entries is handed out as the matcher releases it, so a request that
119 /// asked for no log probabilities streams exactly as through a bare [`StopMatcher`].
120 pub fn push(&mut self, piece: &str, logprobs: Vec<TokenLogprob>) -> Vec<TokenText> {
121 if self.stops.hit() {
122 return Vec::new();
123 }
124 self.groups.push_back(Group {
125 len: piece.len(),
126 logprobs,
127 });
128 let safe = self.stops.push(piece);
129 self.released.push_str(&safe);
130 self.hand_out(self.stops.hit())
131 }
132
133 /// End of generation: what the matcher still holds was never a stop, so all of it goes out.
134 pub fn flush(&mut self) -> Vec<TokenText> {
135 let tail = self.stops.flush();
136 self.released.push_str(&tail);
137 self.hand_out(true)
138 }
139
140 /// Hand out the released text, group by group. While more text may follow (`all` false), a
141 /// group with entries goes out only once all of its text has been released; at the end every
142 /// released byte goes, and a group cut short by a stop takes its entries with what it returned.
143 fn hand_out(&mut self, all: bool) -> Vec<TokenText> {
144 let mut out: Vec<TokenText> = Vec::new();
145 while let Some(g) = self.groups.front_mut() {
146 let avail = self.released.len();
147 let take = if g.len <= avail {
148 g.len
149 } else if all || g.logprobs.is_empty() {
150 avail
151 } else {
152 break;
153 };
154 if take == 0 && g.len > 0 {
155 break;
156 }
157 let text: String = self.released.drain(..take).collect();
158 g.len -= take;
159 let logprobs = if take > 0 {
160 std::mem::take(&mut g.logprobs)
161 } else {
162 Vec::new()
163 };
164 if g.len == 0 {
165 self.groups.pop_front();
166 }
167 match out.last_mut() {
168 // Text without entries joins the run before it when that has none either, so it
169 // goes out in one piece, as the matcher released it.
170 Some(last) if last.logprobs.is_empty() && logprobs.is_empty() => {
171 last.text.push_str(&text)
172 }
173 _ if text.is_empty() => {}
174 _ => out.push(TokenText { text, logprobs }),
175 }
176 }
177 if all {
178 // Nothing after a stop, or after the end, is returned.
179 self.groups.clear();
180 self.released.clear();
181 }
182 out
183 }
184}
185
186#[cfg(test)]
187mod tests {
188 use super::*;
189
190 /// A request without log probabilities streams exactly as through a bare [`StopMatcher`]: the
191 /// same text in the same pieces, at a stop and at the end.
192 #[test]
193 fn without_entries_it_releases_what_the_stop_matcher_does() {
194 let pieces = ["Hel", "lo E", "N", "d. ", "Then E", "ND", " more"];
195 for stops in [vec![], vec!["END".to_owned()], vec!["\n\n".to_owned()]] {
196 let mut bare = StopMatcher::new(stops.clone());
197 let mut ours = LogprobStops::new(stops.clone());
198 for p in pieces {
199 let want = bare.push(p);
200 let got = ours.push(p, Vec::new());
201 let got: Vec<&str> = got.iter().map(|t| t.text.as_str()).collect();
202 if want.is_empty() {
203 assert!(got.is_empty(), "{stops:?} {p:?}: {got:?}");
204 } else {
205 assert_eq!(got, [want.as_str()], "{stops:?} {p:?}");
206 }
207 }
208 let want = bare.flush();
209 let got: String = ours.flush().into_iter().map(|t| t.text).collect();
210 assert_eq!(got, want, "{stops:?}");
211 assert_eq!(ours.hit(), bare.hit(), "{stops:?}");
212 }
213 }
214
215 /// A clamped log probability goes out as a number, never as `null`.
216 #[test]
217 fn the_lowest_finite_logprob_serializes_as_a_number() {
218 let lp = infr_engine::TokenLogprob::unresolved(1, f32::MIN, Vec::new());
219 let v = serde_json::to_value(ChatLogprobs::from_tokens(&[lp])).unwrap();
220 assert!(v["content"][0]["logprob"].is_number(), "{v}");
221 }
222}