Skip to content
ImagineWorld

Evaluating reasoning models

node_idnode-book_build-a-reasoning-model_chapter-03-evaluating-reasoning-models
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num3
chapter_titleEvaluating reasoning models
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Evaluating reasoning models

This chapter covers

  • Extracting final answers reliably from an LLM response
  • Verifying answer correctness by comparing an LLM’s output to the reference solution using a symbolic math solver
  • Running a full evaluation pipeline that loads a pretrained model, generates outputs, and grades them against a dataset

Evaluation is what lets us distinguish between LLMs that merely sound convincing and those that can solve problems correctly. LLM evaluation techniques span a broad range of approaches, from measuring task accuracy to making sure that LLMs adhere to specific safety standards. In this chapter, “evaluate” means quantitatively testing a model on many examples and scoring its outputs against reference answers.

More specifically, we’ll focus on implementing a verification-based method that checks whether an LLM can solve math problems accurately by comparing its answers against reference solutions using a calculator-like implementation.

This verifier is particularly useful because it not only evaluates performance on math tasks but also introduces the principle of verifiable rewards, the foundation of the reinforcement learning approach to reasoning models that we’ll implement in chapter 6.

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 3.1 — A model of the topics covered in this book (printed p. 58, scan page-070.png). This chapter covers evaluation methods (stage 2), with a special focus on implementing verifiers, which we’ll reuse as the basis for verifiable rewards in chapter 6. In the print, stage 1 is annotated “These LLM basics were covered in the previous chapter” and stage 2 “This chapter focuses on model evaluation”. The “Benchmark-based evaluation” and “Judgment-based evaluation” substeps fan out into four leaf methods, with Verifiers marked “This chapter covers a benchmark-based evaluation method: verifiers”:

graph TD
    B1["Benchmark-based evaluation"] --> M1["Multiple choice"]
    B1 --> M2["Verifiers"]
    B2["Judgment-based evaluation"] --> M3["Leaderboards"]
    B2 --> M4["LLM judges"]

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).

There are four common ways to evaluate trained LLMs in practice: multiple choice, verifiers, leaderboards, and LLM judges. These methods are widely used across research papers, technical reports, marketing materials, and model cards (documents that summarize how a model was trained, evaluated, and intended to be used), and results often draw from more than one category.

As figure 3.1 illustrates, these evaluation approaches can be grouped into two broader types: benchmark-based evaluation and judgment-based evaluation. The former is usually more quantitative, whereas the latter relies more on qualitative judgments. All four evaluation methods are useful in different contexts, but verifiers are especially relevant for reasoning models.

Math problems provide a natural example: depending on the problem’s complexity, they benefit from step-by-step reasoning, yet evaluation is straightforward because the final answer can be checked against the correct answer. In this setting, the verifier provides a simple and reliable way to measure whether a model’s reasoning steps lead to the correct outcome.

In this chapter, we’ll focus on verifiers as a benchmark-based approach for measuring answer correctness in math problems. Verifiers compare the extracted answer with the reference solution, as shown in figure 3.2, often by relying on external tools such as code interpreters or calculator programs.

NOTE Appendix F covers other evaluation methods, such as multiple-choice benchmarks, preference-based leaderboards, and LLM-as-a-judge approaches.

graph LR
    subgraph IN ["Question-answer pair from a benchmark dataset"]
        direction TB
        Q["Input:<br/>If a + b = 3 and ab = 13/6,<br/>what is the value of a² + b²?"]
        R["Reference answer:<br/>14/3"]
    end
    Q --> L["LLM"]
    L --> O["Output:<br/>We use the identity<br/>a² + b² = (a + b)² − 2ab<br/>...<br/>Final Answer: ⌊14/3⌋"]
    O --> E["Extracted answer:<br/>14/3"]
    R --> V{"Verify answer"}
    E --> V

[!visual-conversion] Figure 3.2 — Evaluating an LLM with a verification-based method in free-form question answering (printed p. 59, scan page-071.png). The model generates a free-form answer (which may include multiple steps) and a final boxed answer, which is extracted and compared with the correct answer from the dataset. Print annotations: “The correct answer provided in the dataset” on the reference answer and “The extracted answer” on the boxed result.

While our immediate focus is evaluation, verifiers will reappear later in this book. They serve not only as a way to measure performance but also as the feedback signal used in reinforcement learning methods to train reasoning models, which we’ll explore in chapter 6.

The downside is that verifier methods can be applied only to domains that can be easily (and, ideally, deterministically) verified, such as math and code. Also, this approach can introduce additional complexity and dependencies, and it may shift part of the evaluation burden from the model itself to the external tool.

Because math problem solving can be generated in unlimited variations programmatically and because it benefits from step-by-step reasoning, this task has become a cornerstone of evaluating and developing reasoning models. In this chapter, we’ll build a math verifier step by step, following the eight steps shown in figure 3.3.

graph TD
    S1["1 - Load pretrained LLM"] --> S2["2 - Ask LLM to generate answer"]
    S2 --> S3["3 - Extract final answer box"]
    S3 --> S4["4 - Normalize extracted answer"]
    S4 --> S5["5 - Verify equivalence"]
    S5 --> S6["6 - Grade answers"]
    S6 --> S7["7 - Load MATH-500 dataset"]
    S7 --> S8["8 - Evaluate the model"]

[!visual-conversion] Figure 3.3 — A step-by-step workflow for building and applying a math verifier (printed p. 60, scan page-072.png). Starting with a pretrained LLM, we’ll generate answers, extract and normalize them, and then compare them with the ground-truth solutions. The verified answers are then graded, and the process is repeated across a dataset (MATH-500) to evaluate overall model performance. The print shows the worked example alongside the steps: the LLM output box (“We use the identity a² + b² = (a + b)² − 2ab … Final Answer: ⌊14/3⌋”, annotated “Answer generated by the LLM”), the normalized form (14)/(3) compared against the ground truth 14/3 (“Are equal?” → True, annotated “‘Ground truth’ is the correct answer provided in the dataset”), and a callout on step 8: “Apply steps 2–6 to multiple examples from a larger dataset (MATH-500).”

The next section will go through steps 1 and 2 in figure 3.3: loading a pretrained LLM and setting it up to generate answers.

3.2 Loading a pretrained model to generate text

In this section, we begin implementing the verifier by loading the pretrained LLM introduced in the previous chapter and configuring it to generate answers. This will lay the foundation for the later steps in figure 3.3, where we’ll extract, normalize, and verify those answers. It will also set up a reusable model-loading path for later chapters, where we’ll compare different reasoning methods and need a consistent way to measure whether they actually improve the model.

We will use the same pretrained base model that we used in chapter 2. For convenience and reuse in future chapters, we’ll wrap the model-loading logic in a load_model_and_tokenizer function call, as shown in the following listing.

Listing 3.1 Loading a pretrained model

from pathlib import Path
import torch
from reasoning_from_scratch.ch02 import (
get_device
)
from reasoning_from_scratch.qwen3 import (
download_qwen3_small,
Qwen3Tokenizer,
Qwen3Model,
QWEN_CONFIG_06_B
)
def load_model_and_tokenizer(
which_model, device, use_compile, local_dir="qwen3"
):
if which_model == "base":
download_qwen3_small(
kind="base", tokenizer_only=False, out_dir=local_dir
)
tokenizer_path = Path(local_dir) / "tokenizer-base.json"
model_path = Path(local_dir) / "qwen3-0.6B-base.pth"
tokenizer = Qwen3Tokenizer(tokenizer_file_path=tokenizer_path)
elif which_model == "reasoning":
download_qwen3_small(
kind="reasoning", tokenizer_only=False, out_dir=local_dir
)
tokenizer_path = Path(local_dir) / "tokenizer-reasoning.json"
model_path = Path(local_dir) / "qwen3-0.6B-reasoning.pth"
<!-- page: 074 (printed 62) -->
tokenizer = Qwen3Tokenizer(
tokenizer_file_path=tokenizer_path,
apply_chat_template=True,
add_generation_prompt=True,
add_thinking=True,
)
else:
raise ValueError(f"Invalid choice: which_model={which_model}")
model = Qwen3Model(QWEN_CONFIG_06_B)
model.load_state_dict(torch.load(model_path))
model.to(device)
if use_compile:
torch.dynamo.config.allow_unspec_int_on_nn_module = True
model = torch.compile(model)
return model, tokenizer
WHICH_MODEL = "base"
device = get_device()
# device = torch.device("cpu")
model, tokenizer = load_model_and_tokenizer(
which_model=WHICH_MODEL,
device=device,
use_compile=False
)

