Skip to content
ImagineWorld

Inference-time scaling via self-refinement

node_idnode-book_build-a-reasoning-model_chapter-05-inference-time-scaling-via-self-refinement
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num5
chapter_titleInference-time scaling via self-refinement
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 5 — Inference-time scaling via self-refinement

Section titled “Chapter 5 — Inference-time scaling via self-refinement”

Inference-time scaling via self-refinement

This chapter covers

  • Scoring LLM answers with a simple rule-based scorer
  • Computing an LLM’s confidence in its answers
  • Coding a self-refinement loop where the LLM iteratively improves its answers

The previous chapter introduced the concept of inference-time scaling (inference scaling for short), which improves the accuracy of model responses without further training. In particular, it focused on self-consistency, where the model generates multiple answers, and the final answer is the most frequent one.

As outlined in figure 5.1, this chapter will move beyond self-consistency for inference scaling and cover another popular and useful inference-scaling technique, self-refinement. Instead of generating and choosing from multiple answers, self-refinement focuses on iteratively refining a single answer to correct potential mistakes.

graph LR
    subgraph G1 ["1 - Conventional LLM"]
        direction TB
        A1["Loading pretrained weights"]
        A2["Text generation"]
    end
    subgraph G2 ["2 - Evaluation"]
        direction TB
        B1["Benchmark-based evaluation"]
        B2["Judgment-based evaluation"]
    end
    subgraph G3 ["3 - Inference techniques"]
        direction TB
        C1["Advanced text generation and voting"]
        C2["Self-refinement"]
    end
    subgraph G4 ["4 - Training techniques"]
        direction TB
        D1["Reinforcement learning"]
        D2["Distillation"]
    end
    G1 --> G2 --> G3 --> G4

[!visual-conversion] Figure 5.1 — A model of the topics covered in this book (printed p. 136, scan page-148.png). This chapter continues with stage 3 and focuses on inference-time techniques for improving reasoning without additional training. It introduces self-refinement, where the model iteratively critiques and improves its own answers. The placeholder for this figure did not survive OCR and has been restored here at its print location. Print stage headings: Stage 1: LLM basics (chapter 2) · Stage 2: Measuring performance (chapter 3) · Stage 3: Reasoning without training (chapters 4 and 5) · Stage 4: Reasoning with training (chapters 6 to 8).

5.1 Scoring and iteratively improving model responses

As you’ve seen, inference scaling trades additional compute for better accuracy. We’ve covered two inference-scaling techniques so far: chain-of-thought prompting and self-consistency.

Chain-of-thought prompting, the first method illustrated in figure 5.2, modifies the prompt, such as by adding the phrase “Explain step by step.”, which can trigger a base model to write longer explanations that can in turn improve answer accuracy. This method is particularly useful for base models that don’t naturally provide reasoning-like explanations. Models trained as reasoning models usually don’t benefit from this type of inference scaling because they already explain their answers.

Self-consistency, the second method in figure 5.2, lets the model produce several answers in parallel. We then choose the final answer by selecting the most frequent of these candidates.

Even though self-consistency is quite simple, it often yields large gains in answer accuracy, which is why it has become a common choice in LLM applications where accuracy is a higher priority than latency. Recent examples include DeepSeekMath-V2 and Google’s Gemini 3 Deep Think mode (see appendix A for references). One downside

graph TD
    S1["1 - Load pretrained LLM"] --> S2["2 - Chain-of-thought prompting<br/>(1st inference-scaling method)"]
    S2 --> S3["3 - Temperature scaling"]
    S3 --> S4["4 - Top-p filtering"]
    S4 --> S5["5 - Self-consistency sampling<br/>(2nd inference-scaling method)"]
    S5 --> S6["6 - Logprob scoring"]
    S6 --> S7["7 - Self-refinement<br/>(3rd inference-scaling method)"]

[!visual-conversion] Figure 5.2 — The three inference-time methods to improve reasoning covered in this book (printed p. 138, scan page-150.png). The first two methods were covered in the previous chapter. This chapter covers the third method, self-refinement, where the model iteratively improves its own answers. Steps 1 to 5 are ticked; step 7 (self-refinement) is highlighted and labelled “3rd method: Self-refinement”, with chain-of-thought marked “1st method: CoT prompting” and self-consistency “2nd method: Self-consistency”. The three worked panels are as in figure 4.3: chain-of-thought produces “1. Set up the equation … 2. Eliminate the fraction … Final answer: 83”; self-consistency produces 18, 83, 83, 54, 22 with “Most frequent answer: 83”; and self-refinement takes a first response of 21, critiques it (“The answer is missing a step of solving for x in the equation”) and revises to “Explanation:

  1. Start with the given equation … Final answer: 83”. of self-consistency is that selecting the most common answer requires short answers that can be compared.

In this chapter, we’ll implement a more versatile technique, self-refinement, in which the LLM learns to improve its own answers iteratively (method 3 in figure 5.2). Before we do so, though, we’ll first implement scoring functions to compare and rank different answers, as outlined in figure 5.3.

After loading the pretrained LLM, as in previous chapters (step 1 in figure 5.3), we’ll implement a simple rule-based scoring function to illustrate the concept of scoring (step 2). Then we’ll go over the concepts of token probabilities (step 3) and token log probabilities

graph LR
    R1["1 - Load pretrained LLM"] --> R2["2 - Rule-based score"]
    R2 --> R3["3 - Token probabilities"]
    R3 --> R4["4 - Token log probabilities"]
    R4 --> R5["5 - Logprob scoring"]
    R5 --> R6["6 - Self-refinement"]

[!visual-conversion] Figure 5.3 — We’ll build a simple rule-based score, compute token probabilities and log probabilities, and use these scores as part of a self-refinement method in which the model iteratively improves its own answers (printed p. 139, scan page-151.png). Print annotations: step 1 — “We load a pretrained LLM as in previous chapters”; step 2 — “In this section, we implement a rule-based score to rank or compare different answers generated by the LLM”; step 5 — “Part of the self-refinement method is a scoring function we can use to compare answers.”

(step 4), which we’ll need to implement the log-probability scoring (logprob scoring) method (step 5) for our self-refinement loop (step 6).

We will primarily use the logprob scoring function (step 5 in figure 5.3) to track progress within the self-refinement loop. These scoring functions can also be used to break ties in self-consistency or to select the best response instead of relying on a majority vote.

The overview in figure 5.3, leading up to self-refinement, looks relatively short and straightforward, but the topics of token probability and log probability are somewhat complex. These topics will also be relevant in the next chapter, where we’ll implement reinforcement learning methods to train the LLM. To that end, we’ll spend some time here discussing the concept of log-probability scoring.

As in the previous chapter, we’ll begin by loading the model and tokenizer we’ll use throughout this chapter.

Listing 5.1 Loading the tokenizer and base model

import torch
from reasoning_from_scratch.ch02 import get_device
from reasoning_from_scratch.ch03 import (
load_model_and_tokenizer
)
device = get_device()
device = torch.device("cpu") # Delete this line to run the code on a GPU (if supported by your machine).
model, tokenizer = load_model_and_tokenizer(
which_model="base",
<!-- page: 156 (printed 144) -->
device=device,
use_compile=False,
)

Figure 5.3 We’ll build a simple rule-based score, compute token probabilities and log probabilities, and use these scores as part of a self-refinement method in which the model iteratively improves its own answers.

(step 4), which we’ll need to implement the log-probability scoring (logprob scoring) method (step 5) for our self-refinement loop (step 6).

We will primarily use the logprob scoring function (step 5 in figure 5.3) to track progress within the self-refinement loop. These scoring functions can also be used to break ties in self-consistency or to select the best response instead of relying on a majority vote.

The overview in figure 5.3, leading up to self-refinement, looks relatively short and straightforward, but the topics of token probability and log probability are somewhat complex. These topics will also be relevant in the next chapter, where we’ll implement reinforcement learning methods to train the LLM. To that end, we’ll spend some time here discussing the concept of log-probability scoring.

As in the previous chapter, we’ll begin by loading the model and tokenizer we’ll use throughout this chapter.

Listing 5.1 Loading the tokenizer and base model

The preceding code runs on the CPU by default, to ensure results that are generally more consistent with those shown in this chapter. Small numerical differences can still occur on the CPU, depending on the operating system and machine, but these differences are typically smaller and more predictable than those observed across different accelerator backends.

Sections 5.4 and 5.5 will use computations involving very small numbers with many digits after the decimal point, and these are more sensitive to device choice and low-level implementation details. This is not a problem in practice, but such mismatches can be confusing on a first read-through. For that reason, I recommend starting with the CPU device and considering MPS or CUDA devices later.

To ensure that the model is loaded correctly, let’s use it with the temperature and top-p sampling code from the previous chapter on a MATH-500 prompt.

Listing 5.2 Generating text with temperature scaling and top-p sampling

from reasoning_from_scratch.ch03 import render_prompt
from reasoning_from_scratch.ch04 import (
generate_text_stream_concat_flex,
generate_text_top_p_stream_cache
)
raw_prompt = (
"Half the value of $3x-9$ is $x+37$."
"What is the value of $x$?"
)
prompt = render_prompt(raw_prompt)
prompt_cot = prompt + "\n\nExplain step by step."
torch.manual_seed(0)
response_1 = generate_text_stream_concat_flex(
model, tokenizer, prompt_cot, device,
max_new_tokens=2048, verbose=True,
generate_func=generate_text_top_p_stream_cache,
temperature=0.9,
top_p=0.9
)

The model produces the following response:

The problem states that half the value of 3x-9 is equal to x+37. We need to find the value of {x}.

Step 2: Translate the problem into an equation

Section titled “Step 2: Translate the problem into an equation”

…

[ \boxed{83} ]

Because we are using temperature scaling and top-pp sampling, changing the random seed produces a different response:

torch.manual_seed(3)
response_2 = generate_text_stream_concat_flex(
model, tokenizer, prompt_cot, device,
max_new_tokens=2048, verbose=True,
generate_func=generate_text_top_p_stream_cache,
temperature=0.9,
top_p=0.9,
)

This time, the model responds as follows:

We start with the given equation:
$$
\frac{1}{2} \times (3x - 9) = x + 37
$$
...
Final Answer:
$$
\boxed{83}
$$

In both cases, the model produces the correct final answer (83). The second response is much shorter, which we can confirm by printing the number of characters or tokens in each response:

print("Response 1 characters:", len(response_1))
print("Response 1 tokens:", len(tokenizer.encode(response_1)))
print("\nResponse 2 characters:", len(response_2))
print("Response 2 tokens:", len(tokenizer.encode(response_2)))

This is the result:

