Talk to me out log probabilities from the output of a large language model, and how we can interpret them. Particularly in a cognitive science context.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Okay, let's break down log probabilities in the context of a Large Language Model's (LLM) output, specifically thinking about how to interpret them, especially from a cognitive science perspective.
1. What an LLM is Fundamentally Doing
At its core, a typical LLM trained on vast amounts of text is a highly sophisticated next-token predictor. Given a sequence of text (the "prompt" or the preceding words it has generated), it calculates the likelihood of every possible next token in its vocabulary.
Tokens: These can be words, parts of words (like "##ing"), punctuation, or special symbols. The model has a fixed vocabulary of tens or hundreds of thousands of these tokens.
Probability Distribution: The model outputs a probability distribution over this entire vocabulary for the very next token. This means for every token in its vocabulary, it assigns a probability between 0 and 1, where the sum of probabilities for all tokens equals 1.
Example: If the text is "The cat sat on the", the model might calculate:
P("mat") = 0.4
P("floor") = 0.3
P("sofa") = 0.15
P("dog") = 0.02
P("apple") = 0.00001
... and so on for every token in its vocabulary.
2. Why Log Probabilities?
Instead of outputting raw probabilities, LLMs (and many other probabilistic models) often provide log probabilities. Why?
Computational Stability (Avoiding Underflow): When you have a long sequence of tokens, the probability of that entire sequence is the product of the probabilities of each token given the preceding ones: P(sequence) = P(token1) * P(token2 | token1) * P(token3 | token1, token2) * ...
Probabilities are often small numbers (e.g., 0.001, 0.0000001). Multiplying many small numbers together results in extremely small numbers, which can become computationally difficult to handle or can "underflow" (become zero due to limitations in computer precision).
Transforming Multiplication to Addition: The logarithm of a product is the sum of the logarithms: log(a * b) = log(a) + log(b). By using log probabilities, the probability of a sequence becomes the sum of the log probabilities of the individual tokens. Summing is computationally much more stable than multiplying many small numbers.
Scale and Interpretation:
The logarithm used is typically the natural logarithm (ln) or base-e log.
The logarithm of a probability (a number between 0 and 1) is always zero or a negative number.
log(1) = 0 (This corresponds to a 100% certain event).
log(0) = -infinity (This corresponds to an impossible event).
Log probabilities will range from 0 down to potentially very large negative numbers.
Example (Log Probabilities):
log(0.4) ≈ -0.916
log(0.3) ≈ -1.204
log(0.15) ≈ -1.897
log(0.02) ≈ -3.912
log(0.00001) ≈ -11.513
So, for "The cat sat on the", the model might output a list of tokens and their log probabilities:
"mat": -0.916
"floor": -1.204
"sofa": -1.897
"dog": -3.912
"apple": -11.513
... and so on.
3. Interpreting Log Probabilities
When an LLM generates text, it often provides the log probability of the chosen next token, and sometimes the log probabilities for a limited set of other highly probable tokens.
How do you interpret these numbers?
Magnitude: The closer the log probability is to 0, the higher the original probability was, and the more confident the model was in that token being the next one. More negative numbers indicate lower confidence/probability.
-0.1 is much more likely than -5.0.
-1.0 is less likely than -0.5.
Comparison: Comparing the log probabilities of different tokens tells you their relative likelihood according to the model in that specific context. If "mat" has log prob -0.9 and "floor" has -1.2, the model considered "mat" about exp(-0.9 - (-1.2)) = exp(0.3) ≈ 1.35 times more likely than "floor".
Model Uncertainty: The distribution of log probabilities across the top few tokens gives insight into the model's uncertainty.
If the top log probability is very close to 0 (e.g., -0.05) and the next highest is much more negative (e.g., -2.0), the model is highly confident in its top choice.
If the top log probabilities are relatively close together (e.g., -0.8, -1.1, -1.3), the model is less certain and sees several tokens as reasonably probable continuations.
4. Log Probabilities in a Cognitive Science Context
This is where it gets interesting, drawing analogies (important word: analogy, not identity) between the computational process of the LLM and human language processing.
Prediction and Expectation: Human language processing is highly predictive. We constantly anticipate upcoming words and structures. LLMs, through their probability distributions, explicitly model this predictive process. The log probability of a token represents the model's learned expectation or surprise level for that token appearing next, given the preceding context.
Uncertainty and Ambiguity: The distribution of log probabilities can be seen as analogous to how humans might handle uncertainty or ambiguity.
A narrow distribution (one token with a much higher log prob) is like a human having a strong expectation and low uncertainty about the next word.
A flatter distribution (several tokens with similar, less negative log probs) is like a human encountering a point where several continuations seem plausible, leading to higher uncertainty. This maps onto cognitive concepts like probabilistic parsing or maintaining multiple interpretations in working memory.
Processing Difficulty / Surprisal: A major concept in cognitive models of language processing (often informed by eye-tracking or ERP studies, like the N400 component) is surprisal. Surprisal is often defined as the negative logarithm of the probability of the observed word given its context: Surprisal = -log(P(word | context)).
Notice this is simply the negative of the log probability provided by the model!
A word with a low probability (very negative log prob) is highly surprising. In humans, this often correlates with increased processing effort (longer reading times, larger N400).
A word with a high probability (log prob closer to 0) is less surprising and easier to process.
So, the log probabilities directly map onto a key metric used to study human online language processing difficulty. Researchers use LLMs to calculate surprisal for stimuli and correlate it with human behavioral or neural data.
Hypothesis Space: The list of tokens and their associated log probabilities can be seen as the model's internal "hypothesis space" for the next word. It's not just picking one; it's considering multiple possibilities and assigning a likelihood to each based on its training. This parallels cognitive ideas about how humans might activate multiple candidate words or sentence structures during comprehension.
Knowledge Representation: The specific log probabilities reflect the model's learned associations and "knowledge" derived from its training data. For example, why is "mat" more likely than "apple" after "The cat sat on the"? Because in the vast text data the model trained on, "cat sat on the mat" occurs frequently, reflecting real-world knowledge and common linguistic patterns. The log probabilities encode this statistical knowledge.
In Summary for Cognitive Science:
Log probabilities from LLMs offer a quantitative window into the model's internal state regarding word prediction. They are valuable because:
They provide a direct measure of the model's learned expectation or likelihood for any given next token in a specific context.
Their distribution reveals the model's uncertainty or the plausibility of alternative continuations.
Their negative value directly corresponds to the concept of surprisal, a widely used metric in cognitive science to model human language processing difficulty and expectation violation.
By examining these log probabilities, cognitive scientists can gain insights into:
How statistical learning can lead to human-like patterns of prediction and expectation in language.
Computational models of surprisal and processing load.
How a system trained purely on text statistics might implicitly capture aspects of world knowledge and linguistic regularities that influence prediction.
However, it's crucial to remember that the LLM is a model. Its "probabilities" are based on patterns in its training data, not necessarily true understanding or the full richness of human cognitive processes like pragmatics, intent, or embodied experience. But as a sophisticated prediction engine, its log probabilities provide a powerful tool for exploring predictive coding hypotheses in language cognition.
User
Talk about the the llm log probabilities in a decision making context. Do they become more interpretable when the llm is constrained to respond with only a single word? Discuss the scenario where the model must respond with either A or B (i.e., it's choosing between options). And scenario where the model must respond with an integer (e.g., the model is estimating the amount of energy an appliance uses). To what extent can the logprob be interpreted as 'confidence' in these contexts?
Assistant
Okay, let's explore LLM log probabilities specifically in the context of decision-making, particularly when the model's output is constrained to represent a choice or an estimate.
How LLMs "Decide"
As we discussed, an LLM, at each step, computes a probability distribution over its entire vocabulary for the next token. When the model needs to produce an output, it essentially makes a "decision" about which token(s) to generate. This decision is based on this distribution.
Greedy Decoding: The simplest "decision" is to pick the token with the highest probability (or least negative log probability).
Sampling: More complex "decisions" involve sampling from the distribution, potentially influenced by parameters like 'temperature' (higher temperature makes less likely tokens more probable to be sampled, leading to more varied, sometimes surprising output).
Constrained Decoding: When the model is explicitly told to respond in a specific format (like choosing between A and B, or providing a number), the decoding process can be constrained to only consider tokens that fit that format.
The log probabilities are the model's internal "scores" for each potential next token, reflecting its learned likelihood based on the prompt and its training data.
Interpretability When Constrained to a Single Word
Yes, the log probabilities become significantly more interpretable when the LLM is constrained to respond with only a single word (or a specific set of single-word options).
Clear Comparison Space: When the model must output a single token, the relevant part of the probability distribution is the slice corresponding to the valid single-word tokens in its vocabulary.
Direct Likelihood: The log probability associated with the chosen single word directly tells you how likely the model considered that specific word to be, relative to all other possible single words it could have generated at that point, given the context.
Reduced Complexity: You're not dealing with the accumulated log probabilities of multi-token sequences, which can be harder to intuitively grasp. You're looking at the scores of atomic units (tokens/words).
If the API or output format allows you to see the log probabilities of the top few single-word options (not just the chosen one), the interpretability increases even further, as you can see the shape of the distribution over likely single-word continuations.
Scenario 1: Forced Choice (Responding with A or B)
User
Evaluate how well this R code works for going from log probs to confidence:
--- LLM Query Function (Modified for Confidence Calculation) ---
This approach calculates the average probability of the individual tokens that form the generated number sequence.
Let's break down what logprobs_data$content provides: It's a list, where each element corresponds to a token generated in the model's response. For a response like "120", logprobs_data$content might contain information for tokens "1", "2", and "0" (assuming they are separate tokens), or possibly other tokens if max_tokens was set higher and trailing text appeared before the number extraction. For each token t_i at position i in the sequence, logprobs_data$content[[i]]$logprob is the log probability of generating t_igiven the preceding tokenst_1, ..., t_{i-1}.
So, exp(logprob) for token t_i is P(t_i | t_1, ..., t_{i-1}).
The code then calculates mean(P(t_i | t_1, ..., t_{i-1})) over all tokens t_i in the generated numerical string.
How well does mean(exp(token_logprobs)) represent confidence in the numerical estimate?
This is a prime example where log probabilities are very interpretable. Imagine a prompt like:
"Which of the following colours is typically associated with danger?
A) Blue
B) Red
Respond with either 'A' or 'B'."
When the model processes this, it generates a probability distribution for the very next token. Assuming the prompt successfully primes it to output either "A" or "B", the relevant parts of the distribution are the log probabilities for the tokens corresponding to "A" and "B".
Let log_prob("A") be the log probability of the token "A".
Let log_prob("B") be the log probability of the token "B".
Interpretation:
Decision Basis: The model will likely choose the token with the higher log probability (less negative). If log_prob("B") > log_prob("A") (e.g., log_prob("B") = -0.5, log_prob("A") = -2.0), the model will choose "B".
Relative Preference: The difference between the log probabilities (log_prob("chosen") - log_prob("alternative")) indicates the strength of the model's preference. A large positive difference (e.g., -0.5 vs -5.0, difference is 4.5) means the model strongly favored the chosen option. A small positive difference (e.g., -1.0 vs -1.1, difference is 0.1) means the model saw them as nearly equally likely, even if it picked one.
Absolute Likelihood: The absolute values of log_prob("A") and log_prob("B") matter. If log_prob("B") is -0.1 and log_prob("A") is -5.0, the model is not only certain "B" is better than "A", but it's also very likely in general to produce "B" as the next token (close to 0 log prob). If log_prob("B") is -4.0 and log_prob("A") is -4.5, while "B" is still preferred, neither "A" nor "B" was a highly probable next token according to the model; the entire distribution might have been "flat" or peaked elsewhere, perhaps indicating the prompt wasn't strongly guiding it, or it's "uncertain" even between these options.
Scenario 2: Integer Response (Estimating Energy Use)
Consider a prompt like:
"Estimate the average daily energy consumption of a standard refrigerator in kilowatt-hours (kWh). Respond with just the integer number."
Here, the model needs to output a sequence of tokens that form an integer (e.g., "1", "0").
The model will consider the probability distribution for the first token (likely a digit), then the distribution for the second token given the first, and so on.
The log probability of a sequence of tokens is the sum of the log probabilities of each token conditioned on the preceding ones: log P("120") = log P("1") + log P("2" | "1") + log P("0" | "12"). The model typically chooses the sequence with the highest total log probability.
Interpretation:
Sequence Likelihood: The total log probability of the chosen integer sequence (e.g., "120") tells you how likely that specific sequence was according to the model, summing up the likelihoods at each step of generating the digits.
Comparison is Harder (Often Requires More Data): Comparing the log probability of "120" (-1.5 total log prob) to "50" (-2.0 total log prob) or "1000" (-3.0 total log prob) is possible if you have the log probabilities for these alternative sequences. This often requires specifically asking the model for top log probs over a range of tokens at each step or using tools that expose this.
Distribution over Numbers: Ideally, to interpret "confidence" in an estimate, you'd want to see the model's estimated log probability for a range of possible numbers around its chosen value. Does the log probability drop off steeply for numbers slightly higher or lower than "120" (e.g., "110", "130"), or is there a relatively flat peak spanning, say, "100" to "150"? A steeper peak indicates higher "confidence" in the specific chosen number.
Extent to Which Log Probabilities Can Be Interpreted as "Confidence"
In these constrained decision-making contexts, log probabilities are indeed a valuable indicator of the model's statistical confidence or certainty based on its training data.
Statistical Certainty: A higher log probability (closer to 0) for the chosen output, especially when combined with significantly lower log probabilities for plausible alternatives, indicates that the model's learned patterns strongly predict that specific output in that context. This is the model saying, "Based on everything I've learned, this option is much more probable than others."
Relative Confidence: Comparing the log probabilities of the options (like A vs. B) directly reflects the model's relative preference, which can be interpreted as relative confidence in one option over another.
Uncertainty: A narrow distribution of log probabilities over options (one much higher than others) suggests low uncertainty within the model's prediction space. A flatter distribution suggests higher uncertainty.
Limitations and Nuances of "Confidence":
Not Truth Confidence: The model's log probability reflects statistical likelihood based on its training data, not necessarily the factual correctness or real-world validity of the output. A model can be highly "confident" (assign a high log prob) to a confidently incorrect statement if that statement was prevalent in its training data in similar contexts (e.g., misinformation).
Context Dependence: Confidence is specific to the exact phrasing of the prompt and the model's internal state at that moment. Slight changes in wording can significantly alter the probability distribution.
Decoding Strategy: The log probabilities represent the potential scores. The actual output depends on the decoding strategy (greedy, sampling). However, even with sampling, the log probabilities guide the likelihood of picking certain tokens.
Vocabulary Limitations: The model can only assign probabilities to tokens in its vocabulary. If a required output is out of vocabulary or needs complex structuring, the log probabilities might not fully capture its "confidence" in generating the concept, only the specific token sequence.
In Summary:
When an LLM is constrained to output a specific type of response representing a decision or estimate (like A/B or an integer), the associated log probabilities become highly informative.
They quantify the model's internal statistical likelihood for each possible valid output option.
Comparing log probabilities reveals the model's relative preference and the strength of its "decision".
The shape of the distribution of log probabilities over the relevant options is a good measure of the model's uncertainty (in a statistical sense) regarding that specific decision or estimate.
While these log probabilities are excellent indicators of the model's internal predictive certainty, it's crucial to interpret this as statistical confidence rooted in training data patterns, not as guaranteed truthfulness or human-like self-assurance.
estimates <- numeric(nrow(items_df))
confidence_scores <- numeric(nrow(items_df))
logprob_details_list <- list() # Store raw logprobs for potential later analysis
system_prompt_content <- "You are participating in a psychology study. Answer questions with only a single number, representing your best estimate. Do not include units, explanations, or any other text."
for (i in 1:nrow(items_df)) {
user_prompt <- items_df$prompt[i]
item_name <- items_df$item_name[i]
message(paste("Stage 1: Getting estimate & confidence for:", item_name))
req_body <- list(
model = model,
messages = list(
list(role = "system", content = system_prompt_content),
list(role = "user", content = user_prompt)
),
temperature = temperature,
n = 1,
max_tokens = 15, # Allow slightly more tokens for numbers like 3500
logprobs = TRUE, # Always request logprobs
top_logprobs = top_n_logprobs
)
current_estimate <- NA
current_confidence <- NA
current_logprobs <- NULL
tryCatch({
response <- request("https://api.openai.com/v1/chat/completions") %>%
req_headers(
"Content-Type" = "application/json",
"Authorization" = paste("Bearer", api_key)
) %>%
req_body_json(req_body) %>%
req_perform() %>%
resp_body_json()
answer_text <- response$choices[[1]]$message$content
numeric_match <- regmatches(answer_text, regexpr("[+-]?([0-9]*[.])?[0-9]+", answer_text))
if (length(numeric_match) > 0) {
current_estimate <- as.numeric(numeric_match)
} else {
warning(paste("Could not extract numeric estimate for item:", item_name, "- Response:", answer_text))
}
# Calculate confidence from logprobs (Average Token Probability)
logprobs_data <- response$choices[[1]]$logprobs
current_logprobs <- logprobs_data # Store raw data
if (!is.null(logprobs_data) && !is.null(logprobs_data$content) && length(logprobs_data$content) > 0) {
# Filter tokens to only include those matching the extracted number's string representation
# This is crucial but tricky due to tokenization variance (e.g., "1500" vs "1", "500")
# Simple approach: use all tokens returned for the number. Refined approach needed for precision.
estimate_str <- as.character(current_estimate)
# A simplified approach: average logprobs of *all* returned content tokens
# Assumes the response is ONLY the number. max_tokens helps enforce this.
token_logprobs <- sapply(logprobs_data$content, function(x) x$logprob)
token_probs <- exp(token_logprobs)
avg_prob <- mean(token_probs, na.rm = TRUE)
current_confidence <- avg_prob
} else {
warning(paste("Logprobs data missing or empty for item:", item_name))
current_confidence <- NA
}
}, error = function(e) {
warning(paste("API Error (Stage 1) for item:", item_name, "-", e$message))
current_estimate <- NA
current_confidence <- NA
current_logprobs <- list(error = e$message)
})
estimates[i] <- current_estimate
confidence_scores[i] <- current_confidence
logprob_details_list[[i]] <- current_logprobs # Store raw logprobs
Sys.sleep(0.6) # Slightly longer pause
if (is.na(llm_estimate) || confidence_level == "Unknown") {
return("Could not generate an explanation due to missing estimate or confidence.")
}
action_verb <- ifelse(item_type == "Energy Used", "uses", "saves")
estimate_str <- format(round(llm_estimate), big.mark = ",") # Format number nicely
Construct base prompt asking for explanation/context
base_prompt <- paste0(
"Regarding the item '", item_name,
"', the estimated energy it ", action_verb, " is approximately ", estimate_str, " units per hour (where a 100W bulb uses 100 units). ",
"Provide a brief, helpful explanation or context (1-2 sentences) related to this estimate."
)
Modify prompt based on confidence level
style_instruction <- switch(confidence_level,
"High" = " Frame your explanation confidently.",
"Medium" = " Frame your explanation with some hedging or mention of typicality (e.g., 'often', 'around', 'typically').",
"Low" = " Frame your explanation expressing uncertainty (e.g., 'It's hard to be precise, but...', 'Estimates can vary...', 'I'm not very sure, but...').",
"Unknown" = "" # Should not happen based on initial check
)
Sys.sleep(0.6) # Pause
return(trimws(explanation)) # Trim whitespace
}
Weakness 1: Averages Conditional Probabilities: The probability of the entire sequence (the number) is the product of these conditional probabilities: P("120") = P("1") * P("2" | "1") * P("0" | "1", "2"). In log space, this is a sum: log P("120") = log P("1") + log P("2" | "1") + log P("0" | "1", "2"). Averaging the individual probabilities does not directly correspond to the probability of the overall sequence. mean(P(t_i | ...)) is mathematically different from exp(sum(log P(t_i | ...))).
Weakness 2: Ignores Alternatives: A key aspect of confidence in an estimate is how likely that estimate is compared to plausible alternative estimates. For example, if the model estimates "120", confidence should relate to how much more likely "120" was than, say, "110", "130", "50", or "500". The current method only looks at the probabilities along the specific path taken to generate "120". It doesn't incorporate information about the probability of generating tokens that would lead to alternative numbers. The top_logprobs parameter in the API request does provide information about other likely tokens at each step, but this code doesn't use the top_logprobs information in the confidence calculation; it only uses the logprob of the chosen token at each step (logprobs_data$content).
Weakness 3: Sensitive to Tokenization: The average probability will be affected by how the number is tokenized. If "120" is three tokens ("1", "2", "0"), the average is over three probabilities. If "120" was a single token in the vocabulary, the average would just be the probability of that one token. This makes scores non-comparable between numbers that are tokenized differently.
Weakness 4: Intuitive Meaning: What does an "average token probability of 0.75" mean in terms of confidence that the actual energy usage is "120 kWh"? It's not immediately clear. It's an internal metric of the model's sequential prediction process, not a direct measure of the estimated value's likelihood within a range of possibilities.
Potential Improvements for Confidence Calculation:
A more theoretically grounded approach for confidence in this context would likely involve one of the following:
Total Log Probability of the Chosen Sequence: Use the sum of the log probabilities for the tokens in the generated number sequence (sum(token_logprobs)). This gives the log probability of the entire number string being generated. A log probability closer to 0 indicates a higher probability for that specific sequence. This still doesn't consider alternatives but is a better metric of how likely the chosen string was. (Need to be mindful that longer sequences inherently have more negative log probabilities).
Average Log Probability of the Chosen Sequence: Divide the sum of log probabilities by the number of tokens (sum(token_logprobs) / num_tokens). This gives an average log probability per token, making it somewhat more comparable across different number lengths. Higher (less negative) average log probability means higher confidence in the sequence given its length.
Comparing Chosen Sequence Logprob to Alternatives (Ideal but Complex): This would involve finding the log probabilities of generating other plausible numerical strings (e.g., by exploring paths in the logprob data or making multiple API calls with slight variations) and seeing how much higher the chosen number's log probability is compared to its neighbors. This is significantly more complex to implement with a standard API call.
Focus on the First Token's Log Probability: The first digit often carries a lot of the information about the magnitude. The log probability of the first token might be a simpler, albeit cruder, proxy for confidence in the general magnitude of the estimate.
Evaluation of the Rest of the Code:
Prompting Strategy: The system prompt and user prompt structure are good for eliciting a specific format. Using temperature = 0.0 for the estimate helps get the single most likely answer, which is appropriate when you want the model's "best guess".
Numeric Extraction: Using regexpr to extract the number is robust to slight variations in formatting (like a space or punctuation before/after).
Error Handling: The tryCatch blocks are good practice for handling API errors and ensuring the loop continues.
Confidence Binning (get_confidence_level): This is a reasonable way to discretize a continuous score. However, the numerical thresholds (0.85, 0.50) are completely arbitrary given the current confidence score calculation method. These thresholds would need to be empirically determined by looking at the distribution of mean(exp(token_logprobs)) scores obtained across many items.
Explanation Generation (generate_explanation): This function's approach of modifying the prompt based on the confidence level to influence the tone of the LLM's response is a very effective technique. This part leverages the LLM's capabilities well. Using a slightly higher temperature (0.5) for the explanation is also sensible to allow for more natural phrasing.
Overall Assessment:
The R code provides a functional pipeline for obtaining an LLM estimate and then generating a confidence-aware explanation.
The architecture is sound.
The method for generating explanations based on a confidence level is well-implemented using prompt engineering.
However, the method for calculating the numerical confidence score itself (mean(exp(token_logprobs))) is not the most theoretically sound or standard way to use log probabilities for quantifying confidence in a numerical estimate. It's an average of sequential token probabilities, not the overall sequence probability or a measure related to the distribution over possible estimates.
Recommendations:
Revise Confidence Calculation: Change current_confidence to use the sum or average of the log probabilities of the generated tokens (e.g., sum(token_logprobs) or mean(token_logprobs)). The sum of log probabilities is the true log probability of the sequence. You'd then need to interpret these log probabilities (more negative means less confident). You might need to experiment with scaling or transforming these log probabilities to make them intuitive or comparable across items.
Examine Raw Logprobs: During development, print or inspect logprobs_data for several responses to understand exactly which tokens are included and what their logprob and top_logprobs look like. This will inform how to best use the available data.
Tune Thresholds: Once you have a more robust confidence score metric, run the code on a sample dataset and examine the distribution of these scores. Adjust the thresholds in get_confidence_level based on this observed distribution to create meaningful bins (e.g., quartiles or based on visual inspection of the histogram of scores).
Consider top_logprobs (Advanced): If you want a more sophisticated confidence measure, explore how to use the top_logprobs data (which provides probabilities for tokens other than the one chosen at each step) to get a better sense of the probability mass around the chosen sequence. This is complex but would provide a richer picture of the model's uncertainty.
In conclusion, the code is a good starting point, but the method of calculating the confidence score from log probabilities needs refinement to be a more accurate reflection of the model's certainty in the numerical estimate itself.