Optionally set to true to enable model compilation. Uses the base model, similar to chapter 2, by default Uncomment this line if you have compatibility issues with your device.

By default, listing 3.1 loads the base model, just as in chapter 2.

An optional variant is the official Qwen3 reasoning model, which the Qwen3 team trained on top of the base model using reasoning-specific methods. This is not the custom reasoning model that we’ll build later in the book. Instead, we’ll use it here as a reference point. You can load it by setting WHICH_MODEL = "reasoning" in listing 3.1, so that you can later compare its evaluation results with those of the base model.

Now that we have loaded the model, we can use the text generation function from chapter 2 to generate text, as shown in the following listing.

Listing 3.2 Generating model outputs

from reasoning_from_scratch.ch02 import (
generate_text_basic_stream_cache
)
prompt = (
r"If $a+b=3$ and $ab=\tfrac{13}{6}$, "
r"what is the value of $a^2+b^2$?"
)

Define the math problem as a string prompt.

input_token_ids_tensor = torch.tensor(
tokenizer.encode(prompt),
device=device
).unsqueeze(0) # Adds batch dimension
all_token_ids = []
for token in generate_text_basic_stream_cache(
model=model,
token_ids=input_token_ids_tensor,
max_new_tokens=2048,
eos_token_id=tokenizer.eos_token_id
):
token_id = token.squeeze(0)
decoded_id = tokenizer.decode(token_id.tolist())
print(
decoded_id,
end="",
flush=True
)
all_token_ids.append(token_id)
all_tokens = tokenizer.decode(all_token_ids) # Decode the full generated sequence into text.

In this listing, we start by encoding a simple math problem into token IDs that the model can process. The model then generates tokens one by one in a streaming fashion. We print them immediately as they appear so we can read the output while it’s being generated. At the same time, we collect the generated tokens into a list so that we can later decode them into the final answer string. This pattern of both streaming and collecting tokens is handy because it lets us monitor the generation live while still storing the full answer text (in all_tokens) so we can process it later.

The response generated by the code in listing 3.2 is as follows:

To find the value of (a2+b2)( a^2 + b^2 ) given that (a+b=3)( a + b = 3 ) and (ab=136)( ab = \frac{13}{6} ), we can use the following algebraic identity:

a2+b2=(a+b)2−2aba^2 + b^2 = (a + b)^2 - 2ab

Step 1: Substitute the given values into the equation.

a2+b2=(3)2−2(136)a^2 + b^2 = (3)^2 - 2 \left( \frac{13}{6} \right)

[ … ] # Shortened for brevity

Final Answer:

143\boxed{\frac{14}{3}}

As you can see from this response, even though we’re using a base model, it provides a reasoning-model-like explanation. This is likely because the Qwen3 team included chain-of-thought data during pretraining, as stated in their technical report. But even though the model shows some reasoning-model-like behavior, adding additional reasoning methods can further improve these capabilities. (Note that the generated response may differ depending on whether you executed the code on a CPU, CUDA, or MPS device.)

If you’re unfamiliar with the LaTeX syntax commonly used for mathematics, the preceding response may be hard to decipher. In that case, you can use IPython’s Latex class to render it:

from IPython.display import Latex, display
display(Latex(all_tokens))

The result of running the preceding code in a code notebook is shown in figure 3.4.

“***” symbols, used for bold font in Markdown syntax, are not part of the LaTeX syntax and are thus not rendered.

Step 1: Substitute the given values into the equation.

a2+b2=(3)2−2(136)a^2 + b^2 = (3)^2 - 2(\frac{13}{6})

Step 2: Calculate (3)2(3)^2.

(3)2=9(3)^2 = 9

Step 3: Calculate 2×1362 \times \frac{13}{6}.

2×136=266=1332 \times \frac{13}{6} = \frac{26}{6} = \frac{13}{3}

Step 4: Subtract the second result from the first.

a2+b2=9−133a^2 + b^2 = 9 - \frac{13}{3}

Step 5: Convert 9 to a fraction with a denominator of 3 to perform the subtraction.

9=2739 = \frac{27}{3} a2+b2=273−133=143a^2 + b^2 = \frac{27}{3} - \frac{13}{3} = \frac{14}{3}

FinalAnswer:

Step 1: Substitute the given values into the equation.\textbf{Step 1: } \text{Substitute the given values into the equation.} a2+b2=(3)2−2(136)a^2 + b^2 = (3)^2 - 2\left(\tfrac{13}{6}\right) Step 2: Calculate (3)2.\textbf{Step 2: } \text{Calculate } (3)^2. (3)2=9(3)^2 = 9 Step 3: Calculate 2×136.\textbf{Step 3: } \text{Calculate } 2 \times \tfrac{13}{6}. 2×136=266=1332 \times \tfrac{13}{6} = \tfrac{26}{6} = \tfrac{13}{3} Step 4: Subtract the second result from the first.\textbf{Step 4: } \text{Subtract the second result from the first.} a2+b2=9−133a^2 + b^2 = 9 - \tfrac{13}{3} Step 5: Convert 9 to a fraction with a denominator of 3 to perform the subtraction.\textbf{Step 5: } \text{Convert 9 to a fraction with a denominator of 3 to perform the subtraction.} 9=2739 = \tfrac{27}{3} a2+b2=273−133=143a^2 + b^2 = \tfrac{27}{3} - \tfrac{13}{3} = \tfrac{14}{3} Final Answer: 143\textbf{Final Answer: } \boxed{\tfrac{14}{3}}

[!visual-conversion] Figure 3.4 — Rendered response with step-by-step calculations and the final boxed answer (printed p. 64, scan page-076.png). The print is a screenshot of the response rendered in a code notebook via IPython’s Latex class; the mathematics is transcribed above as KaTeX display math rather than embedded as a raster. Print annotations: “** symbols, used for bold font in Markdown syntax, are not part of the LaTeX syntax and are thus not rendered”, “LaTeX code is properly rendered”, and “The final answer is given in an answer box”. The final answer is given in an answer box.

The final answer shown in figure 3.4 is indeed the correct answer to this problem.

3.3 Implementing a wrapper for easier text generation

Section titled “3.3 Implementing a wrapper for easier text generation”

We have loaded the pretrained LLM and set up the text generation functionality (as illustrated in figure 3.5). Now, for convenience in later sections, we’ll create a wrapper (see listing 3.3) for the text generation function so that we only have to pass in the model, tokenizer, and prompt, along with some additional settings, instead of repeating the tokenization and input preparation steps each time.

graph TD
    S1["1 - Load pretrained LLM"] --> S2["2 - Ask LLM to generate answer"]
    S2 --> S3["3 - Extract final answer box"]
    S3 --> S4["4 - Normalize extracted answer"]
    S4 --> S5["5 - Verify equivalence"]
    S5 --> S6["6 - Grade answers"]
    S6 --> S7["7 - Load MATH-500 dataset"]
    S7 --> S8["8 - Evaluate the model"]

[!visual-conversion] Figure 3.5 — In this section, we’ll wrap steps 1 and 2 of the verifier workflow into a reusable text-generation helper (printed p. 65, scan page-077.png). Instead of repeating tokenization and input preparation each time, the wrapper handles prompting and streamed generation and returns the model’s raw LaTeX output. Steps 1 and 2 are highlighted in the print. The right-hand panel shows the worked example: Input — the raw prompt If \(a+b=3\) and \(ab=\tfrac{13}{6}\), what is the value of \(a^2+b^2\)?, annotated “The rendered question”; Output — the LLM’s answer in raw text using LaTeX syntax, annotated “The LLM’s answer in raw text (using LaTeX syntax)” and, once rendered, “The rendered answer”.

Listing 3.3 A wrapper for streamed text generation

Section titled “Listing 3.3 A wrapper for streamed text generation”
def generate_text_stream_concat(
model, tokenizer, prompt, device, max_new_tokens,
verbose=False,
):
input_ids = torch.tensor(
tokenizer.encode(prompt), device=device
).unsqueeze(0)

Figure 3.5 In this section, we’ll wrap steps 1 and 2 of the verifier workflow into a reusable text-generation helper. Instead of repeating tokenization and input preparation each time, the wrapper handles prompting and streamed generation and returns the model’s raw LaTeX output.

Listing 3.3 A wrapper for streamed text generation

