Skip to main content

infr_chat/
logprob.rs

1//! Per-token log probabilities for the OpenAI `logprobs` reply fields.
2
3/// One generated token's log probability and, when the request asked for them, its most likely
4/// alternatives. `text`/`bytes` are filled in by the backend that owns the tokenizer; the decode
5/// loop only knows the id and the probabilities.
6#[derive(Clone, Debug, PartialEq)]
7pub struct TokenLogprob {
8    pub token: u32,
9    /// The token decoded on its own. May be a replacement character for a byte-fallback token
10    /// whose bytes only complete in context.
11    pub text: String,
12    /// The bytes of `text`, as OpenAI's `bytes` array.
13    pub bytes: Vec<u8>,
14    /// Natural log of the token's probability: the log-softmax of the logits row it was sampled
15    /// from, after `logit_bias` and the penalties, before temperature and the truncating samplers
16    /// (top-k, top-p, min-p).
17    pub logprob: f32,
18    /// The most likely tokens at this position, at most the request's `top_logprobs`, descending
19    /// by probability. Does not necessarily contain `token`.
20    pub top: Vec<TokenLogprobAlt>,
21}
22
23/// One alternative in [`TokenLogprob::top`].
24#[derive(Clone, Debug, PartialEq)]
25pub struct TokenLogprobAlt {
26    pub token: u32,
27    pub text: String,
28    pub bytes: Vec<u8>,
29    pub logprob: f32,
30}
31
32impl TokenLogprob {
33    /// A token id and its probability, before the tokenizer-dependent fields are filled in.
34    pub fn unresolved(token: u32, logprob: f32, top: Vec<TokenLogprobAlt>) -> Self {
35        Self {
36            token,
37            text: String::new(),
38            bytes: Vec::new(),
39            logprob,
40            top,
41        }
42    }
43}