Response 1 characters: 1419
Response 1 tokens: 534
Response 2 characters: 533
Response 2 tokens: 231

A shorter response is not necessarily better. If two responses reach the same correct answer, judging which is better is not straightforward. It often depends on human preferences regarding clarity, usefulness, and the partial correctness of the intermediate steps.

Scoring the intermediate steps of a response remains an active research area (see appendix A), and methods such as process reward models, which evaluate the reasoning itself, do not always yield better outputs in practice.

If the qualitative value of two responses is comparable, one thing is certain: shorter responses are cheaper because they require fewer tokens to be generated, and these responses are therefore preferred.

5.3 Scoring LLM responses with a rule-based score

Section titled “5.3 Scoring LLM responses with a rule-based score”

In the previous section, the LLM generated two correct responses. In this section, we’ll develop a simple rule-based scoring function to compare them, as illustrated in figure 5.4.

graph LR
    R1["1 - Load pretrained LLM"] --> R2["2 - Rule-based score"]
    R2 --> R3["3 - Token probabilities"]
    R3 --> R4["4 - Token log probabilities"]
    R4 --> R5["5 - Logprob scoring"]
    R5 --> R6["6 - Self-refinement"]

[!visual-conversion] Figure 5.4 — This section implements a rule-based scorer to rank different answers generated by the pretrained LLM (printed p. 142, scan page-154.png). Step 1 is ticked and step 2 is highlighted. Print annotations: step 1 — “In the previous section, we loaded the pretrained LLM”; step 2 — “Begin with a rule-based score to rank or compare different answers generated by the LLM”; step 5 — “Part of the self-refinement method is a scoring function we can use to compare answers.”

The rule-based scoring function will assign a score to each of two LLM responses (see figure 5.5), which will allow us to rank them and select the better one. Here, “better” refers to format and brevity, not correctness.

There are several ways to implement a scoring function (scorer) for evaluating responses, as shown in figure 5.5. The scorer can be heuristic, meaning a simple rule-based method. It can also be another LLM that rates the answers, often referred to as LLM-as-a-judge (see appendix F). It can also rely on internal probability scores or likelihoods, which we will explore later in this chapter.

In this section, we’ll begin with a heuristic, a rule-based scorer, implemented in listing 5.3. We begin with this version not because it is the most sophisticated option, but because it gives us a simple baseline that will make the later probability-based scorers easier to compare and reason about.

Scoring LLM responses with a rule-based score

Section titled “Scoring LLM responses with a rule-based score”
graph TD
    I["Input:<br/>Half the value of 3x − 9 is x + 37.<br/>What is the value of x?"] --> L["LLM"]
    L -->|"Use temperature scaling and top-p<br/>sampling to generate different answers"| R1
    L --> R2
    subgraph R1 ["Response 1"]
        direction TB
        A1["Step 1: Understand the problem<br/>The problem states that half the value of<br/>3x − 9 is x + 37. We need to find the value of x.<br/>Step 2: Translate the statement into an equation<br/>...<br/>Final answer: 83"]
    end
    subgraph R2 ["Response 2"]
        direction TB
        A2["We start with the given equation:<br/>(1/2)(3x − 9) = x + 37<br/>Step 1: Simplify the left side of the equation.<br/>(1/2)(3x − 9) = (3x − 9)/2<br/>Final answer: 83"]
    end
    R1 --> S1["Scorer → 2.087"]
    R2 --> S2["Scorer → 2.408"]

[!visual-conversion] Figure 5.5 — Two generated responses reach the same correct answer but differ in their explanations (printed p. 143, scan page-155.png). A scorer evaluates the responses and assigns a score to each response. Both responses give the final answer 83, but response 1 scores 2.087 and response 2 scores 2.408. Print annotation: “We develop a scorer to assign a score to each answer.”

from reasoning_from_scratch.ch03 import extract_final_candidate
import math
def heuristic_score(
answer,
prompt=None,
brevity_bonus=500.0,
boxed_bonus=2.0,
extract_bonus=1.0,
fulltext_bonus=0.0,
):
score = 0.0
cand = extract_final_candidate(answer, fallback="none")
if cand:
score += boxed_bonus
else:
cand = extract_final_candidate(answer, fallback="number_only")
if cand:
score += extract_bonus
else:
cand = extract_final_candidate(
answer, fallback="number_then_full"
)
if cand:
score += fulltext_bonus
score += 1.5 * math.exp(-len(answer) / brevity_bonus)
return score

Give weaker rewards if the answer doesn’t have a boxed value.

Add a brevity reward that decays with text length.

This heuristic_score function assigns a numerical score to an LLM answer based on how cleanly the answer can be extracted and on the answer’s length. For instance, we award a bonus if the answer has a \boxed{} response (boxed_bonus). Otherwise, we give a smaller bonus if it contains at least a number (extract_bonus). The brevity_bonus assigns points based on how short the answer is.

The absolute values are not very important. What matters more is their relative scale. Here, boxed_bonus=2.0 is intentionally larger than extract_bonus=1.0 so that a cleanly boxed final answer is preferred over one where we can only extract a number. The brevity term contributes at most 1.5 additional points, so it mainly helps to break ties between answers of similar quality rather than dominating the extraction bonuses. We also keep fulltext_bonus=0.0 so that arbitrary long-form answers are not rewarded unless we can extract a clearer final candidate from them.

NOTE We are developing a scorer here, and not using the verifier from chapter 3, because we are assuming we don’t know the true answer to the question. We only use the verifier for evaluation when we’re evaluating the model on an existing test set.

The prompt argument is a placeholder that doesn’t serve a purpose in the function, but it will make life easier (and the code simpler) when we develop a self-refinement function with swappable scorer plugins later in the chapter.

Although brevity_bonus=500.0 may appear high, it is used as an exponentially decaying term via 1.5×math.exp(−len(answer)/brevity_bonus)1.5 \times \mathrm{math.exp}(-\text{len(answer)} / \text{brevity\_bonus}). The following plot, whose results are shown in figure 5.6, illustrates the effect of the brevity_bonus on the score.

Listing 5.4 Plotting the brevity penalty curve

import matplotlib.pyplot as plt
def plot_brevity_curve(brevity_bonus, max_len=2048):
lengths = torch.arange(1, max_len)
scores = 1.5 * torch.exp(-lengths / brevity_bonus)
<!-- page: 157 (printed 145) -->
plt.figure(figsize=(4, 3))
plt.plot(lengths, scores)
plt.xlabel("Text length (number of characters)")
plt.ylabel("Score contribution")
plt.tight_layout()
plt.show()
plot_brevity_curve(500)

The score bonus approaches 1.5 for shorter answers, while answers longer than 1,000 characters receive a bonus of 0.2 or less. A response of a few hundred characters corresponds to a short paragraph or a concise worked solution, whereas 1,000 characters or more usually means a fairly long, multisentence explanation. This term mildly favors compact answers, but it does not force the model to collapse everything into a one-line response.

For simplicity, the brevity bonus is computed using the number of characters rather than the number of tokens, which avoids passing the tokenizer to the scoring function. Using token counts would also be reasonable and may even be preferable.

We can now apply the heuristic scorer to the first (longer) response from section 5.2:

print(round(heuristic_score(response_1), 3))

The resulting score is 2.088. Next, let’s try the second (shorter) response:

print(round(heuristic_score(response_2), 3))

The computed score is 2.517, which means the second (shorter) response would be the preferred answer.

You’ve now seen the basic idea of scoring methods. Later in the chapter, we’ll develop another scorer and return to the heuristic scorer as part of the self-refinement method.

Exercise 5.1: Using the heuristic scorer as a tiebreaker in self-consistency

Extend the self-consistency implementation (self_consistency_vote) in the previous chapter (listing 4.17) so that it can handle ties among candidate answers. For instance, when two or more answers receive the same number of votes, apply the heuristic scorer (heuristic_score) from this section to the tied candidates, and select the one with the highest score. Tip: You don’t need to modify the self_consistency_vote function

Text length (characters)Score contribution
01.500
1001.228
2500.910
5000.552
7500.335
10000.203
12500.123
15000.075
17500.045
20000.028
Score contribution
1.50 |#
| #
1.25 | #
| #
1.00 | #
| #
0.75 | #
| ##
0.50 | ###
| ####
0.25 | ######
| #########
0.00 +------------------------------------------
0 500 1000 1500 2000
Text length (number of characters)

[!visual-conversion] Figure 5.6 — A simple rule-based length penalty used by our scorer (printed p. 145, scan page-157.png). Longer explanations receive a smaller score contribution. Values are exact — computed from the scorer’s own formula 1.5 * math.exp(-len(answer) / brevity_bonus) with brevity_bonus = 500.0, not read off the scan. The surrounding text confirms the shape: the bonus approaches 1.5 for shorter answers, while answers longer than 1,000 characters receive a bonus of 0.2 or less.

(continued) itself to apply the tiebreaking; instead, apply the tiebreaking to the results dictionary returned by self_consistency_vote.

Exercise 5.2: Using the heuristic scorer in a best-of-N setup

Modify the self-consistency implementation so that the final answer is chosen using the heuristic scorer rather than majority voting. Generate N candidate answers for each problem (where N = 2 or higher), score each candidate with the heuristic scorer, and select the one with the highest score as the final prediction. (If we use a scorer instead of majority vote, the method is called best-of-N in the literature, as opposed to self-consistency.)

Apply this method to a small subset of MATH-500 and compare the results to both plain best-of-N and the self-consistency tiebreaker from exercise 5.1.

Note that the scorer includes several parameters chosen by intuition, which is why we refer to it as a heuristic score. To optimize the extraction and brevity reward settings, we could plug this scorer into the self-consistency or best-of-N methods from exercises 5.1 and 5.2 and evaluate which settings yield higher accuracy on a benchmark dataset such as MATH-500.

As a practical rule of thumb, increase the extraction-related bonuses if the scorer too often prefers answers whose final result is hard to parse. Increase the brevity pressure if the scorer keeps favoring long, rambling answers that do not improve the final result. On the other hand, if the scorer starts preferring overly short but incomplete answers, reduce the brevity penalty or increase the reward for clearly extractable final answers. Thinking about these tradeoffs is often more useful than focusing on the exact numeric values in isolation.

5.4 Understanding token probability scores

Let’s now take the first step toward building a scorer based on the model’s own confidence (step 5 in figure 5.7), where confidence is a probability that the model assigns. At each position, the model will distribute the probability mass over the possible next tokens. If the tokens in a proposed answer consistently receive high probability, this suggests that the answer is more compatible with the model’s own internal preferences. Conversely, if the model assigns very low probability to many of the answer tokens, that’s a sign that the model itself does not strongly support that answer.