Section titled “Listing 3.3 A wrapper for streamed text generation”
def generate_text_stream_concat(
model, tokenizer, prompt, device, max_new_tokens,
verbose=False,
):
input_ids = torch.tensor(
tokenizer.encode(prompt), device=device
).unsqueeze(0)
<!-- page: 078 (printed 66) -->
generated_ids = []
for token in generate_text_basic_stream_cache(
model=model,
token_ids=input_ids,
max_new_tokens=max_new_tokens,
eos_token_id=tokenizer.eos_token_id,
):
next_token_id = token.squeeze(0)
generated_ids.append(next_token_id.item())
if verbose:
print(
tokenizer.decode(next_token_id.tolist()),
end="",
flush=True
)
return tokenizer.decode(generated_ids)

This wrapper function handles the full cycle of text generation: it tokenizes the input prompt, streams new tokens from the model, and then decodes the results into a final string.

As mentioned before, the optional verbose flag allows us to see tokens as they are generated in real time. The function can be used as follows:

generated_text = generate_text_stream_concat(
model, tokenizer, prompt, device,
max_new_tokens=2048,
verbose=True
)

This prints the exact same response you saw in section 3.2:

[…] Final Answer: [ \boxed{\dfrac{14}{3}} ]

Now that we have the model loaded and ready, we can get to the interesting part: evaluating the model.

It is worth recalling that this book takes a from-scratch approach, which naturally includes some detailed, sometimes tedious, steps. This is intentional. We want to build the evaluation pipeline ourselves so we can better understand how it works, rather than just calling predefined wrapper functions and building blocks.

In the previous section, you saw that the model returned the final answer in an answer box (written as r”\boxed{\dfrac{14}{3}}” in raw text). We did not enforce that format; the model likely produced it because boxed answers are a common convention in math benchmarks and training data. This behavior is not necessarily proof of overfitting to the evaluation and training data. This behavior is not necessarily proof of overfitting to the evaluation tasks we’ll run later, but it reflects that pretrained models often encounter many problem formats online and learn to reproduce those stylistic conventions. As a general rule, it’s fair to assume that any information available on the internet when a model was trained was part of the training data.

Although it was not necessary here, when we later evaluate the model on the MATH-500 dataset, we will add a specific prompt instructing the model to return answers in this boxed form. (MATH-500 is a curated collection of 500 problems widely used as a benchmark dataset for reasoning models.) This step is straightforward, and it will reappear whenever we need to turn a model response into something that can be scored automatically at scale. This common convention makes evaluation more consistent across models and simplifies data extraction.

We will now write code that performs this extraction of the boxed answer content. This section implements step 3 in figure 3.6. (The next section will implement the normalization method for step 4.)

graph TD
    S1["1 - Load pretrained LLM"] --> S2["2 - Ask LLM to generate answer"]
    S2 --> S3["3 - Extract final answer box"]
    S3 --> S4["4 - Normalize extracted answer"]
    S4 --> S5["5 - Verify equivalence"]
    S5 --> S6["6 - Grade answers"]
    S6 --> S7["7 - Load MATH-500 dataset"]
    S7 --> S8["8 - Evaluate the model"]

[!visual-conversion] Figure 3.6 — An illustration of how the boxed result is extracted from the LLM output (printed p. 67, scan page-079.png). Steps 1 and 2 are shown as completed (ticked) and step 3 is highlighted. The worked panel shows the raw output \boxed{\dfrac{14}{3}} with the boxed portion ringed and an arrow to the extracted string \dfrac{14}{3}, annotated “Extracts final boxed result from LLM response”.

Because your model may produce slightly different responses than mine, depending on your hardware, the following code uses a hardcoded placeholder answer rather than generating a response with the model (but we’ll pretend that this answer was generated by the model). In later sections, we’ll revisit the model and have it generate answers for the tasks in the MATH-500 dataset:

model_answer = ( r"""... some explanation...
**Final Answer:**
\[ \boxed{\dfrac{14}{3}} \] """

)

NOTE We are using a raw string (r"""…""" instead of a regular string """…"""). Raw strings make it easier to handle backslash () characters, which would otherwise be treated as escape sequences and require each backslash to be doubled.

Next, let’s define a function to extract the answer box from model_answer.

Listing 3.4 Extracting answer boxes

def get_last_boxed(text):
boxed_start_idx = text.rfind(r"\boxed")
if boxed_start_idx == -1:
return None
current_idx = boxed_start_idx + len(r"\boxed") # Find the last occurrence of "\boxed".
while current_idx < len(text) and text[current_idx].isspace(): # Get the position after "\boxed".
current_idx += 1
if current_idx >= len(text) or text[current_idx] != "{": # Expect an opening brace "{".
return None
current_idx += 1
brace_depth = 1
content_start_idx = current_idx
while current_idx < len(text) and brace_depth > 0: # Parse the braces
char = text[current_idx]
if char == "{":
brace_depth += 1
elif char == "}":
brace_depth -= 1
current_idx += 1
if brace_depth != 0: # Account for unbalanced braces.
return None
return text[content_start_idx:current_idx-1] # Extract content inside the outermost braces.

The get_last_boxed helper utility function in listing 3.4 extracts the content of the last …\boxed{\ldots} expression from a model’s output. More specifically, it scans for the final \boxed, skips over whitespace, checks for braces, and handles any nesting so that it captures the intended answer string.

While it may look a bit tedious, having this parser in place will pay off when we run evaluations on datasets like MATH-500, where extracting the correct final answer is the first step toward measuring a model’s reasoning ability.

Now, let’s test this function on the model answer:

extracted_answer = get_last_boxed(model_answer) print(extracted_answer)

The output of this function call is “\dfrac{14}{3}”, which is the boxed answer we wanted to extract.

Rendering math formulas

We can render math formulas via the Latex class introduced earlier. Alternatively, for standalone math formulas without accompanying answer text, we can use the simpler Math class:

from IPython.display import Math display(Math(r"\dfrac{14}{3}"))

This renders the fraction as

143\frac{14}{3}

The preceding get_last_boxed function correctly extracted the text, but we can make answer extraction a bit more robust with the extract_final_candidate function (shown in the following listing), which accounts for cases where a final answer box is missing or incomplete.

Listing 3.5 Extracting the final answer candidate

import re
RE_NUMBER = re.compile(
r"^-?(\d+|\d+\.\d+|\d+\.?\d+)(?:[eE][+-]?\d+)?"
)
def extract_final_candidate(text, fallback="number_then_full"):
result = "" # CODE-ANNOTATION: "Regular expression for extracting numeric values from the text" # Annotated arrow pointing to the regex pattern
if text:
boxed = get_last_boxed(text.strip()) # CODE-ANNOTATION: "Default return value if nothing matches" # Annotated arrow pointing to the result variable
<!-- CODE-ANNOTATION: "Prefer the last boxed expression if present." | Annotated arrow pointing to the get_last_boxed call -->
return boxed
return fallback
<!-- page: 082 (printed 70) -->
if boxed:
result = boxed.strip().strip("$ ")
elif fallback in ("number_then_full", "number_only"):
m = RE_NUMBER.findall(text)
if m:
result = m[-1]
elif fallback == "number_then_full":
result = text
return result

This extract_final_candidate function provides fallback settings in case no boxed answer is found, as follows:

  • “number_then_full” (the default): Pick the last simple number; otherwise, pick the whole text.
  • “number_only”: Pick the last simple number; otherwise, return an empty string "".
  • “none”: Extract only the boxed content; otherwise, return an empty string "".

For the fallback setting, the code in listing 3.5 uses regular expressions (regex for short) via Python’s re library. Regexes are a way to search for patterns in text. In our case, the regex pattern is designed to recognize numbers, including fractions, decimals, and scientific notation. While the regex syntax looks intimidating, you don’t need to worry about how it works here. What matters is that this gives us a reliable tool for extracting the last numeric candidate from the model’s output when no boxed answer is available.

Let’s try it on our model answer:

print(extract_final_candidate(model_answer))

This correctly returns “\dfrac{14}{3}”.

Now let’s try some additional examples. First, here’s another boxed candidate:

print(extract_final_candidate(r"\boxed{ 14/3. }"))

This correctly returns “14/3.”, stripping the extra whitespace but not the punctuation. The punctuation character will be handled correctly by the equality check we implement later.

Next, let’s try a candidate without a box, which should trigger the fallback setting:

print(extract_final_candidate("abc < > 14/3 abc"))

Thanks to the default fallback setting, it will find the last number in the answer and correctly return “14/3”.

In this section, we defined utility functions to extract the LLM’s answer from its response text. This brings us one step closer to our overall goal of verifying whether that answer is correct. In the next section, we’ll normalize the response into a more general, canonical form before implementing the checking functionality.

Why not use an LLM to extract the answer? We could use an LLM to extract the boxed answer itself, but that would introduce unnecessary complexity and potential errors. Extraction is a simple, mechanical task, assuming that the LLM outputs the answer in a specific format: we just need to locate the last boxed expression or, if that is missing, fall back to a number or the raw text. Regular expressions may look complicated at first, but we now have a small, reusable utility function that is cheap to execute and handles the extraction deterministically and reproducibly, without depending on the variability of another model’s output.

Previously, we extracted the boxed answer “\dfrac{14}{3}” from the model’s response. Models may print the same value in many ways, such as “\frac{14}{3}”, “14/3”, "14/314/3", or “(14)/(3)”. To implement and use a robust checking system to determine whether the answer is correct, we first need a consistent method of comparing results. In this section, we’ll implement a normalization (or canonicalization) pass (step 4 in figure 3.7) that strips formatting and standardizes the answer.

graph TD
    S1["1 - Load pretrained LLM"] --> S2["2 - Ask LLM to generate answer"]
    S2 --> S3["3 - Extract final answer box"]
    S3 --> S4["4 - Normalize extracted answer"]
    S4 --> S5["5 - Verify equivalence"]
    S5 --> S6["6 - Grade answers"]
    S6 --> S7["7 - Load MATH-500 dataset"]
    S7 --> S8["8 - Evaluate the model"]

[!visual-conversion] Figure 3.7 — An illustration of how the boxed result from the LLM output is extracted and converted into a canonical plain form (printed p. 71, scan page-083.png). This normalized answer will later be verified against the correct answer. Steps 1–3 are ticked and step 4 is highlighted. The worked panel carries the extracted \dfrac{14}{3} through to the canonical form (14)/(3), annotated “Convert the extracted answer to a canonical plain form”.

The normalization step shown in figure 3.7 is implemented in the following normalize_text function.

Listing 3.6 Normalizing extracted answers

LATEX_FIXES = [
(r"\left\s*", ""),
(r"\right\s*", ""),
(r"\,|\!\|\\;|\:\|", ""),
(r"\cdot", "*"),
(r"\u00B7|\u00D7", "*"),
(r"\^{\circ}", ""),
(r"\dfrac", r"\frac"),
(r"\tfrac", r"\frac"),
("°", ""),
]
RE_SPECIAL = re.compile(r"<\|[^>]+?\|>")
SUPERSCRIPT_MAP = {
"⁰": "0", "¹": "1", "²": "2", "³": "3", "⁴": "4",
"⁵": "5", "⁶": "6", "⁷": "7", "⁸": "8", "⁹": "9",
"+": "+", "-": "-", "(": "(", ")": ")",
}
def normalize_text(text):
if not text:
return ""
text = RE_SPECIAL.sub("", text).strip()
match = re.match(r"^[A-Za-z]\s*[:.]\s*(.+)$", text)
if match:
text = match.group(1)
text = re.sub(r"^\s*\{\\s*\circ\s*\}", "", text)
text = re.sub(r"^\s*\circ", "", text)
text = text.replace("°", "")
match = re.match(r"^\|\text\{(?P<x>.+)\}\$", text)
if match:
text = match.group("x")
text = re.sub(r"\\\(\\\)|\\\[\\\]|\\]\|\\\]", "", text)
for pat, rep in LATEX_FIXES:
text = re.sub(pat, rep, text)
def convert_superscripts(s, base=None):
converted = "".join(
SUPERSCRIPT_MAP[ch] if ch in SUPERSCRIPT_MAP else ch
for ch in s
)
if base is None:
return converted
return f"{base}**{converted}"

LaTeX formatting to be replaced (left: original value, right: new value)

Strip chat special tokens like <|assistant|>.

Dictionary mapping to convert unicode superscripts to plaintext superscripts

Strip leading multiple choice labels (e.g., like “c. 3” → 3).

Remove angle-degree markers.

Unwrap “\text{…}” if the whole string is wrapped.

Strip inline/display math wrappers: ()[].

LaTeX canonicalization

text = re.sub(
r"(\[0-9A-Za-z\]\])\(([0-9]+)\)",
lambda m: convert_superscripts(m.group(2), base=m.group(1)),
text,
)
text = convert_superscripts(text)
text = text.replace("\\%", "%").replace("$", "").replace("%", "")
text = re.sub(
r"\\sqrt{s*\{([^}]+)\}}",
lambda match: f"sqrt({match.group(1)})",
text,
)
text = re.sub(
r"\\sqrt{s+([^}]+)}",
lambda match: f"sqrt({match.group(1)})",
text,
)
text = re.sub(
r"\\frac{s*\{([^}]+)\}}{([^}]+)}",
lambda match: f"({match.group(1)})/({match.group(2)})",
text,
)
text = re.sub(
r"\\frac{s+([^}]+)}{([^}]+)}",
lambda match: f"({match.group(1)})/({match.group(2)})",
text,
)
text = text.replace("^", "**")
text = re.sub(
r"(?<=[d])s+(\d+/\d+)",
lambda match: "+" + match.group(1),
text,
)
text = re.sub(
r"(?<=[d])\s+(\d+\d\d(\D|$))",
"",
text,
)
return text.replace("{", "").replace("}", "").strip().lower()

This normalize_text function takes an extracted answer string and rewrites it into a standardized format that we can reliably compare against reference solutions. It first

strips away special tokens and unnecessary LaTeX clutter, such as \left, \right, or degree symbols. It then unwraps cases like \text{…}, removes inline math markers, and rewrites common structures into a calculator-style form. For example, it turns \sqrt{a} into sqrt(a) and \frac{a}{b} into (a)/(b). Finally, it normalizes exponents, mixed numbers, and thousands separators and cleans up braces and casing. In short, the function transforms differently formatted LaTeX outputs into a clean, standardized string representation.

Let’s try the normalize_text function on our model answer:

print(normalize_text(extract_final_candidate(model_answer)))

Instead of printing the answer with LaTeX formatting (r”\frac{14}{3}”), it returns the answer in a standardized, LaTeX-free form:

“(14)/(3)”

Next, let’s try a differently formatted answer:

print(normalize_text(r"\text{\frac{14}{3}}"))

This also returns “(14)/(3)”, as intended.

We now have a robust method that extracts answer texts from an LLM’s response. In the next section, we’ll implement a function that compares the LLM answer with a correct reference answer.

So far, we have implemented steps that ask an LLM to generate an answer, extract the relevant portion, and normalize it. The next step, as illustrated in figure 3.8, is to verify the extracted answer by comparing it to a correct reference answer, which in technical contexts is referred to as the ground truth. We will use such a verifier again in chapter 6 to create a verifiable reward signal, and in later chapters we’ll use it to check whether our training changes improved our model.

Note that to implement the equality check shown in figure 3.8, a direct comparison using Python’s == operator is not sufficient, since expressions like “14/3” and “(14)/(3)” would not match, and equivalent but unnormalized fractions such as “(28)/(6)” and “(14)/(3)” would also be treated as unequal.