In this section, we’ll start by computing the token probability scores for a proposed answer and use them to estimate how likely the model considers that answer to be (step 3 in figure 5.7). This may seem like a detour, but these probability and log-probability

Understanding token probability scores

graph LR
    R1["1 - Load pretrained LLM"] --> R2["2 - Rule-based score"]
    R2 --> R3["3 - Token probabilities"]
    R3 --> R4["4 - Token log probabilities"]
    R4 --> R5["5 - Logprob scoring"]
    R5 --> R6["6 - Self-refinement"]

[!visual-conversion] Figure 5.7 — In this section, we’ll move from a simple rule-based score to token-level probabilities (printed p. 147, scan page-159.png). These probabilities will form the basis for the logprob scoring method that we’ll use later in the self-refinement approach. Steps 1 and 2 are ticked and step 3 is highlighted. Print annotations: step 2 — “In the previous section, we implemented a simple rule-based score to rank or compare different answers generated by the LLM”; step 5 — “In this section, we’ll illustrate the concept of token probabilities, which we’ll use to implement a scorer based on log-probability scores (logprob scorer).”

concepts will become important again in the next chapter, where they’ll reappear inside the training objective rather than only being an inference-time scoring signal.

The token probability scores we’ll compute in this section are also known in the literature as next-token probabilities, per-token probabilities, sequence likelihoods, or, more loosely, token-level likelihoods. They represent the probability that the model assigns to each possible next token, expressed as a normalized (softmax) distribution over the vocabulary.

NOTE The term logprob is common shorthand in the AI literature for log probability.

Although this discussion of probabilities may sound complicated, it relies on the same mechanism used for text generation that we covered in the previous chapter. For instance, in chapter 4, you saw that the model assigns a logit score to each token in the vocabulary at each stage, and it selects the next token based on these scores. This process, which we discussed in section 4.4, is illustrated again in figure 5.8.

In the previous chapter, we looked up the vocabulary entry corresponding to the highest score (vocabulary index 19846, corresponding to the token “BerLin” in figure 5.8) to get the next generated token. Here, we’ll revisit the logits with a different goal in mind. Instead of generating the next token, we want to use the scores to quantify the model’s confidence in a particular answer. In other words, we are not going to generate anything based on the scores here; we are just inspecting them.

For example, consider two candidate answers we want to score:

  • “The capital of Germany is Berlin”
  • “The capital of Germany is Bridge”

Our goal is to quantify how confident the model is in each answer. It is important to keep in mind that model confidence does not automatically imply correctness. A model

The model computes a score distribution over the entire vocabulary (set of possible tokens); we select the token with the highest score as the next generated token.

graph BT
    A["1 - Convert input text into token IDs<br/>'The capital of Germany is'<br/>→ 785, 6722, 315, 9856, 374"] --> B["LLM"]
    B --> C["2 - Get scores for the next token<br/>(logit value per vocabulary entry)"]
    C --> D["3 - Find the vocabulary index with the highest score<br/>index 19846 → 'Berlin'"]

[!visual-conversion] Figure 5.8 — How an LLM selects the next token (printed p. 148, scan page-160.png). The model converts the input text into token IDs, computes a score for every vocabulary token, and chooses the token with the highest score. The plot on the right shows the logit values for a subset of the vocabulary (indices ~19,800–19,900), with the token for Berlin having the highest score — the same slice plotted in figure 4.7. Print annotation at the top: “The model computes a score distribution over the entire vocabulary (set of possible tokens); we select the token with the highest score as the next generated token.” Individual bar heights are not recoverable at scan resolution.

can assign high probability to an answer simply because it fits the patterns it has learned well, even if the answer is factually wrong. When this happens, we still need additional methods, such as retrieval-augmented generation, external tools such as web search, calculators, or code execution, or comparison-based approaches like self-consistency to detect and correct confidently wrong answers.

In figure 5.8, the input text “The capital of Germany is” is fed to the model, and the next token with the highest score (“Berlin”) is selected. Instead of selecting a token, here we’ll compare the scores assigned to two candidate next tokens, “Berlin” and “Bridge”, as shown in figure 5.9. (“Bridge” is used as an alternative because it appears within the vocabulary range shown in figure 5.8.)

Rather than working with the raw logits shown in figure 5.9, we convert them to probabilities. Probabilities are easier to interpret, they’re comparable across inputs, and they form the basis for the logprob scoring method we’ll use later in the chapter.

As discussed in chapter 4, applying torch.softmax converts logits into probability values. Figure 5.10 shows the resulting probability distribution. The token probabilities shown in figure 5.10 are computed using torch.softmax as we did in section 4.4.3, as part of the multinomial sampling procedure. The difference here is that we do not Understanding token probability scores

graph BT
    A["1 - Convert input text into token IDs and pass them to the LLM<br/>'The capital of Germany is' → 785, 6722, 315, 9856, 374"] --> B["LLM"]
    B --> C["2 - Get scores for the next token<br/>(logit value per vocabulary entry)"]
    D["3 - Convert tokens we want to score<br/>'Berlin' → 19846<br/>'Bridge' → 19874"] --> E
    C --> E["4 - Look up token score<br/>Berlin → 19.8758<br/>Bridge → 6.625"]

[!visual-conversion] Figure 5.9 — How we look up the logit scores for specific tokens (printed p. 149, scan page-161.png). After passing the input text through the model, we obtain a logit value for every vocabulary token. We then convert the candidate tokens we want to score into token IDs and read off their corresponding logit values from the distribution. In the print, the full-vocabulary bar plot is shown at right with Berlin marked at its peak; the Berlin candidate is ticked and Bridge crossed out, since Bridge is used only as an alternative for comparison.

sample from the distribution. Instead, we simply look up the probability assigned to specific tokens.

In figure 5.10, only the bar for “Berlin” is visible, with a probability of 0.1695. The probabilities for other tokens in the plotted range are near zero. This indicates that the model assigns higher confidence to “Berlin” than to “Bridge” as the next token, given the input text “The capital of Germany is”.

NOTE The bars shown in figure 5.10 do not sum to 1 because the full vocabulary contains 151,000 tokens, and the figure displays only a small slice of the distribution (token indices 19,800–19,900).

In practice, we usually want to compare complete answers rather than individual tokens. This extension from single-token to sequence-level scoring is illustrated in figure

graph BT
    A["1 - Convert input text into token IDs and pass them to the LLM<br/>'The capital of Germany is'"] --> B["LLM"]
    B --> C["2 - Get scores for the next token"]
    C --> D["torch.softmax → probability distribution<br/>Berlin: 0.1695 · Bridge: near zero"]

[!visual-conversion] Figure 5.10 — Next-token scoring (printed p. 150, scan page-162.png). The input text is converted into token IDs and fed to the LLM, which outputs logits for the next token. After applying a softmax, these logits become probabilities, where tokens like "Berlin" receive a high probability and unlikely alternatives such as "Bridge" receive values near zero. The surrounding text gives the one exact figure: only the bar for "Berlin" is visible in the plotted range, with a probability of 0.1695. The bars do not sum to 1 because the full vocabulary contains 151,000 tokens and the figure displays only a small slice of the distribution (token indices 19,800–19,900). Individual bar heights are not recoverable at scan resolution.

5.11, where we compute the probability of each token given its preceding tokens. This is the same procedure as in figure 5.10, except that we repeat it for every token in the sequence.

During ordinary text generation, the model does this one step at a time as it goes along, selecting the next token. Here, we use the same mechanism in a different way: instead of sampling new tokens, we take a completed candidate answer and score each of its tokens one by one under the model. We then multiply these probabilities to obtain the probability of the full sequence, also called the joint probability.

Understanding token probability scores

In each row, the text left of the box is the input to the LLM. Softmax probability score for “of” given “The capital” as input

The capital → 6.151e-05 The capital of → 0.48484 The capital of Germany → 0.816724 The capital of Germany is → 0.73828 The capital of Germany is Berlin → 0.16895

The capital → 6.151e-05 The capital of → 0.48484 The capital of Germany → 0.816724 The capital of Germany is → 0.73828 The capital of Germany is Bridge → 2.98e-07

6.151e-05 = 0.48484 = 0.816724 = 0.73828 = 2.98e-07

  • 0.73828 = 0.16895
  • 0.0572e-05 = 0

Joint probability of the sequence “The capital of Germany is Berlin” Conditional probability of “Berlin” given “The capital of Germany is”

Text input to the LLMNext tokenProbability
The capital—(conditional probability)
The capital ofof(conditional probability)
The capital of GermanyGermany(conditional probability)
The capital of Germany isis(conditional probability)
The capital of Germany is BerlinBerlin(conditional probability)
P(sequence)=∏tP(tokent∣preceding text)P(\text{sequence}) = \prod_{t} P(\text{token}_t \mid \text{preceding text})

[!visual-conversion] Figure 5.11 — Computing token probability scores for a given sequence (printed p. 153, scan page-165.png). For each position, we feed the preceding text into the model and read off the softmax probability of the next token. Multiplying these conditional probabilities yields the joint probability of the full sequence. The figure has the same row-by-row shape as figure 5.16, but in probability space rather than log space, and it contrasts the sequence ending in "Berlin" with the nonsensical "Bridge" variant. Because the joint probability multiplies many small values, both sequences end up close to zero — the problem the next section solves with log probabilities. The individual per-row probability values are not legible at scan resolution and are therefore not transcribed here. The placeholder for this figure did not survive OCR and has been restored at its print location.

Joint probability of a token sequence

For those comfortable with mathematical notation, the joint probability of a token sequence can be written compactly as a product of conditional probabilities. For a sequence x1,x2,...,xTx_1, x_2, ..., x_T and model weights WW, this is

P(x1,x2,...,xT∣W)=∏t=1TP(xt∣xt−1,W)P(x_1, x_2, ..., x_T|W) = \prod_{t=1}^T P(x_t|x_{t-1}, W)

Expanded, this becomes

P(x1∣W)⋅P(x2∣x1,W)⋅P(x3∣x1:2,W)⋯P(xT∣x1:t−1,W)P(x_1|W) \cdot P(x_2|x_1, W) \cdot P(x_3|x_{1:2}, W) \cdots P(x_T|x_{1:t-1}, W)

This matches exactly what we compute in figure 5.11. At each position, we feed the context into the model, obtain the probability of the next token, and multiply these scores across the sequence.

Ideally, the probability assigned to the sequence “The capital of Germany is Berlin” should be much higher than that of the nonsensical answer “The capital of Germany is Bridge”. Because the joint probability is obtained by multiplying many small values, the resulting probabilities for both sequences in figure 5.11 are close to zero. We address this issue in the next section.