As part of our equality check, we’ll add an intermediate step: parsing the extracted, normalized answer with a symbolic math engine. For this, we’ll use the open source SymPy math library (https://sympy.org), which has been developed and tested over two decades and has become a staple of scientific computing in Python. The parsing function is implemented in listing 3.7.

NOTE If you haven’t installed the dependencies from chapter 2, you can manually install SymPy with uv pip install sympy (or uv add sympy).

  • Load pretrained LLM
  • Ask LLM to generate answer
  • Extract final answer box
  • Normalize extracted answer
  • Verify equivalence
  • Grade answers
  • Load MATH-500 dataset
  • Evaluate the model

We use the identity \(a2+b2=(a+b)2−2ab\)\backslash(a^2+b^2=(a+b)^2-2ab\backslash). … Final Answer: \143\\backslash\boxed{\dfrac{14}{3}}\backslash We use the identity a2+b2=(a+b)2−2aba^2 + b^2 = (a + b)^2 - 2ab. … Final Answer: 143\dfrac{14}{3} (1) Output

143\dfrac{14}{3} (14)/(3)(14)/(3) 14/3 Ground truth

Are equal? True “Ground truth” is the correct answer provided in the dataset.

Compare the LLM-generated answer (after extraction and normalization) to the true (correct) answer.

graph TD
    S1["1 - Load pretrained LLM"] --> S2["2 - Ask LLM to generate answer"]
    S2 --> S3["3 - Extract final answer box"]
    S3 --> S4["4 - Normalize extracted answer"]
    S4 --> S5["5 - Verify equivalence"]
    S5 --> S6["6 - Grade answers"]
    S6 --> S7["7 - Load MATH-500 dataset"]
    S7 --> S8["8 - Evaluate the model"]

[!visual-conversion] Figure 3.8 — An illustration of how an LLM-generated answer is checked against the correct reference answer (ground truth) (printed p. 75, scan page-087.png). The LLM’s final boxed answer is extracted, normalized, and compared to the correct answer provided in the dataset. If they match, the response is graded as correct. Steps 1–4 are ticked and steps 5 and 6 are highlighted. The worked panel compares the normalized (14)/(3) against the ground truth 14/3 via “Are equal?” → True, annotated “Compare the LLM-generated answer (after extraction and normalization) to the true (correct) answer” and “‘Ground truth’ is the correct answer provided in the dataset.”

Listing 3.7 Using the SymPy parser for a mathematical equality check

from sympy.parsing import sympy_parser as spp
from sympy.core.sympify import SympifyError
from sympy.polys.polyerrors import PolynomialError
from tokenize import TokenError
def sympy_parser(expr):
if expr is None or len(expr) > 2000: # To avoid crashing on long garbage responses.
return None
try:
return spp.parse_expr(
expr,
transformations=(
*spp.standard_transformations, # Standard transformations like handling parentheses.
spp.implicit_multiplication_application, # Allow omitted multiplication symbols (e.g., 2y -> 2*y).
),
<!-- page: 088 (printed 76) -->
evaluate=True, # Evaluate during parsing so simple constants simplify (e.g., 2+3 -> 5).
)
except (SympifyError, SyntaxError, TypeError, AttributeError,
IndexError, TokenError, ValueError, PolynomialError):
return None

This sympy_parser function takes an input expression, such as the normalized answers we extract from the LLM response, and converts it into a SymPy object that can be reliably compared for mathematical equivalence. To do so, it applies SymPy’s standard parsing rules, supports implicit multiplication (for example, 2y instead of 2 * y), and simplifies basic arithmetic (so 2 + 3 becomes 5).

NOTE The sympy_parser accounts for what may seem like an excessive number of error cases, but these are all errors I’ve encountered when evaluating the model on the 500 MATH-500 problems. The model does not always generate perfectly formatted outputs.

Let’s see sympy_parser in action and apply it to a normalized answer candidate:

print(sympy_parser(normalize_text(
extract_final_candidate(model_answer)
)))

This returns the fraction 14/3. Next, let’s try an unnormalized fraction:

print(sympy_parser("28/6"))

Similarly, this returns 14/3. Using sympy_parser, we can now implement the equality check function.

Listing 3.8 Equality check function using SymPy

from sympy import simplify
def equality_check(expr_gtruth, expr_pred):
if expr_gtruth == expr_pred:
return True
gtruth, pred = sympy_parser(expr_gtruth), sympy_parser(expr_pred) #
if gtruth is not None and pred is not None:
try:
return simplify(gtruth - pred) == 0 #
except (SympifyError, TypeError):
pass
return False

First, check if the two expressions are exactly the same string.

Parse both expressions into SymPy objects (returns None if parsing fails).

If both expressions were parsed successfully, try symbolic comparison.

If the difference is 0, they are equivalent.

Grading answers

The equality_check function in the preceding listing determines whether a model’s answer matches the ground-truth solution. It first looks for an exact string match, which is the simplest case. If the strings differ, it parses both expressions into SymPy objects (via the sympy_parser function we implemented in listing 3.7) and checks whether their difference simplifies to zero. This lets us recognize answers that may look different on the surface (for example, 14/3 and 28/6) but are mathematically the same.

Let’s try the equality checker from listing 3.8 on an example:

print(equality_check(
normalize_text("13/4."),
normalize_text(r"(13)/(4)")
))

As intended, this ignores the formatting and returns True. Next, let’s try a more challenging example and see whether the symbolic math parser recognizes that 0.5 is the same as 1/2:

print(equality_check(
normalize_text("0.5"),
normalize_text(r"(1)/(2)")
))

This also returns True. Now, let’s try a negative example:

print(equality_check(
normalize_text("14/3"),
normalize_text("15/3")
))

This returns False, since the expressions are different.

So far, so good. Based on these encouraging results, we might conclude that we now have a robust equality checker that we can use to evaluate the LLM on a math benchmark dataset. To make sure it’s ready for prime time, let’s try one more example:

print(equality_check(
normalize_text("(14/3, 2/3)"),
normalize_text("(14/3, 4/6)")
))

In this case, we are comparing two tuples. Since 2/3 and 4/6 are mathematically equivalent, we would expect the result to be True. Instead, the function returns False because it currently handles only simple expressions, not tuples. We will address this limitation in the next section.

3.7 Grading answers

Now we’ll build on the previous section’s mathematical equality-checking function to implement a robust grading function that can also handle tuple-like expressions, such as correctly comparing “(14/3, 2/3)” and “(14/3, 4/6)”.

First, we’ll implement a Python helper function that splits such tuple-like expressions into individual subparts.

Listing 3.9 A helper function to split tuple-like expressions

def split_into_parts(text):
result = [text]
if text:
if (
len(text) >= 2
and text[0] in "(["
and text[-1] in ")]"
and "," in text[1:-1]
):
items = [p.strip() for p in text[1:-1].split(",")]
if all(items):
result = items
else:
result = []
return result

The preceding split_into_parts function helps us handle answers with multiple components. If the input looks like a tuple or list, such as (a, b) or [a, b], it splits the content on the commas and returns the individual pieces. (If the string is empty, it simply returns an empty list.) In essence, this function breaks down multipart answers into smaller parts that can be checked one by one.

Before we implement the grading function, let’s take split_into_parts for a test drive on the tuple-like expression from earlier:

split_into_parts(normalize_text(r"(14/3, 2/3)"))

This returns [‘14/3’, ‘2/3’], as desired.

Now, we can implement the grade_answer function (listing 3.10), which splits tuple-like expressions (if present) into subparts and then uses the equality_check function from the previous section to compare a generated answer to a reference (ground truth) answer.

Listing 3.10 Function to grade predicted answers against the ground truth

def grade_answer(pred_text, gt_text):
result = False
if pred_text is not None and gt_text is not None:
gt_parts = split_into_parts(
normalize_text(gt_text)
)
pred_parts = split_into_parts(
normalize_text(pred_text)
)
if (gt_parts and pred_parts
and len(gt_parts) == len(pred_parts)):
# Ensure both sides have the same number of valid parts.
<!-- page: 091 (printed 79) -->
result = all( # True only if all checks passed. Check each part for mathematical equivalence.
equality_check(gt, pred)
for gt, pred in zip(gt_parts, pred_parts)
)
return result

This implementation of the grade_answer function first assumes the prediction is incorrect (False) and continues only if both the prediction and the ground truth are non-empty. It then normalizes each side and splits them into subparts (for example, breaking “(14/3, 2/3)” into [“14/3”, “2/3”]). If the number of subparts matches, it compares them one by one using equality_check. The result is returned as correct (True) only if all pairs match mathematically.

We can think of the grade_answer function as an advanced version of the equality_check function from the previous section. It can split tuple-like expressions and normalize the answers before applying the equality_check function.

On simple expressions, it works similarly to equality_check, returning True if two expressions are mathematically equivalent:

grade_answer("14/3", r"\frac{14}{3}")

In addition, it now also returns True for two mathematically equivalent tuple-like expressions:

grade_answer(r"(14/3, 2/3)", "(14/3, 4/6)")

To check the grade_answer function more comprehensively, the following listing contains more diverse test cases.

Listing 3.11 Test cases and demo function to test the grader

tests = [
("check_1", "3/4", r"\frac{3}{4}", True),
("check_2", "(3)/(4)", r"3/4", True),
("check_3", r"\frac{\sqrt{8}}{2}", "sqrt(2)", True),
("check_4", r"(\frac{1}{2} + \frac{1}{6})", "2/3", True),
("check_5", "(1, 2)", r"(1,2)", True),
("check_6", "(2, 1)", "(1, 2)", False),
("check_7", "(1, 2, 3)", "(1, 2)", False),
("check_8", "0.5", "1/2", True),
("check_9", "0.333333333", "1/3", False),
("check_10", "1,234/2", "617", True),
("check_11", r"\text{2/3}", "2/3", True),
("check_12", "50%", "1/2", False),
("check_13", r"2\cdot 3/4", "3/2", True),
("check_14", r"90^{\circ}", "90", True),
("check_15", r"\left(\frac{3}{4}\right)", "3/4", True),
("check_16", r"2^2", "2*2", True),
]
<!-- page: 092 (printed 80) -->
def run_demos_table(tests):
header = ("Test", "Expect", "Got", "Status")
rows = []
for name, pred, gtruth, expect in tests:
got = grade_answer(pred, gtruth)
status = "PASS" if got == expect else "FAIL"
rows.append((name, str(expect), str(got), status))
data = [header] + rows
col_widths = [
max(len(row[i]) for row in data)
for i in range(len(header))
]
for row in data:
line = " | ".join(
row[i].ljust(col_widths[i])
for i in range(len(header))
)
print(line)
passed = sum(r[3] == "PASS" for r in rows)
print(f"\nPassed {passed}/{len(rows)}")

Runs an equality check

Computes the max width for each column to align table nicely

Prints the table row by row

Prints the summary of passed tests

The code in listing 3.11 is a simple test suite that uses a selection of tests to check whether the grade_answer function works as intended. The tests list contains tuples covering fractions, LaTeX notation, tuple inputs, decimals, percentages, and other tricky formats. The run_demos_table function then runs each test by calling grade_answer, collects the outcomes, and organizes the results into a formatted table.

Calling the run_demos_table(tests) function in listing 3.11 prints the following table:

TestExpectGotStatus
check_1TrueTruePASS
check_2TrueTruePASS
check_3TrueTruePASS
check_4TrueTruePASS
check_5TrueTruePASS
check_6FalseFalsePASS
check_7FalseFalsePASS
check_8TrueTruePASS
check_9FalseFalsePASS
check_10TrueTruePASS
check_11TrueTruePASS
check_12FalseFalsePASS
check_13TrueTruePASS
check_14TrueTruePASS
check_15TrueTruePASS
check_16TrueTruePASS

Passed 16/16

As you can see from the PASS results, the grade_answer function is relatively robust and can handle a variety of differently formatted expressions.

Try to think of additional test cases, ideally, challenging ones, and add them to the run_demos_table() function. Can you find cases where the check fails incorrectly? With grade_answer implemented, we now have the building blocks to evaluate the LLM. In the next section, we’ll load a math dataset on which to evaluate it.

As you have seen so far in this chapter, implementing a robust verification pipeline can be tedious. Fortunately, we now have all the pieces in place, from answer extraction to grading, and we’re ready to evaluate the LLM on a benchmark dataset. As shown in figure 3.9, we’ll use the MATH-500 dataset (https://huggingface.co/datasets/HuggingFaceH4/MATH-500), a widely used benchmark for reasoning models. It is a curated collection of 500 problems sampled from the original MATH dataset.

graph TD
    S1["1 - Load pretrained LLM"] --> S2["2 - Ask LLM to generate answer"]
    S2 --> S3["3 - Extract final answer box"]
    S3 --> S4["4 - Normalize extracted answer"]
    S4 --> S5["5 - Verify equivalence"]
    S5 --> S6["6 - Grade answers"]
    S6 --> S7["7 - Load MATH-500 dataset"]
    S7 --> S8["8 - Evaluate the model"]

[!visual-conversion] Figure 3.9 — Loading the evaluation dataset (printed p. 81, scan page-093.png). We completed steps 2–6 (generate, extract, normalize, verify, and grade answers) in the previous sections; the two remaining steps are to load the full dataset (step 7) and apply the same procedure across all the problems to evaluate the model (step 8). Steps 1–6 are ticked and step 7 is highlighted. The print shows a panel of MATH-500 records beside step 7, annotated “Dataset consisting of many math problems”:

{"index": 1, "problem": "Convert the point $(0,3)$ ...
{"index": 2, "problem": "Define\[p = \sum_{k = 1} ...
{"index": 3, "problem": "If $f(x) = \frac{3x-2}{x-2}$, ...
{"index": 4, "problem": "How many positive whole-number ...
{"index": 5, "problem": "The results of a cross-country ...
{"index": 6, "problem": "A regular hexagon can be divided ...
{"index": 7, "problem": "What is the smallest positive ...
{"index": 8, "problem": "The set of points $(x,y)$ that ...
{"index": 9, "problem": "What is the distance, in units, ...
{"index": 10, "problem": "The expression $2\cdot 3 \cdot ...

(Record text is truncated in the print, as shown.)

Using MATH-500 is a practical choice for three reasons. First, MATH-500 is large enough to be meaningful but still small enough to keep repeated evaluations throughout the book manageable, whereas running the full MATH dataset each time would be much slower. Second, in later chapters we’ll use a non-overlapping training subset derived from the original MATH dataset, so keeping MATH-500 as a held-out evaluation set gives us a clean reference point. Third, MATH-500 is a common benchmark dataset in the reasoning-model literature, which makes the results in this book easier to compare with prior work. I also prefer MATH-500 over simpler datasets such as GSM8K because it is more challenging for modern reasoning models and it better matches the kind of multistep symbolic verification pipeline we are building in this chapter.

We’ll load the MATH-500 dataset using the following code.

Listing 3.12 Loading the MATH-500 dataset

import json
import requests
def load_math500_test(local_path="math500_test.json", save_copy=True):
local_path = Path(local_path)
url = (
"https://raw.githubusercontent.com/rasbt/reasoning-from-scratch/"
"main/ch03/01_main-chapter-code/math500_test.json"
)
if local_path.exists():
with local_path.open("r", encoding="utf-8") as f:
data = json.load(f)
else:
r = requests.get(url, timeout=30)
r.raise_for_status()
data = r.json()
if save_copy: # Saves a local copy
with local_path.open("w", encoding="utf-8") as f:
json.dump(data, f, indent=2)
return data
math_data = load_math500_test()
print("Number of entries:", len(math_data))

This prints the following result:

Number of entries: 500

Loading the dataset from Hugging Face Model Hub

The MATH-500 dataset split was originally proposed in the PRM800K repository (https://github.com/openai/prm800k/tree/main?tab=readme-ov-file#math-splits), and it is also available on the Hugging Face Hub (https://huggingface.co/datasets/HuggingFaceH4/MATH-500). The code we use in this chapter loads a copy from the code repository so you can ensure reproducibility if the external sources change.

If you prefer to download the dataset directly from Hugging Face, you can use the following optional code. Note that this requires the datasets library, which can be installed via pip install datasets or uv add datasets:

from datasets import load_dataset
dset = load_dataset("HuggingFaceH4/MATH-500", split="test")

Before we implement the model evaluation pipeline in the next section, let’s take a closer look at the structure of the dataset by printing its first entry (we’ll use the built-in pprint library for nicer formatting):

from pprint import pprint
pprint(math_data[0])

This produces the following output:

{'answer': '\\left( 3, \\frac{\\pi}{2} \\right)',
'level': 2,
'problem': 'Convert the point $(0,3)$ in rectangular coordinates to polar coordinates. Enter your answer in the form $(r,\\theta)$, where $r > 0$ and $0 \\le \\theta < 2 \\pi.$',
'solution': 'We have that $r = \\sqrt{0^2 + 3^2} = 3.$ Also, if we draw the line connecting the origin and $(0,3)$, this line makes an angle of $\\frac{\\pi}{2}$ with the positive $x$-axis.\n\n[asy]n\nunitsize(0.8 cm);n\n\ndraw((-0.5,0)--(3.5,0));n\ndraw((0,-0.5)--(0,3.5));n\ndraw(arc((0,0),3,0,90),red,Arrow(6));n\n\ndot((0,3), red);n\nlabel("$ (0,3) $", (0,3), W);n\ndot((3,0), red);n\n\n[/asy]n\n\nTherefore, the polar coordinates are $\\boxed{\\left( 3, \\frac{\\pi}{2} \\right)}.$',
'subject': 'Precalculus',
'unique_id': 'test/precalculus/807.json'}

As you can see, the dataset entry is formatted as a Python dictionary with keys and values, sorted in alphabetical order. These are the relevant keys:

  • problem: The math question or problem for the LLM to solve
  • answer: The correct (ground truth) answer we want to compare the LLM answer against
  • solution: A worked-out, step-by-step explanation of the problem (not used in this chapter, but useful for training or analysis)

Now that we have a pretrained LLM, evaluation functions, and a benchmark dataset to work with, we can evaluate the model.

In this section, we’ll put the LLM text generation and evaluation tools from steps 2–6 in figure 3.10 into practice and apply them to the MATH-500 dataset (step 8), which we loaded in the previous section. This full pipeline will be important in future chapters because it will be the main way we’ll measure progress when we compare prompting methods and training-based improvements.

graph TD
    S1["1 - Load pretrained LLM"] --> S2["2 - Ask LLM to generate answer"]
    S2 --> S3["3 - Extract final answer box"]
    S3 --> S4["4 - Normalize extracted answer"]
    S4 --> S5["5 - Verify equivalence"]
    S5 --> S6["6 - Grade answers"]
    S6 --> S7["7 - Load MATH-500 dataset"]
    S7 --> S8["8 - Evaluate the model"]

[!visual-conversion] Figure 3.10 — The complete evaluation pipeline for the MATH-500 dataset (printed p. 84, scan page-096.png). After loading the dataset (step 7), steps 2–6 are applied systematically across all problems to obtain the final model evaluation (step 8). Steps 1–7 are ticked and step 8 is highlighted. A bracket spans steps 2–6 annotated “Step 8 executes steps 2–6 on problems from the MATH-500 dataset shown below”, and the right-hand panel shows the LLM feeding MATH-500 accuracy, beside the same truncated record list annotated “Dataset consisting of many math problems”.

As you may recall from section 3.4, our answer-checking pipeline expects the model to return the answer in boxed form, which is a common convention when evaluating reasoning models on math problems. To increase the likelihood that the model adheres to this format, we can format the prompt as follows.

Listing 3.13 Function to render a prompt template for math evaluation

def render_prompt(prompt):
template = (
"You are a helpful math assistant.\n"
"Answer the question and write the final result on a new line as:\n"
"\\\\boxed{ANSWER}\n\n"
f"Question:{prompt}\n\nAnswer:"
)
return template

Let’s now apply this prompt template to the example prompt introduced in section 3.2 and shown again here:

prompt = (
r"If $a+b=3$ and $ab=\tfrac{13}{6}$, "
r"what is the value of $a^2+b^2$?"
)
prompt_fmt = render_prompt(prompt)
print(prompt_fmt)

The formatted prompt is now as follows:

You are a helpful math assistant. Answer the question and write the final result on a new line as: \boxed{ANSWER}

Question: If a+b=3a+b=3 and ab=136ab=\tfrac{13}{6}, what is the value of a2+b2a^2+b^2?

Answer:

Next, we’ll pass the prompt to the text generation wrapper function we defined in listing 3.3 to recap the text generation process before we construct the model evaluation function:

generated_text = generate_text_stream_concat(
model, tokenizer, prompt_fmt, device,
max_new_tokens=2048,
verbose=True
)

Using this prompt example, the model responds with a relatively brief answer: “\boxed{10}”. (Note that the generated response may differ depending on whether you run the code on a CPU, CUDA, or MPS device.)

While brevity can speed up generation by reducing the number of tokens, the response is incorrect. In section 3.3, by contrast, without a prompt template, the model produced a longer response, which led to the correct answer, 14/3.

Whether the prompt template is well suited to a given model and task needs to be determined on a larger set of examples, such as the MATH-500 dataset, before we can draw any conclusions.

Prompt template choices

The prompt template in listing 3.13 is used here to show how you can implement a model evaluation pipeline with answers that are automatically checked for correctness. The chosen template encourages short outputs, which will let you work through this chapter efficiently on a first read. Afterward, I recommend revisiting the chapter’s examples with alternative settings to optimize accuracy on the official Qwen3 reasoning model variant used here as a reference model.

As it turns out, using no prompt template boosts the base model’s performance by 50%, but it reduces the reasoning model’s accuracy by 40%.

Additionally, we can experiment with alternative prompt templates. For instance, the standard prompt commonly used for the MATH-500 benchmark is a variant of listing 3.13 that swaps “Question:” for “Problem:”. This seemingly minor change improves the base model’s accuracy by approximately 20%, likely because it better matches the memorized training data (assuming the MATH-500 test set was included in the training corpus). While the base model benefits from this change, the reasoning model variant’s accuracy drops by 30%.

Earlier, I mentioned that answer extraction is a simple, mechanical task that can be solved with deterministic code rather than by employing another LLM for answer extraction. Based on the change in accuracy across different prompting templates, it looks like our extraction method may not be reliable. This is not necessarily the case.

Also, it’s not necessarily the case that the LLM generates misformatted answers. It may simply be incorrect, and switching to another LLM for extraction would not solve that. Smaller base models are often quite sensitive to prompt phrasing. In the next chapter, you’ll see that this becomes even more apparent once we introduce additional prompt variations.

Before we implement the final model evaluation function, let’s test our model evaluation pipeline from end to end on a smaller example using the following demo function.

Listing 3.14 Demo function to run the evaluation pipeline

def mini_eval_demo(model, tokenizer, device):
ex = {
"problem": "Compute 1/2 + 1/6.",
"answer": "2/3"
}
prompt = render_prompt(ex["problem"])
gen_text = generate_text_stream_concat(
model, tokenizer, prompt, device,
max_new_tokens=64,
)
pred_answer = extract_final_candidate(gen_text)
is_correct = grade_answer(
pred_answer, ex["answer"]
)
print(f"Device: {device}")
print(f"Prediction: {pred_answer}")
print(f"Ground truth: {ex['answer']}")
print(f"Correct: {is_correct}")
  1. Generate response
  2. Extract and normalize answer
  3. Grade answer

This mini_eval_demo function combines all the aspects we have covered so far in this chapter:

  1. Applying a prompt template 2. Feeding the formatted prompt to the LLM to generate an answer 3. Extracting and normalizing the answer 4. Grading the answer

The mini_eval_demo function essentially connects the evaluation components into a small function that we can use to test the code before building our final evaluation pipeline for the MATH-500 dataset. The code starts with a toy example (ex), renders the problem into the prompt template (prompt), and streams a response from the model (generate_text_stream_concat). It then parses the model output into a final candidate answer (pred_answer) and grades it against the ground truth with grade_answer. Lastly, it prints the results for us to evaluate.

Calling the mini_eval_demo(model, tokenizer, device) function results in the following output:

Device: mps
Prediction: 1/3
Ground truth: 2/3
Correct: False

You can see that the generated answer (“1/3”) was correctly extracted, but it doesn’t match the correct answer (“2/3”), so the check returns False. (Note that your results may differ depending on whether you run the code on a CPU, CUDA, or MPS device.)

Now that we have tested our workflow on a simple example, let’s implement it on the MATH-500 dataset.

Listing 3.15 End-to-end model evaluation pipeline for MATH-500 dataset

import time
def eta_progress_message( # Helper function to print progress with optional ETA (estimated time to arrival)
<!-- page: 100 (printed 88) -->
processed, total, start_time, show_eta=False, label="Progress",
):
progress = f"{label}: {processed}/{total}"
pad_width = len(f"{label}: {total}/{total} # ETA: 00h 00m 00s")
if not show_eta or processed <= 0:
return progress.ljust(pad_width)
elapsed = time.time() - start_time
if elapsed <= 0:
return progress.ljust(pad_width)
remaining = max(total - processed, 0)
if processed:
avg_time = elapsed / processed
eta_seconds = avg_time * remaining
else:
eta_seconds = 0
eta_seconds = max(int(round(eta_seconds)), 0)
minutes, rem_seconds = divmod(eta_seconds, 60)
hours, minutes = divmod(minutes, 60)
if hours:
eta = f"{hours}h {minutes:02d}m {rem_seconds:02d}s"
elif minutes:
eta = f"{minutes:02d}m {rem_seconds:02d}s"
else:
eta = f"{rem_seconds:02d}s"
message = f"{progress} # ETA: {eta}"
return message.ljust(pad_width)
def evaluate_math500_stream(
model,
tokenizer,
device,
math_data,
out_path=None,
max_new_tokens=512,
verbose=False,
):
if out_path is None:
dev_name = str(device).replace(":", "-") # Make the filename compatible with Windows.
out_path = Path(f"math500-{dev_name}.jsonl")
num_examples = len(math_data)
num_correct = 0
start_time = time.time()
with open(out_path, "w", encoding="utf-8") as f: # Save the results for inspection.
<!-- page: 101 (printed 89) -->
for i, row in enumerate(math_data, start=1):
prompt = render_prompt(row["problem"]) # Apply the prompt template.
gen_text = generate_text_stream_concat(
model, tokenizer, prompt, device,
max_new_tokens=max_new_tokens,
verbose=verbose,
)
extracted = extract_final_candidate( # Extract and normalize gen_text # the answer.
)
is_correct = grade_answer( # Grade the answer.
extracted, row["answer"]
)
num_correct += int(is_correct)
record = { # Record to be saved for inspection
"index": i,
"problem": row["problem"],
"gtruth_answer": row["answer"],
"generated_text": gen_text,
"extracted": extracted,
"correct": bool(is_correct),
}
f.write(json.dumps(record, ensure_ascii=False) + "\n")
progress_msg = eta_progress_message(
processed=i,
total=num_examples,
start_time=start_time,
show_eta=True,
label="MATH-500",
)
print(progress_msg, end="\n", flush=True)
if verbose: # Print the responses during generation.
print(
f"\n\n{'='*50}\n{progress_msg}\n"
f"{'='*50}\nExtracted: {extracted}\n"
f"Expected: {row['answer']}\n"
f"Correct so far: {num_correct}\n{'-'*50}"
)
seconds_elapsed = time.time() - start_time
acc = num_correct / num_examples if num_examples else 0.0
print(f"\nAccuracy: {acc*100:.1f}% ({num_correct}/{num_examples})")
print(f"Total time: {seconds_elapsed/60:.1f} min")
print(f"Logs written to: {out_path}")
return num_correct, num_examples, acc

The evaluate_math500_stream function in listing 3.15 uses the same main steps as the smaller demo function from listing 3.14: for each problem, it renders the prompt, streams a model response, extracts the answer candidate, and grades it against the reference answer.

In addition to iterating over a dataset with multiple entries, it adds a few extra bells and whistles. For instance, it saves the generated responses to a JSON file in a Python dictionary-like format for record keeping and closer inspection.

Let’s now run this function on a subset: the first 10 examples of MATH-500. This takes about 0.7 minutes on a Mac Mini with an M4 chip. (Evaluating the reasoning model variant takes about 7 minutes because it generates longer responses.)

print("Model:", WHICH_MODEL)
print("Device:", device)
num_correct, num_examples, acc = evaluate_math500_stream(
model, tokenizer, device,
math_data=math_data[:10], # Only evaluate on the first 10 examples.
max_new_tokens=2048,
verbose=False
# Set to true to read the responses as they are being generated.
)

In the preceding code example, we set max_new_tokens to a generous 2,048 because the reasoning model variant, by design, tends to generate much longer responses, and we don’t want to cut it off prematurely. This leads to much longer evaluation times, and it may appear that generation is stuck. Optionally, you could set verbose=True to see the response being generated live, token by token.

The result of running evaluate_math500_stream is as follows:

Model: base
Device: mps
MATH-500: 10/10 | ETA: 00s
Accuracy: 30.0% (3/10)
Total time: 0.4 min

(As usual, the results may differ depending on whether you execute the code on a CPU, CUDA, or MPS device.)

As you can see, the model achieves a relatively low accuracy of 30%. We can open the math500_base-mps.jsonl file in a text editor to analyze the results together with the generated response. For instance, the answers have been successfully extracted in all cases, but they are simply wrong, which indicates that the model does not have very strong math-problem-solving capabilities (yet). This is expected because it is merely a base model.

The .jsonl file suffix is a convention used for JSON files with one data entry per row. You can view it in your favorite text editor. Optionally, you can load the .jsonl file created during the evaluation in Python using the following code:

dev_name = str(device).replace(":", "-")
local_path = f"math500_{WHICH_MODEL}-{dev_name}.jsonl"
<!-- page: 103 (printed 91) -->
results = []
with open(local_path, "r") as f:
for line in f:
if line.strip():
results.append(json.loads(line))

The reasoning model variant, which you can enable by setting WHICH_MODEL = “reasoning” in listing 3.1, performs much better, achieving 90% accuracy on the same 10-sample subset and 50.8% on the complete 500-sample dataset, as shown in table 3.1.

Table 3.1 MATH-500 task accuracy on different devices

ModeDeviceAccuracyMATH-500 size
BaseCPU30%10
BaseCUDA30%10
BaseMPS30%10
ReasoningCPU90%10
ReasoningCUDA90%10
ReasoningMPS80%10
BaseCUDA15.3%500
ReasoningCUDA50.8%500

As shown in table 3.1, the reasoning variant, with its longer responses, has drastically improved accuracy, but it also increases compute intensity and answer generation time substantially (from 0.4 minutes for the base model to 7 minutes for the reasoning model on a Mac Mini with an M4 chip on the 10-sample subset, and from 13.3 minutes to 185.4 minutes on an NVIDIA H100 GPU on the 500-sample dataset), which highlights one of the tradeoffs of using reasoning models. Note that these numbers were obtained in PyTorch 2.8 and can differ across PyTorch versions.

TIP The book’s code repository contains a bonus script that runs the code in this chapter in batched mode (https://github.com/rasbt/reasoning-from-scratch/blob/main/ch03/02_math500-verifier-scripts/evaluate_math500_batched.py). This means it processes multiple examples per forward pass to speed up evaluation, but it requires more RAM. Using a batch size of 128 to evaluate all 500 samples reduces the running time of the base model from 13.3 minutes to 3.3 minutes on an H100 GPU. Similarly, it reduces the running time of the reasoning model from 185.4 minutes to 14.6 minutes. Note that the H100 is used as an example here; the script is compatible with other GPUs as well.

Exercise 3.2: Calculating the average response length

Try modifying the code in this chapter to also report the average response length in the evaluate_math500_stream function (listing 3.15). Instead of modifying the function directly, you could also compute the response length from the generated JSON report files.

Exercise 3.3: Extending or changing the evaluation dataset

We chose a subset of only 10 examples for computational efficiency. You can also run the code on larger or different portions of the dataset to see whether the 10-sample subset is representative. Ideally, you could also experiment with your own data. (For reference, evaluating the base model on the complete MATH-500 dataset takes about 13.3 minutes for the base model and 185.4 minutes for the reasoning model on an H100.)

Exercise 3.4: Experimenting with different prompt templates

Models can be sensitive to different prompt templates. Experiment with different prompt templates in listing 3.13 to see how they affect the results. Also, while the Qwen3 team recommends using the base model without an additional chat template, you can enable the apply_chat_template=True setting in the tokenizer (listing 3.1) and observe whether it improves base model performance.

This concludes our implementation of a verification-based approach for math tasks (figure 3.11). I chose math because it is both natural to implement and widely used in reasoning-specific training, particularly reinforcement learning with verifiable rewards, which we’ll cover in chapter 6. The same concept can be extended to other domains, such as code; we didn’t explore that here because executing code would involve setting up a secure virtual environment.

Before we move on, it’s worth noting that evaluation also comes in many other flavors. In this chapter, we focused on verification-based accuracy for math problems because it is a popular method and because we will reuse this verifier as part of the reinforcement learning pipeline in chapters 6 and 7. For a broader overview, appendix F walks through other common evaluation strategies, such as multiple-choice benchmarks, verifiers, leaderboards, and LLM-as-judge setups. It also includes hands-on examples if you want a quick tour of how these methods work in practice.

Now that we have an evaluation framework in place, the next chapter will focus on improving reasoning capabilities through more advanced inference (text generation) techniques.

Summary

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 3.11 — A model of the topics covered in this book, showing the four stages of LLM evaluation and reasoning (printed p. 93, scan page-105.png). This chapter completed stage 2: with a working verifier and the MATH-500 benchmark in place, we can now measure the effect of the reasoning methods introduced in the chapters that follow. 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).

Summary

  • There are four main evaluation methods for LLMs: multiple choice, verifiers, leaderboards, and LLM judges.
  • Verification-based evaluation methods allow free-form answers and use external tools to check correctness.
  • This chapter focuses on verification-based evaluation by building a math verifier that extracts, normalizes, and checks answers with SymPy.
    • The verification pipeline involves several core steps, from loading the LLM to running the evaluation on a dataset. - As part of the verification pipeline, answer extraction uses string parsing to locate boxed content (with fallback mechanisms for missing boxes). - Another step implements normalization, which standardizes diverse answer formats by stripping LaTeX and converting mathematical notation.
  • Finally, the pipeline uses mathematical equivalence checking (via SymPy) to compare expressions symbolically.
  • The MATH-500 dataset provides 500 curated math problems for evaluation.
  • Prompt templates significantly impact model performance.
  • The reasoning model achieves higher accuracy than the base model, but it requires a much longer running time.