The two answers in this example are nearly identical, differing only in the final token (“Berlin” versus “Bridge”). The same method can also be applied to sequences that differ more substantially, such as the answers generated in section 5.2 for the MATH-500 prompt (“Half the value of 3x−93x-9 is x+37x+37. What is the value of xx?”).

How this probability scoring differs from greedy sampling and temperature-plus-top-p sampling

When we compute token probability scores, we are not generating text. The full sequence already exists, and we are simply querying the model for the probability of each next token, given the fixed context as input. Nothing about these probabilities influences later inputs. It is a retrospective scoring procedure, not a generation step.

Generation methods like the generate_text_stream_cache function (greedy sampling) and the generate_text_top_p_stream_cache function that we coded in chapter 4 behave very differently. Greedy sampling always selects the most likely next token, while temperature sampling and top-p sampling draw from a reshaped probability distribution. These procedures modify the distribution at each step and then commit to a single token, which becomes the input for the next position.

None of these sampling strategies, including greedy sampling, is guaranteed to produce the sequence with the highest overall probability under the model. A token that looks suboptimal at one step can lead to a future step where the following tokens are much more likely. On the other hand, a locally optimal choice may steer the model toward low-probability sequences later.

Even if we did find the globally highest-probability sequence under the model, that still would not guarantee that it is the correct answer or the most useful answer for the user. It would only mean that it is the sequence the model prefers most under its learned distribution.

Temperature and top-p sampling add even more variability by flattening or truncating the distribution before drawing samples, which may further disconnect the generated text from the globally most likely sequence.

By scoring an existing answer, we avoid all these complications. We do not run a sampling algorithm, and the model does not choose any tokens. We only evaluate how probable the given sequence would have been, if it had already been written.

We’ve looked at the conceptual explanations, so now let’s see the token probability calculation in action.

Listing 5.5 Calculating next-token probabilities

@torch.inference_mode()
def calc_next_token_probas(model, tokenizer, prompt, device, show=True):
token_ids = torch.tensor(tokenizer.encode(prompt), device=device)

Understanding token probability scores

logits = model(token_ids.unsqueeze(0)).squeeze(0) # Get logits and probabilities as in text generation functions.
all_probs = torch.softmax(logits, dim=-1)
t_idx = torch.arange(0, token_ids.shape[0] - 1, device=device) # Select positions we score (here: all).
next_ids = token_ids[1:]
next_token_probas = all_probs[t_idx, next_ids] # Get probabilities for each next token.
prod_next_token_probas = torch.prod(next_token_probas)
if show:
print("Next-token probabilities:", next_token_probas)
print("Joint probability:", prod_next_token_probas)
else:
return next_token_probas, prod_next_token_probas

Print annotations: “Since we have the text, we know the true next tokens.” and “The likelihood of the sequence is the product of the probability scores.”

As you can see, the calc_next_token_probas function, which computes the next-token probabilities (illustrated in figure 5.11), is relatively short and appears simple at first glance. But a lot is happening in this function to carry out the computation. Figure 5.12 illustrates this with a simpler input text example and a tiny five-word vocabulary.

The calc_next_token_probas function, illustrated in figure 5.12, computes next-token probabilities in a few steps. First, it computes the logits in the same way as the text-generation functions introduced earlier (for example, the out = model(token_ids) line in generate_text_basic from section 2.7).

The resulting logits (step 2 in figure 5.12) have shape [sequence_length, vocab_ size] and are then converted into normalized probability distributions using torch .softmax (step 3), so that the probabilities at each position sum to 1.

To extract the probability assigned to the actual next token at each position, we construct an index tensor t_idx for the positions we want to score and another tensor, next_ids, containing the corresponding target tokens. For example, if the input text is “The capital of Germany is Berlin”, then t_idx refers to the positions corresponding to “The capital of Germany is”, and next_ids contains the tokens shifted by one position: “capital of Germany is Berlin”.

These target tokens are simply the input tokens shifted by one position because an LLM is trained to predict the next token in a sequence. For example, given the input “The capital of Germany is Berlin”, the model is asked at position 2 (the token for “capital”) to predict position 3 (the token for “of”). Using all_probs[t_idx, next_ ids] (steps 4 and 5) retrieves exactly these probability values for each position in the sequence.

Finally, the function uses torch.prod to compute the sequence likelihood as the product of the per-token probabilities (step 6).

Input text: "Some example text"
|
v 1 tokenizer.encode()
token_ids = [2, 1, 3]
|
v 2 model()
logits = [
[2.0, 1.0, 0.8, 3.0, -1.0], # 1st token
[-1.0, 0.5, 1.0, 0.0, 2.0], # 2nd token
[0.1, -0.2, 3.0, 1.0, 0.0], # 3rd token
]
(columns: example | some | text | Zoo | ...)
|
v 3 torch.softmax()
all_probas = [
[0.259, 0.095, 0.035, 0.636, 0.014],
[0.036, 0.076, 0.163, 0.060, 0.643],
[0.097, 0.059, 0.535, 0.196, 0.113],
]
|
v 4 t_idx = [0, 1] ; all_probas[t_idx, _]
For the first token position, "Some", we want the
probability of the next token, "example" -> 0.095
For the second token position, "example", we want
the probability of the next token, "text" -> 0.060
|
v 5 next_tokens = [1, 3] ; all_probas[_, next_ids]
[0.095]
[0.060]
|
v 6 torch.prod()
Joint probability / sequence likelihood of "Some example text"
0.095 * 0.060 = 0.0057

[!visual-conversion] Figure 5.12 — Extracting next-token probabilities (printed p. 154, scan page-166.png). After converting the input text into token IDs, the model computes logits that are transformed into probabilities with a softmax function. Using index tensors for positions and true next tokens, we then get the model’s computed probability for each next token. Print annotation: “We have a tiny vocabulary with only 5 entries for illustration purposes.” All numeric values above are transcribed from the figure.

Let’s see this function in action:

torch.set_printoptions(precision=4, sci_mode=True)
calc_next_token_probs(
model, tokenizer, device=device,
prompt="The capital of Germany is Berlin"
)

This is the resulting output:

Next-token probabilities: tensor([6.1512e-05, 4.6484e-01, 1.6724e-02, 7.3828e-01, 1.6895e-01], dtype=torch.bfloat16) Joint probability: tensor(5.9372e-08, dtype=torch.bfloat16)

Understanding token probability scores

Let’s try another text:

calc_next_token_probas(
model, tokenizer, device=device,
prompt="The capital of Germany is Bridge"
)

This results in the following output:

Next-token probabilities: tensor([6.1512e-05, 4.6484e-01, 1.6724e-02, 7.3828e-01, 2.9802e-07], dtype=torch.bfloat16) Joint probability: tensor(1.0481e-13, dtype=torch.bfloat16)

Analyzing these results, the first response (ending in “Berlin”) had a joint probability (sequence likelihood) of 5.9372e-08, which is larger than the joint probability of the second response, 1.0481e-13. (In decimal form, 5.9372e-08 is 0.000000059372 and 1.0481e-13 is 0.00000000000010481.)

These results make sense because the “Berlin” answer receives a higher sequence likelihood than the “Bridge” answer. Both values are extremely small because multiplying many probabilities less than one quickly produces numbers that approach zero. This makes raw likelihoods difficult to work with in practice, especially for longer sequences where underflow becomes a problem.

NOTE These scores reflect the model’s internal likelihood, not a calibrated probability of correctness. In other words, they tell us how strongly the model prefers one answer over another under its own distribution, not whether the answer is actually true, correct, or useful. A high score means the answer fits the model’s learned patterns well, not that it is guaranteed to be right.

In the next section, we’ll modify this calculation with log probabilities, which will let us avoid these numerical issues and give us a more stable way to score entire sequences.

Probabilities vs. likelihoods

You may have noticed that we’ve used both the terms “probability” and “likelihood.” Is there a difference? In statistics, probabilities describe how likely an event is before we observe any data, and they must sum to one across all possible outcomes. Likelihoods, in contrast, measure how well a specific model explains observed data, and they are viewed as a function of the model’s weights or parameters, not the data. In short, probabilities predict data given a model, while likelihoods evaluate models given data. (For a more detailed example, see my article on probabilities versus likelihoods: “What is the difference between likelihood and probability?” at https://sebastianraschka.com/faq/docs/probability-vs-likelihood.html.)

In LLMs, the next-token probability is technically a probability, not a likelihood, because it comes from a normalized distribution over all possible next tokens that sums to one. In other words, the values in next_token_probas are probabilities, not (continued) likelihoods. They come directly from the model’s softmax over the vocabulary for each position, which is a normalized probability distribution.

The product, computed as the joint probability (torch.prod(next_token_probas)), is the model-assigned probability of the sequence. This quantity is often referred to as the sequence likelihood (especially when viewed as a function of the model parameters).

5.5 From token probability scores to log probabilities

Section titled “5.5 From token probability scores to log probabilities”

The token probabilities computed in the previous section can be used as a scoring function to rank different responses. As we saw, the probability scores can be very small, especially when multiplied to obtain the joint probability or sequence likelihood.

In this section, to avoid the numerical stability issues that often arise when working with such small values, we’ll apply logarithmic scaling (also called log scaling) to these probabilities, as shown in the overview in figure 5.13.

graph LR
    R1["1 - Load pretrained LLM"] --> R2["2 - Rule-based score"]
    R2 --> R3["3 - Token probabilities"]
    R3 --> R4["4 - Token log probabilities"]
    R4 --> R5["5 - Logprob scoring"]
    R5 --> R6["6 - Self-refinement"]

[!visual-conversion] Figure 5.13 — Overview of moving from token probability scores to token log probabilities, which provide a numerically more stable basis for the log-probability scoring used later in self-refinement (printed p. 156, scan page-168.png). Steps 1 to 3 are ticked and step 4 is highlighted. Print annotations: step 3 — “In the previous section, we calculated token probabilities using the softmax function”; step 4 — “In this section, we calculate log probabilities, which are numerically more stable than regular softmax probabilities.” In the previous section, we calculated token probabilities using the softmax function.

In this section, we calculate log probabilities, which are numerically more stable than regular softmax probabilities.

Figure 5.13 Overview of moving from token probabilities to token log probabilities, which provide a numerically more stable basis for the log-probability scoring used later in self-refinement.

NOTE This section focuses on applying a scaling transformation to the probabilities from the previous section. Our overall goal is still to compute the token probabilities, or, in this case, log probabilities (which you’ll see soon).

Consider this simple example of computing probabilities for a selection of logit values:

torch.set_printoptions(precision=4, sci_mode=False)
logits = torch.linspace(-2, 2, steps=7)
probas = torch.softmax(logits, dim=-1)
print(probas)

The probability values are as follows:

tensor([0.0090, 0.0175, 0.0341, 0.0665, 0.1295, 0.2522, 0.4912])

We can turn them into log-probability scores via the torch.log function:

print(torch.log(probas))

These are the log-probability values:

tensor([-4.7109, -4.0442, -3.3776, -2.7109, -2.0442, -1.3776, -0.7109])

Here, torch.log applies the natural logarithm, where log(0.0090)=−4.7109log(0.0090) = -4.7109, and vice versa, e−4.7109=0.0090e^{-4.7109} = 0.0090.

Instead of chaining torch.log(torch.softmax(…)), PyTorch also has an optimized torch.log_softmax function that combines these two operations:

log_probas = torch.log_softmax(logits, dim=-1) print(log_probas)

Similar to before, this returns the following:

tensor([-4.7109, -4.0442, -3.3776, -2.7109, -2.0442, -1.3776, -0.7109])

Note that log scaling changes only the magnitude of the values, not their ordering, so a sequence with a higher likelihood will always have a higher log likelihood as well. To see this visually, let’s plot the logits, probabilities, and log probabilities side by side.

Listing 5.6 Plotting logits, softmax probabilities, and log-softmax values

plt.figure(figsize=(9, 4))
plt.subplot(1, 3, 1)
plt.bar(range(len(logits)), logits, color="C0", alpha=0.7)
plt.title("Logits")
plt.xlabel("Token index")
plt.ylabel("Value")
plt.grid(alpha=0.3)
plt.subplot(1, 3, 2)
plt.bar(range(len(probas)), probas, color="C1", alpha=0.7)
plt.title("torch.softmax(Logits)")
plt.xlabel("Token index")
plt.ylabel("Probability")

Plotting logits Plotting softmax probabilities

plt.ylim(0, 1)
plt.grid(alpha=0.3)
plt.subplot(1, 3, 3)
plt.bar(range(len(log_probas)), log_probas, color="C2", alpha=0.7)
plt.title("torch.log_softmax(logits)")
plt.xlabel("Token index")
plt.ylabel("Log-probability")
plt.grid(alpha=0.3)
plt.tight_layout()
plt.savefig("logits_softmax_log_softmax.pdf")
plt.show()

The resulting plot is shown in figure 5.14. As you can see, the log probabilities have the same order as the logits and probability values. A larger logit corresponds to a larger probability and a less negative log probability. Smaller logits, in turn, produce smaller probabilities and more negative log probabilities.

Token indexLogittorch.softmax(logits)torch.log_softmax(logits)
0−2.00000.0090−4.7109
1−1.33330.0175−4.0442
2−0.66670.0341−3.3776
30.00000.0665−2.7109
40.66670.1295−2.0442
51.33330.2522−1.3776
62.00000.4912−0.7109
Logits torch.softmax(logits) torch.log_softmax(logits)
2.0 | # 1.0 | 0 |
1.5 | # # | | #
1.0 | # # 0.8 | -1 | # #
0.5 | # # # | | # # #
0.0 | # # # # 0.6 | -2 | # # # #
-0.5 | # # # # # | # | # # # # #
-1.0 | # # # # # 0.4 | # # -3 | # # # # # #
-1.5 | # # # # # # | # # # | # # # # # # #
-2.0 | # # # # # # 0.2 | # # # # -4 | # # # # # # # #
+------------- 0 +-#-#-#-#-#-# -5 +-#-#-#-#-#-#-#-#-#-#
0 2 4 6 0 2 4 6 0 2 4 6
Token index Token index Token index

[!visual-conversion] Figure 5.14 — Comparing logits, softmax probabilities, and log probabilities for a simple example (printed p. 158, scan page-170.png). The log probabilities preserve the ordering of the probabilities. Values are exact: the logits are torch.linspace(-2, 2, steps=7) from the listing above the figure, and the probability and log-probability rows are the tensors printed in the surrounding text. A larger logit corresponds to a larger probability and a less negative log probability; smaller logits produce smaller probabilities and more negative log probabilities.

In practical terms, higher probabilities are better because they indicate the model assigns more confidence to a token. For log probabilities, values closer to zero are better, since zero corresponds to a probability of one, while very negative values correspond to extremely small probabilities. This makes it easy to compare tokens: the least negative log probability is the most likely one, and the most negative log probability is the least likely.

While figure 5.14 illustrates the relationship between logits, probabilities, and log probabilities for a simple example, we can apply it to the probability values from the earlier “The capital of Germany is” prompt, as shown in figure 5.15.

graph BT
    A["1 - Convert input text into token IDs and pass them to the LLM<br/>'The capital of Germany is' → 785, 6722, 315, 9856, 374"] --> B["LLM"]
    B --> C["2 - Get scores for the next token (logits)<br/>Berlin (19846) high · Bridge (19874) low"]
    C --> D["torch.softmax() → probabilities<br/>Berlin: largest probability value"]
    D --> E["torch.log() → log probabilities<br/>Berlin: −1.7812 · Bridge: −15.0"]

[!visual-conversion] Figure 5.15 — How logits are converted to probabilities and log probabilities for next-token scoring (printed p. 159, scan page-171.png). The correct next token ("Berlin") receives a high logit, which becomes a high probability and a less negative log probability, while unlikely candidates like "Bridge" map to very small probabilities and large negative log probabilities. Print annotations: “Note that these logit values can be positive or negative”, “This largest probability value corresponds to the largest logit value”, and “This largest logprob value corresponds to the largest probability value”. The two exact values marked on the log-probability plot are −1.7812 (Berlin) and −15.0 (Bridge); the remaining per-token bar heights are not recoverable at scan resolution.

We use probabilities instead of logits because probabilities are normalized and easier to interpret as confidence values. Earlier, we also noted that log probabilities offer an additional benefit, since they allow more numerically stable calculations than working with raw probabilities.

The numerical stability comes from the fact that even very small probability scores map to log probabilities in a reasonable numeric range. Another reason is that multiplying many probabilities quickly drives the result toward zero, while taking the log turns this multiplication into addition, which avoids underflow and is much more stable for long sequences.

Figure 5.16 shows how the joint log probability (or sequence log likelihood) is computed for the two example texts we used earlier. When we computed the regular joint probability score, we saw that both sequences had values close to zero. Now, with the joint log probability, we can see that even changing just the final token (for example, “Berlin” versus “Bridge”) results in a noticeably different total log probability (-16.6250 versus -29.8750).

Text input to the LLMNext tokenLog-probability score
The capital—−9.6875
The capital ofof−0.7695
The capital of GermanyGermany−4.0938
The capital of Germany isis−0.3008
The capital of Germany is BerlinBerlin−1.7812
−9.6875+(−0.7695)+(−4.0938)+(−0.3008)+(−1.7812)=−16.6250-9.6875 + (-0.7695) + (-4.0938) + (-0.3008) + (-1.7812) = -16.6250

Compared with "Bridge" as the final token:

Text input to the LLMNext tokenLog-probability score
The capital—−9.6875
The capital ofof−0.7695
The capital of GermanyGermany−4.0938
The capital of Germany isis−0.3008
The capital of Germany is BridgeBridge−15.0
−9.6875+(−0.7695)+(−4.0938)+(−0.3008)+(−15.0)=−29.8750-9.6875 + (-0.7695) + (-4.0938) + (-0.3008) + (-15.0) = -29.8750

[!visual-conversion] Figure 5.16 — How token-level log probabilities accumulate to form sequence log probabilities (printed p. 160, scan page-172.png). Each row shows the log probability of the next token, given the preceding text. Summing these values results in the joint log probability of the full sequence. Print annotations: “In each row, the text left of the box is the input to the LLM”, “Log-probability score for ‘of’ given ‘The capital’ as input”, “Joint log probability of the sequence ‘The capital of Germany is Berlin’”, “Conditional log probability of ‘Berlin’ given ‘The capital of Germany is’”, and, on the right-hand column, “The only value that differs compared to the left side”.

Working with log probabilities

When we compute the joint probability of a sequence, we multiply many numbers between 0 and 1:

P(x1,x2,…,xT∣W)=∏t=1TP(xt∣x1:t−1,W)P(x_1, x_2, \dots, x_T|W) = \prod_{t=1}^T P(x_t|x_{1:t-1}, W)

We can write the expanded form as follows:

P(x1∣W)⋅P(x2∣x1,W)⋅P(x3∣x1:2,W)⋯P(xT∣x1:t−1,W)P(x_1|W) \cdot P(x_2|x_1, W) \cdot P(x_3|x_{1:2}, W) \cdots P(x_T|x_{1:t-1}, W)

These products quickly become extremely small, which is inconvenient and can cause numerical underflow. When numbers become too tiny, the computer may round them down to zero, and we lose useful information. To avoid this, we often work in log space. Taking the logarithm of the joint probability gives us this:

log⁡(P(x1,x2,…,xT∣W))=log⁡(∏t=1TP(xt∣x1:t−1∣W))\log(P(x_1, x_2, \dots, x_T|W)) = \log\left(\prod_{t=1}^T P(x_t|x_{1:t-1}|W)\right)

Using the fact that the logarithm of a product is the sum of the logarithms, this expands to

log⁡P(x1∣W)+log⁡P(x2∣x1,W)+log⁡P(x3∣x1:2,W)+⋯+log⁡P(xT∣x1:t−1,W)\log P(x_1|W) + \log P(x_2|x_1, W) + \log P(x_3|x_{1:2}, W) + \cdots + \log P(x_T|x_{1:t-1}, W)

In other words, the log probability of a sequence is just the sum of the log probabilities of its individual tokens. This is both numerically more stable and easier to work with. It also matches the values returned by torch.log_softmax, which provides the log probabilities directly.

Summing log probabilities is therefore the standard approach in machine learning and AI.

Implementing the token log probability function is straightforward because it requires only two small changes to the code in listing 5.6: changing torch.softmax to torch.log_softmax and changing torch.prod to torch.sum.

WARNING Using mismatched combinations, such as torch.softmax with torch.sum or torch.log_softmax with torch.prod, is technically possible but mathematically incorrect.

Listing 5.7 Calculating next-token log probabilities

@torch.inference_mode()
def calc_next_token_logprobas(model, tokenizer, prompt, device, show=True):
token_ids = torch.tensor(tokenizer.encode(prompt), device=device)
logits = model(token_ids.unsqueeze(0)).squeeze(0)
all_logprobas = torch.log_softmax(logits, dim=-1) # CODE-ANNOTATION: unlabeled # An arrow pointing to the right with the text "We now use log_softmax."
<!-- page: 174 (printed 162) -->
t_idx = torch.arange(0, token_ids.shape[0] - 1, device=device)
next_ids = token_ids[1:]
next_token_logprobas = all_logprobas[t_idx, next_ids]
sum_next_token_logprobas = torch.sum(next_token_logprobas) # We replace the product with a sum.
if show:
print("Next-token log-probabilities:", next_token_logprobas)
print("Joint log-probability:", sum_next_token_logprobas)
else:
return next_token_logprobas, sum_next_token_logprobas

Let’s now try the updated function on the example prompts from earlier:

calc_next_token_logprobas(
model, tokenizer, device=device,
prompt="The capital of Germany is Berlin"
)

The result is as follows:

Next-token log-probabilities: tensor([-9.6875, -0.7695, -4.0938, -0.3008, -1.7812], dtype=torch.bfloat16) Joint log-probability: tensor(-16.6250, dtype=torch.bfloat16)

Now let’s try the second sequence:

calc_next_token_logprobas(
model, tokenizer, device=device,
prompt="The capital of Germany is Bridge"
)

This returns the following:

Next-token log-probabilities: tensor([-9.6875, -0.7695, -4.0938, -0.3008, -15.0000], dtype=torch.bfloat16) Joint log-probability: tensor(-29.8750, dtype=torch.bfloat16)

As you can see, the difference between the “Berlin” and “Bridge” is now much more pronounced (-16.6250 and -29.8750), with “Berlin” scoring much higher (better).

5.6 Scoring model confidence with log probabilities

Section titled “5.6 Scoring model confidence with log probabilities”

The previous two sections explained the concepts of token probabilities and log probabilities in great detail. In this section, we’ll make slight modifications to the log-probability computation to develop a log-probability-based scorer function analogous to the heuristic scorer we developed at the beginning of this chapter (see figure 5.17).

The logprob scoring method we’ll develop is very similar to the procedure we covered in the previous section. We’ll make two main modifications. First, we’ll exclude the prompt from the score calculation and calculate the score only for the answer tokens.

graph LR
    R1["1 - Load pretrained LLM"] --> R2["2 - Rule-based score"]
    R2 --> R3["3 - Token probabilities"]
    R3 --> R4["4 - Token log probabilities"]
    R4 --> R5["5 - Logprob scoring"]
    R5 --> R6["6 - Self-refinement"]

[!visual-conversion] Figure 5.17 — This section implements a logprob scorer based on token log probabilities, which we’ll use in the self-refinement method later in this chapter (printed p. 163, scan page-175.png). Steps 1 to 4 are ticked and step 5 is highlighted. Print annotations: step 5 — “In this section, we prepare a scoring function to calculate the log-probability scores of the LLM answers”; steps 3 and 4 — “In the previous sections, we covered how to calculate the token probability and log-probability scores.” In this section, we prepare a scoring function to calculate the log-probability scores of the LLM answers.

In the previous sections, we covered how to calculate the token probability and log-probability scores.

Figure 5.17 This section implements a logprob scorer based on token log probabilities, which we’ll use in the self-refinement method later in this chapter.

Second, we’ll average (instead of sum) the token log probabilities so that it is fairer to compare two sequences of different lengths. The updated calculation with these two modifications is shown in figure 5.18.

For illustration, let’s implement the two modifications shown in figure 5.18 using the calc_next_token_logprobas function from listing 5.7. For example, suppose we have the following prompt and answer:

example_prompt = "What is the capital of Germany?" example_answer = " The capital of Germany is Berlin."
next_token_logprobas, sum_next_token_logprobas = calc_next_token_logprobas(
model, tokenizer, device=device,
prompt=example_prompt+example_answer,
show=False
)
print("Next-token logprobas:", next_token_logprobas)
print("Joint log-probability:", sum_next_token_logprobas)

This prints the following output. (Note that the tensor contains scores for the prompt token as well, which is why the numbers appear different from figure 5.18. This will become clearer as you read on.)

Next-token logprobas: tensor([-0.4512, -0.3418, -8.3125, -0.3906, -3.8125, -3.0469, -1.1719, 0.0000, -0.0155, 0.0000, -0.0078, -0.0752, -0.1582], dtype=torch.bfloat16) Joint log-probability: tensor(-17.7500, dtype=torch.bfloat16)

Prompt: What is the capital of Germany? Response: The → -1.1719

Text input to the LLMScored tokenLog probabilityCounted?
What is the capital of Germany?The−1.1719prompt token — excluded
What is the capital of Germany? Thecapital0.0000yes
What is the capital of Germany? The capitalof−0.0155yes
What is the capital of Germany? The capital ofGermany0.0000yes
What is the capital of Germany? The capital of Germanyis−0.0078yes
What is the capital of Germany? The capital of Germany isBerlin−0.0752yes
What is the capital of Germany? The capital of Germany is Berlin.−0.1582yes
−1.1719+0.0000+(−0.0155)+0.0000+(−0.0078)+(−0.0752)+(−0.1582)7=−0.2041\frac{-1.1719 + 0.0000 + (-0.0155) + 0.0000 + (-0.0078) + (-0.0752) + (-0.1582)}{7} = -0.2041

[!visual-conversion] Figure 5.18 — The modified logprob scoring procedure (printed p. 164, scan page-176.png). The prompt tokens are excluded from the calculation, and only the log probabilities of the answer tokens are collected. These values are then averaged to obtain a length-normalized score, allowing us to compare answers of different lengths fairly. Print annotations: “Include the prompt to calculate the log probability for the next token”, “Average log probability of the sequence ‘The capital of Germany is Berlin.’”, and “Divide by the number of values to calculate the average log probability (also known as the ‘per-token log-likelihood’).” The placeholder for this figure survived OCR only as an unlabeled comment and has been relabelled here. Include the prompt to calculate the log probability for the next token.

What is the capital of Germany? The capital → 0.0000

What is the capital of Germany? The capital of → -0.0155

What is the capital of Germany? The capital of Germany → 0.0000

What is the capital of Germany? The capital of Germany is → -0.0078

What is the capital of Germany? The capital of Germany is Berlin → -0.0752

What is the capital of Germany? The capital of Germany is Berlin. → -0.1582

(-1.1719 + 0.0000 + -0.01550 + 0.0000 + -0.0078 + -0.0752 + -0.1582) / 7 = -0.2041 Divide by the number of values to calculate the average log probability (also known as the “per-token log-likelihood”).

Figure 5.18 The modified logprob scoring procedure. The prompt tokens are excluded from the calculation, and only the log probabilities of the answer tokens are collected. These values are then averaged to obtain a length-normalized score, allowing us to compare answers of different lengths fairly.

We can then calculate the number of answer tokens with the following code, which yields 7:

print(len(tokenizer.encode(example_answer)))

Then, to calculate the average log probability over the answer tokens, as shown in figure 5.18, we need to average over those seven answer tokens:

last_7 = next_token_logprobas[-7:]
print(last_7)
print(torch.mean(last_7))

This prints:

tensor([-1.1719, 0.0000, -0.0155, 0.0000, -0.0078, -0.0752, -0.1582],
dtype=torch.bfloat16)
tensor(-0.2041, dtype=torch.bfloat16)

We can see that the resulting average, -0.2041, is similar to what’s shown in figure 5.18.

We can combine the calc_next_token_logprobas code with this calculation into a new function, avg_logprob_answer.

Listing 5.8 Average log-probability scoring for answer tokens

@torch.inference_mode()
def avg_logprob_answer(model, tokenizer, prompt, answer, device="cpu"):
prompt_ids = tokenizer.encode(prompt)
answer_ids = tokenizer.encode(answer)
full_ids = torch.tensor(prompt_ids + answer_ids, device=device)
logits = model(full_ids.unsqueeze(0)).squeeze(0)
logprobs = torch.log_softmax(logits, dim=-1) # Same as in calc_next_token_logprobas before
start = len(prompt_ids) - 1 # Index range for positions corresponding to answer tokens
end = full_ids.shape[0] - 1
t_idx = torch.arange(start, end, device=device)
next_tokens = full_ids[start + 1 : end + 1]
next_token_logps = logprobs[t_idx, next_tokens] # Same as before, except for using start and end
return torch.mean(next_token_logps) # Average over the answer token scores.

The avg_logprob_answer function is similar to the calc_next_token_logprobas function in listing 5.7, except that we calculate logprobs only for the answer tokens rather than for the whole sequence, including the prompt, and we average the calculated logprob values instead of summing them.

Let’s apply this new function to the prompt and answer from earlier in this section:

score_1 = avg_logprob_answer(
model, tokenizer,
prompt="What is the capital of Germany?",
answer=" The capital of Germany is Berlin.",
device=device
)
print(score_1)

This returns -0.2041, as before, which indicates that we implemented the function correctly. We can now also apply this function to the nonsensical “Bridge” answer:

score_2 = avg_logprob_answer(
model, tokenizer,
prompt="What is the capital of Germany?",
answer="The capital of Germany is Bridge.",
device=device
)
print(score_2)

The resulting score here is -3.8906, which is much lower than the “Berlin” score, as expected.

With the average logprob scoring function now in place, we could also calculate the scores for the MATH-500 prompt (prompt_cot) we defined at the beginning of this chapter and the responses we stored as response_1 and response_2. I’ll leave that to you as an exercise.

We’ve spent a lot of time in this chapter going through the concepts of next-token probability and log-probability scoring. One reason for doing so is that we can use these as scorers in the upcoming section on self-refinement. A second reason is that the concept of log probabilities will also be relevant when we implement the reinforcement learning with verifiable rewards training in the next chapter.

At the same time, it is important not to assume logprob scoring can be a universal fix. Because it measures what the model itself strongly prefers, logprob scoring can still favor confident mistakes over correct but less strongly preferred answers. In practice, logprob scoring is best viewed as one useful scoring signal among several, not as a guaranteed tiebreaker.

Exercise 5.3: Using the logprob scorer as a tiebreaker in self-consistency Using the logprob scorer instead of the heuristic scorer in exercise 5.1, extend the self-consistency implementation (self_consistency_vote) from the previous chapter (listing 4.17) so it can handle ties among candidate answers. Then run the two implementations on a subset of the MATH-500 dataset to see which tiebreaking method performs better.

Exercise 5.4: Using the logprob scorer in a best-of-N setup Extend the self-consistency implementation so that the final answer is chosen using the logprob scorer (avg_logprob_answer) rather than the heuristic scorer or majority voting, as in exercise 5.2. Then run the different implementations on a subset of the MATH-500 dataset to see which tiebreaking method performs better.

Tip: You don’t need to modify the self_consistency_vote function itself to apply the tiebreaking. You can apply tiebreaking to the results dictionary returned by self_consistency_vote, which is used inside the evaluate_math500_stream function from listing 3.15.

5.7 Self-refinement through iterative feedback

Section titled “5.7 Self-refinement through iterative feedback”

Having introduced several methods for scoring LLM answers, let’s now get to the core inference-scaling technique of this chapter, self-refinement (figure 5.19). We’ll first introduce self-refinement and walk through the process manually. In the next section, as shown in figure 5.19, we’ll automate the self-refinement loop and add support for the scoring methods developed earlier in the chapter (the heuristic scorer and the average logprob scorer).

graph LR
    R1["1 - Load pretrained LLM"] --> R2["2 - Rule-based score"]
    R2 --> R3["3 - Token probabilities"]
    R3 --> R4["4 - Token log probabilities"]
    R4 --> R5["5 - Logprob scoring"]
    R5 --> R6["6 - Self-refinement"]

[!visual-conversion] Figure 5.19 — The final step in our workflow, where the logprob scorer we developed earlier is used in the self-refinement method (printed p. 167, scan page-179.png). Steps 1 to 5 are ticked and step 6 is highlighted, annotated “We’ll now code the self-refinement method, which will make use of the logprob scorer we developed previously.”

Self-refinement is a technique in which the LLM analyzes and refines its own answers. As shown in figure 5.20, the LLM starts with an initial answer to the prompt, as in regular LLM usage. Then it critiques the answer and refines it.

The self-refinement procedure in figure 5.20 may look complicated at first, but it’s essentially just a sequential application of the text generation function to different prompts and inputs. Let’s walk through it step by step with a code example.

NOTE In this example, we won’t use chain-of-thought prompting. In practice, though, you can combine self-refinement with chain-of-thought prompting when working with a base model.

We’ll start with the base prompt and the answer (steps 1 and 2 in figure 5.20), based on the code from section 5.2.

Similar to using a regular LLM, we feed a prompt to the LLM, which responds with an answer.

graph TD
    P["1 - Prompt<br/>'Half the value of 3x−9 is x+37.<br/>What is the value of x?'"] --> L1["LLM"]
    L1 --> A["2 - Initial answer<br/>\boxed{24}"]
    A --> CP["3 - Critique prompt<br/>Question: raw_prompt<br/>Draft answer: (draft)<br/>Write a short critique and bullet-point fix plan (under ~120 words)."]
    CP --> L2["LLM"]
    L2 --> C["4 - Critique<br/>'The question seems to be asking for the value of x ...<br/>However, the question itself is incomplete ...<br/>Fix plan: ...'"]
    C --> RP["5 - Refine prompt<br/>Revise the answer using the critique.<br/>End with a final boxed result: \boxed{ANSWER}"]
    RP --> L3["LLM"]
    L3 --> R["6 - Revised answer<br/>\boxed{83}"]

[!visual-conversion] Figure 5.20 — The self-refinement process (printed p. 168, scan page-180.png). The LLM first produces an initial answer to the prompt, and then receives a critique prompt that asks it to analyze its own response and produce a short critique with a plan to refine the answer. In the final step, the model is given a refine prompt that contains the original question, its draft answer, and the critique, and it generates a revised answer that incorporates the suggested improvements. Print annotations: “Similar to using a regular LLM, we feed a prompt to the LLM, which responds with an answer”, “Next, we have the LLM write a critique of its previous answer”, and “Using the critique, the LLM refines its own answer.”

Listing 5.9 Base prompt and answer

raw_prompt = {
"Half the value of $3x-9$ is $x+27$.",
"What is the value of $x$?"
}
prompt = render_prompt(raw_prompt)
torch.manual_seed(123)
<!-- page: 181 (printed 169) -->
initial_response = generate_text_stream_concat_Flex(
model, tokenizer, prompt, device,
max_new_tokens=2048, verbose=True,
generate_func=generate_text_top_p_stream_cache,
temperature=0.7,
top_p=0.9,
)

The LLM responds with ” \boxed{18} ”, which is incorrect (the correct answer is 83).

Next, we have the LLM critique the answer. To do this, we write a critique prompt that includes the original question (raw_prompt) and the answer (draft), as shown in steps 3 and 4 in figure 5.20.

Listing 5.10 Critique prompt and refinement plan

def make_critique_prompt(raw_prompt, draft):
return (
"You are a meticulous reviewer. Identify logical errors, missing "
"steps, or arithmetic mistakes. If the answer seems correct, "
"say so briefly. Then propose a concise plan to fix issues.\n\n"
f"Question:\n{raw_prompt}\n\n"
f"Draft answer:\n{draft}\n\n"
"Write a short critique and bullet-point fix plan "
"(under ~120 words).\n"
"Critique:"
)
critique_prompt = make_critique_prompt(raw_prompt, initial_response)
torch.manual_seed(123)
critique = generate_text_stream_concat_Flex(
model, tokenizer, critique_prompt, device,
max_new_tokens=2048, verbose=True,
generate_func=generate_text_top_p_stream_cache,
temperature=0.7,
top_p=0.9,
)

The preceding critique prompt lets the LLM write an elaborate critique that even contains the correct answer itself:

The question seems to have a logical error in its setup. The statement “Half the value of 3x−93x-9 is x+37x+37” is incorrect because half of 3x−93x- 9 should be 12(3x−9)\frac{1}{2}(3x-9), not 3x−93x-9. The equation should be 12(3x−9)=x+37\frac{1}{2}(3x-9) = x + 37.

Fix Plan: 1. Correct the equation to 12(3x−9)=x+37\frac{1}{2}(3x-9) = x + 37. 2. Multiply both sides by 2 to eliminate the fraction: 3x−9=2(x+37)3x - 9 = 2(x + 37). 3. Distribute the 2 on the right side: 3x−9=2x+743x - 9 = 2x + 74. 4. Subtract 2x2x from both sides: x−9=74x - 9 = 74. 5. Add 9 to both sides: x=83x = 83.

Note that the critique can contain factual errors. For instance, it says “The question itself is incomplete”, which is not true, yet it still proceeds with a correct plan for a fix. This is important because, in self-refinement, a critique can be useful even if parts of it are wrong, as long as it pushes the model toward a better revision overall.

Finally, we use this refinement prompt to revise the original answer (steps 5 and 6 in figure 5.20).

Listing 5.11 Answer refinement

def make_refine_prompt(raw_prompt, draft, critique):
return (
"Revise the answer using the critique. Keep it concise and "
"end with a final boxed result: \\boxed{ANSWER}\n\n"
f"Question:\n{raw_prompt}\n\n"
f"Previous answer:\n{draft}\n\n"
f"Critique:\n{critique}\n\n"
"Revised answer:"
)
refine_prompt = make_refine_prompt(raw_prompt, initial_response, critique)
torch.manual_seed(123)
revised_answer = generate_text_stream_concat_flex(
model, tokenizer, refine_prompt, device,
max_new_tokens=2048, verbose=True,
generate_func=generate_text_top_p_stream_cache,
temperature=0.7,
top_p=0.9,
)

While the base model is not the best instruction follower, the refinement prompt gets the LLM to generate the correct answer:

\boxed{83}
Final result: The value of $x$ is \boxed{83}.

This example illustrates a single refinement loop. In practice, it’s common to repeat this loop for multiple iterations. Next, we’ll code a function to automate this process.

We’ll now package the previous section’s manual self-refinement steps into a convenient function, simplifying the use of self-refinement and allowing the process to be repeated for a fixed number of iterations.

In addition, the function will support plugging in the scoring methods we developed earlier in the chapter (heuristic scoring and logprob scoring) to compute a score for each answer (figure 5.21). This score can then be used to decide whether a refined answer should be accepted.

graph TD
    P["1 - Prompt<br/>'Half the value of 3x−9 is x+37.<br/>What is the value of x?'"] --> L1["LLM"]
    L1 --> A["2 - Initial answer<br/>\boxed{24}"]
    A --> S1["Scorer → −1.258"]
    A --> CP["3 - Critique prompt<br/>Question: raw_prompt<br/>Draft answer: (draft)<br/>Write a short critique and bullet-point fix plan (under ~120 words)."]
    CP --> L2["LLM"]
    L2 --> C["4 - Critique<br/>'The question seems to be asking for the value of ...<br/>However, the question itself is incomplete ...<br/>Fix plan: ...'"]
    C --> RP["5 - Refine prompt<br/>Revise the answer using the critique.<br/>End with a final boxed result: \boxed{ANSWER}"]
    RP --> L3["LLM"]
    L3 --> R["6 - Revised answer<br/>\boxed{83}"]
    R --> S2["Scorer → −0.377"]
    S1 --> D{"Accept revision only if<br/>its score beats the previous"}
    S2 --> D

[!visual-conversion] Figure 5.21 — The self-refinement loop with optional scoring (printed p. 171, scan page-183.png). The model produces an initial answer, then critiques it, and generates a revised answer based on the critique. Both answers can be evaluated with scoring functions (such as logprob scoring), and the revised answer is only accepted if its score improves on the previous one. Print annotations: “We score the LLM’s answer” and “We also score the revised answer and only accept it if its score is better than the previous score.” In the worked example the revised answer scores −0.377 against the initial answer’s −1.258.

In figure 5.21, the revised answer receives a higher logprob score (-0.377) than the initial answer (-1.258), which makes it reasonable to accept the revision. In practice, self-refinement can also produce worse answers, especially when it’s run for multiple iterations. The scorer therefore provides a way to decide whether a revised answer represents an improvement.

NOTE Scoring does not always improve the results. Whether you should use a scorer in self-refinement, and which one you should use, depends on the LLM. You can determine this by experimenting on a benchmark dataset like MATH-500.

The complete code, which combines the steps from the previous section and adds an iterations parameter and a scoring function (score_fn) option, is shown in the following listing.

Listing 5.12 Self-refinement with multiple iterations and scoring support

def self_refinement_loop(
model,
tokenizer,
raw_prompt,
device,
iterations=2,
max_response_tokens=2048,
max_critique_tokens=256,
score_fn=None,
prompt_renderer=render_prompt,
prompt_suffix="",
verbose=False,
temperature=0.7,
top_p=0.9,
):
steps = []
prompt = prompt_renderer(raw_prompt) + prompt_suffix # Initial response (draft)
current_full = generate_text_stream_concat_flex(
model=model,
tokenizer=tokenizer,
prompt=prompt,
device=device,
max_new_tokens=max_response_tokens,
verbose=False,
generate_func=generate_text_top_p_stream_cache,
temperature=temperature,
top_p=top_p,
)
current_extracted = extract_final_candidate(
current_full, fallback="number_then_full"
)
if score_fn:
current_score = score_fn(answer=current_full, prompt=prompt)
else:
current_score = 0.0
for it in range(iterations): # Run for one or more iterations.
draft_before_full = current_full
draft_before_extracted = current_extracted
score_before = current_score
critique_prompt = make_critique_prompt( # Critique the response. raw_prompt, draft_before_full
)
critique_full = generate_text_stream_concat_flex(
model=model,
tokenizer=tokenizer,
prompt=critique_prompt,
device=device,
max_new_tokens=max_critique_tokens,
verbose=False,
generate_func=generate_text_top_p_stream_cache,
temperature=temperature,
top_p=top_p,
)
refine_prompt = make_refine_prompt(
raw_prompt, draft_before_full, critique_full
)
revised_full = generate_text_stream_concat_flex(
model=model,
tokenizer=tokenizer,
prompt=refine_prompt,
device=device,
max_new_tokens=max_response_tokens,
verbose=False,
generate_func=generate_text_top_p_stream_cache,
temperature=temperature,
top_p=top_p,
)
revised_extracted = extract_final_candidate(
revised_full, fallback="number_then_full"
)
if score_fn:
revised_score = score_fn(
answer=revised_full, prompt=prompt
)
else:
revised_score = 0.0
step = {
"iteration": it + 1,
"draft_full": draft_before_full,
"draft_extracted": draft_before_extracted,
"critique": critique_full,
"revised_full": revised_full,
"revised_extracted": revised_extracted,
"score_before": score_before,
"score_after": revised_score,
}
steps.append(step)
if verbose:
print(
f"[Refinement {it+1}/{iterations}]"
f"\nCurrent: {draft_before_extracted}"
f"\nRevised: {revised_extracted}"
f"\nScore before: {score_before:.3f}"
f"\nScore after: {revised_score:.3f}"
f"\n{'=' * 25}\n"
)
<!-- page: 186 (printed 174) -->
if revised_score >= current_score:
current_full = revised_full
current_extracted = revised_extracted
current_score = revised_score
return {
"final_full": current_full,
"final_extracted": current_extracted,
"steps": steps,
}

The self_refinement_loop function runs the self-refinement procedure from the previous section for one or more iterations (for it in range(iterations)). At the end of each iteration, it compares the revised score to the current score (revised_score >= current_score) and keeps the revised answer only if its score is equal or higher.

Using a scoring function is optional. When score_fn=None (the default), the score is always set to 0.0. Since 0.0 >= 0.0 evaluates to True, the most recent answer is always accepted when running multiple refinement iterations.

Then we run the self-refinement loop using the average logprob scorer, avg_logprob_answer. This function, shown in listing 5.8, takes several arguments (model, tokenizer, prompt, answer, and device). As you can see in the previous listing, the scoring function is called with only two arguments:

…

if score_fn:
revised_score = score_fn(
answer=revised_full, prompt=prompt
)

To make avg_logprob_answer compatible with this score_fn call, we can use the partial function from Python’s built-in functools module to prespecify the remaining arguments.

Listing 5.13 Creating an average log-probability scorer

from functools import partial
avg_logprob_score = partial(
avg_logprob_answer,
model=model,
tokenizer=tokenizer,
device=device
)

Now we can use the avg_logprob_score function in the self-refinement loop:

torch.manual_seed(1) results_logprob = self_refinement_loop(

model=model, tokenizer=tokenizer, raw_prompt=raw_prompt, device=device, iterations=2, max_response_tokens=2048, max_critique_tokens=256, score_fn=avg_logprob_score, verbose=True, temperature=0.7, top_p=0.9, )

The output is shown here:

[Refinement 1/2] Current: 10 Revised: 83 Score before: -0.855 Score after: -0.226

Section titled “[Refinement 1/2] Current: 10 Revised: 83 Score before: -0.855 Score after: -0.226”

[Refinement 2/2] Current: 83 Revised: 83 Score before: -0.226 Score after: -1.320

Section titled “[Refinement 2/2] Current: 83 Revised: 83 Score before: -0.226 Score after: -1.320”

Looking at the preceding results, we can see that the model corrected the initially incorrect answer (from 10 to 83) in the first iteration, and the score improved from -0.855 to -0.226. In the second iteration, the score gets worse, but that’s okay since we already have the correct answer.

We can also access the final answer extracted from the best-scoring response, typically from its boxed content when present, via results_logprob[“final_extracted”], which in this case returns 83. If you are interested in the full answer, use results_logprob[“final_full”]. To read through the critiques and longer answers, you can print the results_logprob dictionary, which contains the detailed results for all iterations.

Exercise 5.5: Using the heuristic score for self-refinement

Run self_refinement_loop using the heuristic_score function, which we defined in listing 5.3.

The previous example showed that self-refinement can help the model generate the correct answer. To get a better idea of how useful this self-refinement method really is, I ran it on MATH-500 and summarized the results in table 5.1.

Table 5.1 MATH-500 task accuracy for different self-refinement methods

MethodScoringIterationsModelAccuracyTime
1Baseline (chapter 3)--Base15.2%10.1 min
2Self-refinementNone1Base25.0%84.8 min
3Self-refinementNone2Base22.0%165.4 min
4Self-refinementHeuristic1Base21.6%84.7 min
5Self-refinementHeuristic2Base20.8%151.4 min
6Self-refinementAvg. logprob1Base21.4%85.3 min
7Self-refinementAvg. logprob2Base22.0%165.3 min
8Baseline (chapter 3)--Reasoning48.2%182.1 min
9Self-refinementNone1Reasoning56.6%498.8 min
10Self-refinementHeuristic1Reasoning57.8%498.6 min
11Self-refinementAvg. logprob1Reasoning48.4%499.7 min

The accuracy values shown in table 5.1 were computed on all 500 samples in the MATH-500 test set using a “cuda” GPU (DGX Spark).

As shown in table 5.1, self-refinement improves performance over the base model (rows 1–7), but the improvement is very moderate, with the best accuracy achieved when no scoring is used in self-refinement. This means that both the heuristic score and the average logprob score can sometimes lead to incorrect answers being accepted over the initial correct answer.

Note that when adding “Explain step by step.” chain-of-thought to both the base model and the self-refinement, the model failed to improve over the base model (results not shown).

Looking at the reasoning model results (rows 8–11), we can see that the combination of self-refinement and heuristic scoring improved answer accuracy by almost 10%. (As explained in chapter 3, the reasoning model can be used by changing which_model=“base” to which_model=“reasoning” in load_model_and_tokenizer in listing 5.1.)

In both cases, it seems that average logprob scoring results in worse performance than no scorer or the heuristic scorer. This is likely because the average logprob score is more closely related to how natural or expected an answer looks under the model than to whether the answer is actually correct. As a result, it can favor answers that are fluent, familiar, or syntactically clean, even when they are semantically wrong. In other words, the logprob criterion can unintentionally select confident mistakes, whereas the heuristic score is more focused on the format and structure of the answer.

At this point, it may seem that we’ve spent a lot of time discussing the concept of average logprob scoring. Logprob scoring is a fundamental concept when working with LLMs, and it will come in handy in upcoming chapters, when we implement the reinforcement learning training procedure.

Comparing the results in table 5.1 with those in the previous chapter (table 4.1), we also observe that self-refinement is less effective than self-consistency for this model on this math task. Self-consistency remains widely used because it works well in practice, despite its simplicity.

Another method we haven’t explored in this chapter is self-refinement with an external model in an LLM-as-a-judge setup, similar to what’s described in appendix F (section F.5). For instance, instead of using the heuristic score or average logprob, we can use a second LLM to compute a score and write the critique.

In November 2025, with DeepSeekMath-V2, the DeepSeek team demonstrated that self-refinement with a second LLM can be very successful, leading to gold-level performance in several math competitions. Specifically, the team proposed a new method in which they trained a second LLM to be a strong critique model and further trained their base model to become a better math problem solver in the context of self-refinement (by contrast, in this chapter, we applied self-refinement without any additional training).

This concludes our discussion of inference scaling without additional training (see figure 5.22). In the next chapter, we’ll begin covering training techniques that update the model weights to improve reasoning.

graph LR
    R1["1 - Load pretrained LLM"] --> R2["2 - Rule-based score"]
    R2 --> R3["3 - Token probabilities"]
    R3 --> R4["4 - Token log probabilities"]
    R4 --> R5["5 - Logprob scoring"]
    R5 --> R6["6 - Self-refinement"]

[!visual-conversion] Figure 5.22 — Overview of the book’s progression from basic LLM use to inference-time reasoning methods (printed p. 177, scan page-189.png). All six steps are complete: we loaded the pretrained LLM, built a rule-based scorer, worked through token probabilities and log probabilities, implemented a logprob scorer, and used it inside the self-refinement loop. This closes the inference-time half of the book; the chapters that follow turn to training-time methods. The next chapter covers techniques that train and update the model to improve reasoning performance.

Stage 1: LLM basics (chapter 2) 1 Conventional LLM Loading pretrained weights Text generation

Stage 2: Measuring performance (chapter 3) 2 Evaluation Benchmark-based evaluation Judgment-based evaluation

Stage 3: Reasoning without training (chapters 4 and 5) 3 Inference techniques Advanced text generation and voting Self-refinement

Stage 4: Reasoning with training (chapters 6 to 8) 4 Training techniques Reinforcement learning Distillation

In this and the previous chapter, we covered two popular inference-scaling techniques to improve answer accuracy and reasoning performance.

Figure 5.22 Overview of the book’s progression from basic LLM use to inference-time reasoning methods and finally to training-based techniques. This chapter concludes our discussion of inference-scaling methods that don’t require additional training. The next chapters introduce approaches that update model weights to further improve reasoning performance.

Summary

  • Self-refinement extends the inference-time scaling ideas from the previous chapter by iteratively critiquing and improving a single answer, rather than relying on multiple independent samples as in self-consistency.
  • A simple rule-based scoring function ranks model outputs by rewarding extractable final answers and shorter, more economical completions.
  • Next-token scoring quantifies model confidence by converting logits into normalized probabilities and combining these into a sequence-level likelihood.
  • Log probabilities replace raw probabilities to avoid numerical underflow and to turn products over many tokens into stable sums and averages.
  • These scoring functions are useful beyond self-refinement, such as for breaking ties in self-consistency or implementing best-of-N selection strategies.
  • The self-refinement procedure consists of three stages: generating an initial draft, producing a short critique and fix plan, and generating a revised answer.
  • A reusable refinement function automates the self-refinement workflow across multiple iterations (refinement rounds), and it can use score-based acceptance to keep only revisions that do not degrade the computed answer’s score using one of the scoring functions we developed earlier.