Appendix F: Common approaches to model evaluation
local graph
Appendix F: Common approaches to model evaluation
Section titled “Appendix F: Common approaches to model evaluation”appendix F Common approaches to model evaluation
F.1 Understanding the main evaluation methods for LLMs
Section titled “F.1 Understanding the main evaluation methods for LLMs”There are four common ways of evaluating trained LLMs in practice: multiple choice, verifiers, leaderboards, and LLM judges, as shown in figure F.1. Research papers, marketing materials, technical reports, and model cards (a term for LLM-specific technical reports) often include results from two or more of these categories.
As you can see in figure F.1, the four evaluation categories introduced here fall into two groups: benchmark-based evaluation and judgment-based evaluation. Other measures, such as training loss, perplexity, and rewards, are typically used internally during model development. They are covered in the model-training chapters (chapters 6 to 8).
F.2 Evaluating answer-choice accuracy
Section titled “F.2 Evaluating answer-choice accuracy”Historically, one of the most widely used evaluation methods has been multiple-choice benchmarks such as MMLU (short for Massive Multitask Language Understanding, https://huggingface.co/datasets/cais/mmlu).
Figure F.2 shows a single example from the MMLU dataset. The complete MMLU dataset consists of 57 subjects (from high school math to biology) and about 16 thousand multiple-choice questions in total. Performance is measured in terms of accuracy (the fraction of correctly answered questions); for example, the score would be 87.5% if 14,000 out of 16,000 questions are answered correctly.
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 F.1 — A model of the topics covered in this book, with a focus on the two broad evaluation categories covered in this appendix: benchmark-based evaluation and judgment-based evaluation (printed p. 378, scan page-390.png). Stage 2 is highlighted. As in figure 3.1, the two evaluation substeps fan out into four leaf methods, with Multiple choice marked “The next section covers multiple-choice question answering”:
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).
graph BT
I["Input text from the MMLU dataset:<br/>'How many ways are there to put 4<br/>distinguishable balls into 2 indistinguishable<br/>boxes?<br/>A. 7 B. 11 C. 16 D. 8<br/>Answer:'"] --> L["LLM"]
L --> P["LLM-generated answer text ('prediction'): 'D'"]
R["The correct answer from the MMLU dataset<br/>(not shown to the LLM): 'D'"] --> C{"Compare the given<br/>solution to the<br/>LLM prediction"}
P --> C
[!visual-conversion] Figure F.2 — Evaluating an LLM on MMLU by comparing its multiple-choice prediction with the correct answer from the dataset (printed p. 378, scan page-390.png). Print annotation on the model: “A pretrained LLM that can follow basic instructions and generate text.”
Multiple-choice benchmarks, such as MMLU, test an LLM’s knowledge recall in a straightforward, quantifiable way similar to standardized tests, many school exams, or theoretical driving tests.
Note that figure F.2 shows a simplified version of multiple-choice evaluation, where the model’s predicted answer letter is compared directly to the correct one. Other popular methods use log-probability scoring (log probabilities are discussed in more detail in chapter 4).
The following subsections illustrate how the MMLU scoring shown in figure F.2 can be implemented in code. End-to-end MMLU scripts, including the different scoring variants, will be provided as bonus materials in this book’s code repository.
F2.1 Loading the model
Before we can evaluate the model on MMLU, we have to load the pretrained model. The following code is identical to listing 3.1.
Listing F.1 Loading a pretrained model
from pathlib import Pathimport torchfrom reasoning_from_scratch.ch02 import get_devicefrom reasoning_from_scratch.qwen3 import ( download_qwen3_small, Qwen3Tokenizer, Qwen3Model, QWEN_CONFIG_06_B)device = get_device()torch.set_float32_matmul_precision("high") # Lower precision from "highest" to enable Tensor Cores if applicable# device = "cpu" # Uncomment this line if you have compatibility issues with your device.WHICH_MODEL = "base" # Uses the base model, similar to chapter 2, by defaultif WHICH_MODEL == "base": download_qwen3_small( kind="base", tokenizer_only=False, out_dir="qwen3" ) tokenizer_path = Path("qwen3") / "tokenizer-base.json" model_path = Path("qwen3") / "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="qwen3" ) tokenizer_path = Path("qwen3") / "tokenizer-reasoning.json" model_path = Path("qwen3") / "qwen3-0.6B-reasoning.pth" tokenizer = Qwen3Tokenizer( tokenizer_file_path=tokenizer_path, apply_chat_template=True, add_generation_prompt=True, add_thinking=True, )
<!-- page: 392 (printed 380) -->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) # Optionally set to true to enable model compilation.USE_COMPILE = Falseif USE_COMPILE: torch._dynamo.config.allow_unspec_int_on_nn_module = True model = torch.compile(model)F.2.2 Checking the generated answer letter
Section titled “F.2.2 Checking the generated answer letter”Now we’ll implement the simplest and perhaps most intuitive MMLU scoring method, which relies on checking whether a generated multiple-choice answer letter matches the correct answer. This is similar to what was illustrated in figure F.2.
We will work with an example from the MMLU dataset:
example = { "question": ( "How many ways are there to put 4 distinguishable" " balls into 2 indistinguishable boxes?" ), "choices": ["7", "11", "16", "8"], "answer": "D",}Next, we’ll define a function to format the LLM prompts.
Listing F.2 Formatting the LLM prompt
def format_prompt(example): return ( f"{example['question']}\n" f"A. {example['choices'][0]}\n" f"B. {example['choices'][1]}\n" f"C. {example['choices'][2]}\n" f"D. {example['choices'][3]}\n" "Answer: " )The trailing space encourages a single-letter next token.
Let’s execute the function on the MMLU example to get an idea of what the formatted LLM input looks like:
prompt = format_prompt(example) print(prompt)The output is as follows:
How many ways are there to put 4 distinguishable balls into 2 indistinguishable boxes?
A. 7 B. 11 C. 16 D. 8 Answer:
The preceding model prompt provides the model with a list of answer choices, and it ends with an “Answer: ” text that encourages the model to generate the correct answer.
While this is not strictly necessary, it can sometimes be helpful to provide additional questions along with the correct answers as input so that the model can observe how it is expected to solve the task. (For example, cases where five examples are provided are known as 5-shot MMLU.) However, for current generations of LLMs, in which even the base models are quite capable, this is not required.
Loading different MMLU samples
You can load examples from the MMLU dataset directly from the datasets library (which can be installed with pip install datasets or uv add datasets):
from datasets import load_datasetconfigs = get_dataset_config_names("cais/mmlu")dataset = load_dataset("cais/mmlu", "high_school_mathematics")
example = dataset["test"][0]print(example)Here we used the “high_school_mathematics” subset. To get a list of the other subsets, use the following code:
from datasets import get_dataset_config_namessubsets = get_dataset_config_names("cais/mmlu")print(subsets)Next, we’ll tokenize the prompt and wrap it in a PyTorch tensor object as input to the LLM (similar to what we did in chapter 2):
prompt_ids = tokenizer.encode(prompt)prompt_fmt = torch.tensor(prompt_ids, device=device).unsqueeze(0)Now we’ll define the main scoring function, which generates a few tokens (eight by default) and extracts the first instance of the letter A, B, C, or D that the model prints.
Listing F.3 Extracting the generated letter
from reasoning_from_scratch.ch02 import ( generate_text_basic_stream_cache)
def predict_choice(
<!-- page: 394 (printed 382) --> model, tokenizer, prompt_fmt, max_new_tokens=8): pred = None for t in generate_text_basic_stream_cache( model=model, token_ids=prompt_fmt, max_new_tokens=max_new_tokens, eos_token_id=tokenizer.eos_token_id, ): answer = tokenizer.decode(t.squeeze(0).tolist()) for letter in answer: letter = letter.upper() if letter in "ABCD": pred = letter break if pred: breakreturn predWe can now check the generated letter using the function from listing F.3:
pred1 = predict_choice(model, tokenizer, prompt_fmt)print( f"Generated letter: {pred1}\n" f"Correct? {pred1 == example['answer']}")This is the result:
Generated letter: C Correct? False
As you can see, the generated answer is incorrect (False) in this case.
Multiple-choice answer formats This section implements a simplified version of multiple-choice evaluation for illustration purposes, where the model’s predicted answer letter is compared directly with the correct one. In practice, more widely used variations exist, such as log-probability scoring, where we measure how likely the model considers each candidate answer rather than just checking the final letter choice. (Probability-based scoring is discussed in chapter 5.) For reasoning models, evaluation can also involve assessing the likelihood of generating the correct answer when it is provided as input.
Regardless of the variant, evaluation still amounts to checking whether the model selects correctly from the predefined answer options. Examples of these variations are included in the code repository as optional bonus material.
A limitation of multiple-choice benchmarks like MMLU is that they only measure an LLM’s ability to select from predefined options and thus are not very useful for evaluating reasoning capabilities beyond checking whether, and how much, knowledge the model has forgotten compared to the base model. They do not capture free-form writing ability or real-world utility. Still, they remain a simple and useful diagnostic: a high MMLU score doesn’t necessarily mean the model is strong in practical use, but a low score can highlight potential knowledge gaps.
3 Using verifiers to check answers
Related to the multiple-choice question answering that was discussed in the previous section, verification-based approaches quantify LLM capabilities with an accuracy metric. But unlike multiple-choice benchmarks, verification methods allow LLMs to provide a free-form answer. We then extract the relevant portion of the answer and use a verifier to compare it with the correct answer provided in the dataset, as illustrated in figure F.3.
graph BT
I["Input text without predefined answer choices:<br/>'Answer the question and write the final<br/>result on a new line as: \\boxed{ANSWER}<br/>Question: How many ways are there to put 4<br/>distinguishable balls into 2 indistinguishable<br/>boxes?<br/>Answer:'"] --> L["LLM"]
L --> O["LLM-generated answer text:<br/>'We want to distribute 4 distinguishable balls into 2 indistinguishable boxes.<br/>### Step 1: Count with distinguishable boxes ...<br/>So total = (1 + 7 − 8).<br/>### Final Answer: \\boxed{8}'"]
O --> E["The extracted answer: '8'"]
R["The correct answer provided in the dataset: '8'"] --> V{"Verify answer"}
E --> V
[!visual-conversion] Figure F.3 — Evaluating an LLM with a verification-based method in free-form question answering (printed p. 383, scan page-395.png). The model generates a free-form answer (which may include multiple steps) and a final boxed answer, which is extracted and compared against the correct answer from the dataset. Print annotation: “Question-answer pair from a benchmark dataset” spanning the input and reference answer.
When we compare the extracted answer with the provided answer, as shown in figure F.3, we can use external tools such as code interpreters or calculator software.
The downside is that this method can only be applied 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 this method allows us to generate an unlimited number of math problem variations programmatically and it benefits from step-by-step reasoning, it has become a cornerstone of reasoning model evaluation and development. An extensive example of this method is provided in chapter 3, so we’ll skip a code demonstration here.
F.4 Comparing models using preferences and leaderboards
Section titled “F.4 Comparing models using preferences and leaderboards”So far, we’ve covered two methods that offer easily quantifiable metrics such as model accuracy. But none of the methods discussed so far evaluate LLMs in a more holistic way, including the style of the responses. In this section, as illustrated in figure F.4, we’ll discuss a judgment-based method: LLM leaderboards.
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 F.4 — A model of the topics covered in this book, with a focus on the judgment- and benchmark-based evaluation methods covered in this appendix (printed p. 384, scan page-396.png). Having already covered benchmark-based approaches in the previous sections (multiple choice and verifiers), we’ll now introduce judgment-based approaches for measuring LLM performance, with this section focusing on leaderboards. In the print, Multiple choice and Verifiers are ticked and Leaderboards is marked:
graph TD B1["Benchmark-based evaluation"] --> M1["Multiple choice - done"] B1 --> M2["Verifiers - done"] B2["Judgment-based evaluation"] --> M3["Leaderboards - this section"] B2 --> M4["LLM judges"]Print annotations: “The two benchmark-based evaluation methods that we discussed in the previous sections” and “There are two judgment-based evaluation methods; this section focuses on leaderboards.” 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).
The leaderboard method is a judgment-based approach in which models are ranked not by accuracy values or other fixed benchmark scores but by user (or another LLM’s) preferences regarding their outputs. A popular leaderboard is Arena (formerly Chatbot Arena, https://arena.ai/leaderboard/text), where users compare responses from two models, either user-selected or anonymous, and vote for the one they prefer, as shown in figure F.5.

Figure F.5 Example of a judgment-based leaderboard interface (Arena). Two LLMs are given the same prompt, their responses are shown side by side, and users vote for their preferred answer. (Crop from scan page-397.png, printed p. 385. Embedded rather than recreated: the figure is a dense browser screenshot whose two side-by-side response panels and voting bar would not survive translation to Mermaid or ASCII.)
These preference votes, which are collected as shown in figure F.5, are then aggregated across all users into a leaderboard that ranks different models by user preference. In the remainder of this section, we’ll implement a simple example of a leaderboard.
Let’s consider users prompting different LLMs in a setup similar to figure F.5. The following list represents pairwise votes where the first model is the winner:
votes = [ ("GPT-5", "Claude-3"), ("GPT-5", "Llama-4"), ("Claude-3", "Llama-3"), ("Llama-4", "Llama-3"), ("Claude-3", "Llama-3"), ("GPT-5", "Llama-3"), ]In this list, each tuple in the votes list represents a pairwise preference between two models, written as (winner, loser). So (“GPT-5”, “Claude-3”) means that a user preferred GPT-5’s answer over a Claude-3 model answer.
In the remainder of this section, we’ll turn the votes list into a leaderboard. We’ll use the popular Elo rating system, which was originally developed for ranking chess players. Each model will start with a baseline score. Then, after each comparison and preference vote, the model’s rating will be updated. If a user prefers the current model over a highly ranked model, the current model will receive a relatively large rating update and move higher in the leaderboard. Conversely, if the current model wins against a low-ranked model, its rating increases only a little. (If the current model loses, it is updated in a similar way, but ranking points are subtracted instead of added.)
The following listing shows the code to turn these pairwise rankings into a leaderboard.
Listing F.4 Constructing a leaderboard
def elo_ratings(vote_pairs, k_factor=32, initial_rating=1000): ratings = { model: initial_rating for pair in vote_pairs for model in pair }
for winner, loser in vote_pairs: expected_winner = 1.0 / ( 1.0 + 10 ** ((ratings[loser] - ratings[winner]) / 400.0) )
ratings[winner] = ( ratings[winner] + k_factor * (1 - expected_winner) ) ratings[loser] = ( ratings[loser] + k_factor * (0 - (1 - expected_winner)) )
return ratingsThe elo_ratings function in listing F.4 takes votes as input and turns it into a leaderboard, as follows:
ratings = elo_ratings(votes, k_factor=32, initial_rating=1000)for model in sorted(ratings, key=ratings.get, reverse=True): print(f"{model:8s} : {ratings[model]:.1f}")This results in the following leaderboard ranking, where the higher the score is, the better:
GPT-5 : 1043.7 Claude-3 : 1015.2 Llama-4 : 1000.7 Llama-3 : 940.4
So how does this work? For each pair, we compute the expected score of the winner using the following formula:
expected_winner = 1 / (1 + 10 ** ((rating_loser - rating_winner) / 400))The expected_winner value is the model’s predicted chance to win in a no-draw setting based on the current ratings. It determines how large the rating update is.
Each model starts at initial_rating = 1000. If the winner and loser’s ratings are equal, we have expected_winner = 0.5, which indicates an even match. In this case, the updates are as follows:
rating_winner + k_factor * (1 - 0.5) = rating_winner + 16 rating_loser + k_factor * (0 - (1 - 0.5)) = rating_loser - 16
If a heavy favorite (a model with a high rating) wins, we have expected_winner ≈ 1. The favorite gains only a small amount and the loser loses only a little:
rating_winner + 32 * (1 - 0.99) = rating_winner + 0.32 rating_loser + 32 * (0 - (1 - 0.99)) = rating_loser - 0.32
But if an underdog (a model with a low rating) wins, we have expected_winner ≈ 0, and the winner gets almost the full k_factor points, while the loser loses about the same number of points:
rating_winner + 32 * (1 - 0.01) = rating_winner + 31.68 rating_loser + 32 * (0 - (1 - 0.01)) = rating_loser - 31.68
Order matters
The Elo approach updates ratings after each match (model comparisons), so later results build on ratings that have already been updated. This means the same set (continued) of outcomes, when presented in a different order, can end with slightly different final scores. This effect is usually mild, but it can happen, especially when an upset happens earlier rather than later.
To reduce this order effect, we can shuffle the votes pairs, run the elo_ratings function multiple times, and average the resulting ratings.
Leaderboard approaches such as the one described here provide a more dynamic view of model quality than static benchmark scores. But the results can be influenced by user demographics, prompt selection, and voting biases. Benchmarks and leaderboards can also be gamed, and users may select responses based on style rather than correctness. Finally, compared to automated benchmark harnesses, leaderboards do not provide instant feedback on newly developed variants, which makes them harder to use during active model development.
Other ranking methods Arena originally used the Elo method described in this section, but it has recently transitioned to a statistical approach based on the Bradley–Terry model. The main advantage of the Bradley–Terry model is that, because it is statistically grounded, it allows for the construction of confidence intervals to express uncertainty in the rankings. In contrast to Elo ratings, the Bradley–Terry model also estimates all ratings jointly using a statistical fit over the entire dataset, which makes it immune to order effects.
To keep the reported scores in a familiar range, the Bradley–Terry model is fitted to produce values comparable to Elo. Even though the leaderboard no longer officially uses Elo ratings, the term “Elo” remains widely used by LLM researchers and practitioners when comparing models. A code example showing the Elo rating is included in this book’s bonus materials at https://github.com/rasbt/reasoning-from-scratch/ tree/main/chF/03_leaderboards.
F.5 Judging responses with other LLMs
Section titled “F.5 Judging responses with other LLMs”In the early days, LLMs were evaluated using statistical and heuristics-based methods, including a measure called BLEU, which crudely measures how well generated text matches reference text. The problem with such metrics is that they require exact word matches and don’t account for synonyms, word substitutions, and so on.
One solution to this problem, if we want to judge the written answer text as a whole, is to use relative rankings and leaderboard-based approaches, as discussed in the previous section. But a downside of leaderboards is the subjective nature of preference-based comparisons because they involve human feedback, and there are the challenges of collecting that feedback.
A related method is to use another LLM with a predefined grading rubric (that is, an evaluation guide) to compare an LLM’s response with a reference response and judge the response quality based on that rubric, as illustrated in figure F.6.

Figure F.6 Example of an LLM-judge evaluation. The model to be evaluated generates an answer, which is then scored by a separate judge LLM according to a rubric and a provided reference answer. (Crop from scan page-401.png, printed p. 389. Embedded rather than recreated: the figure overlays annotated callouts on a live chat-interface screenshot.) Figure F.6 Example of an LLM-judge evaluation. The model to be evaluated generates an answer, which is then scored by a separate judge LLM according to a rubric and a provided reference answer.
In practice, the judge-based approach shown in figure F.6 works well when the judge LLM is strong. Common setups use leading proprietary LLMs via API, though specialized judge models also exist (see appendix A for references). One reason judges work so well is that evaluating an answer is often easier than generating one.
To implement a judge-based model evaluation programmatically in Python, we could load one of the Qwen3 models (discussed in appendix D) and prompt it with a grading rubric and the model answer we want to evaluate. Alternatively, we can use other LLMs through an API, such as the ChatGPT or Ollama API.
In the remainder of this section, we’ll implement the judge-based evaluation shown in figure F.6 using the Ollama API in Python. Specifically, we will use the 20-billion-parameter gpt-oss open-weight model by OpenAI because it offers a good balance between capability and efficiency. For more information about gpt-oss, please see my “From GPT-2 to gpt-oss: Analyzing the Architectural Advances” article at https://magazine.sebastianraschka.com/p/from-gpt-2-to-gpt-oss-analyzing-the.
F.5.1 Implementing the LLM-as-a-judge approach in Ollama
Section titled “F.5.1 Implementing the LLM-as-a-judge approach in Ollama”Ollama (https://ollama.com) is an efficient open source application for running LLMs on a laptop. It serves as a wrapper around the open source llama.cpp library (https://github.com/ggerganov/llama.cpp), which implements LLMs in pure C/C++ for maximum efficiency. However, Ollama is only a tool for generating text with LLMs (inference); it does not support training or fine-tuning LLMs.
To execute the following code, install Ollama by visiting https://ollama.com and follow the instructions for your operating system:
- For macOS and Windows users: Open the downloaded Ollama application. If prompted to install command-line support, select “Yes.”
- For Linux users: Use the installation command available on the Ollama website.
Before implementing the model evaluation code, let’s first download the gpt-oss model and verify that Ollama is functioning correctly from the command-line terminal. Execute the following command on the command line (not in a Python session):
ollama run gpt-oss:20b
The first time you execute this command, the 20-billion-parameter gpt-oss model, which takes up 14 GB of storage space, will automatically be downloaded. The output is as follows:
$ ollama run gpt-oss:20bpulling manifestpulling b112e727c6f1: 100% 13 GBpulling fa6718a93d78: 100% 7.2 KBpulling f60356777647: 100% 11 KBpulling d8ba2f9a17b3: 100% 18 Bpulling 55c108d8e936: 100% 489 Bverifying sha256 digestwriting manifestremoving unused layerssuccessAlternative Ollama models
Section titled “Alternative Ollama models”Note that the gpt-oss:20b in the ollama run gpt-oss:20b command refers to the 20-billion-parameter gpt-oss model. Using Ollama with the gpt-oss:20b model requires approximately 13 GB of RAM. If your machine does not have enough RAM, you can try a smaller model, such as the 4-billion-parameter qwen3:4b model via ollama run qwen3:4b, which requires only around 4 GB of RAM.
For more powerful computers, you can also use the larger 120-billion-parameter gpt-oss model by replacing gpt-oss:20b with gpt-oss:120b. But keep in mind that this model requires significantly more computational resources.
Once the model download is complete, you will be presented with a command-line interface that allows you to interact with the model. For example, try asking the model, “What is 1+2?”:
>>> What is 1+2?Thinking...User asks: "What is 1+2?" This is simple: answer 3. Provide explanation?Possibly ask for simple arithmetic. Provide answer: 3....done thinking.
1 + 2 = **3**You can end this Ollama session using the input /bye.
In the remainder of this section, we’ll use the Ollama API. This approach requires that Ollama is running in the background. There are three options for doing this:
-
Run the ollama serve command in the terminal (recommended). This runs the Ollama backend as a server, usually on http://localhost:11434. Note that it doesn’t load a model until it’s called through the API (later in this section).
-
Run the ollama run gpt-oss:20b command, as you did earlier, but keep it open and don’t exit the session via /bye. As discussed earlier, this opens a minimal convenience wrapper around a local Ollama server. Behind the scenes, it uses the same server API as ollama serve.
-
Open the Ollama desktop app to run the same backend automatically, which provides a graphical interface on top, as shown earlier in figure F.6.
Ollama server IP address
Section titled “Ollama server IP address”Ollama runs locally on your machine by starting a local server-like process. When you run ollama serve in the terminal, you may encounter an error message saying Error: listen tcp 127.0.0.1:11434: bind: address already in use.
(continued) If that’s the case, try using the command OLLAMA_HOST=127.0.0.1:11435 ollama serve (and if this address is also in use, increment the numbers by one until you find an address that isn’t in use).
The following code verifies that the Ollama session is running properly.
Listing F.5 Checking Ollama is running
import psutil
def check_if_running(process_name): running = False for proc in psutil.process_iter(["name"]): if process_name in proc.info["name"]: running = True break return running
ollama_running = check_if_running("ollama")
if not ollama_running: raise RuntimeError( "Ollama not running. Launch ollama before proceeding." )
print("Ollama running:", check_if_running("ollama"))Ensure that the output from executing the previous code displays Ollama running: True. If it shows False, verify that the ollama serve command or the Ollama application is running.
In the remainder of this appendix, we’ll interact with the local gpt-oss model through the Ollama REST API using Python. The following query_model function shows how to use the API.
Listing F.6 Querying a local Ollama model
import jsonimport requests
def query_model( prompt, model="gpt-oss:20b", url="http://localhost:11434/api/chat"): data = { "model": model, "messages": [ {"role": "user", "content": prompt}
<!-- page: 405 (printed 393) --> ], "options": { "seed": 123, "temperature": 0, "num_ctx": 2048}}with requests.post(url, json=data, stream=True, timeout=30) as r: r.raise_for_status() response_data = "" for line in r.iter_lines(decode_unicode=True): if not line: continue response_json = json.loads(line) if "message" in response_json: response_data += response_json["message"]["content"]
return response_dataIterate over each streamed line from the response.
Here’s an example of how to use the query_model function from listing F.6:
ollama_model = "gpt-oss:20b"result = query_model("What is 1+2?", ollama_model)print(result)The resulting response is “3”. (It differs from what we’d get if we ran ollama run or the Ollama application due to different default settings.)
F.5.2 Evaluating responses with a grading rubric
Section titled “F.5.2 Evaluating responses with a grading rubric”Using the query_model function, we can evaluate the responses generated by our model with a prompt that includes a grading rubric that asks the gpt-oss model to rate the target model’s responses on a scale of 1 to 5, using a correct answer as a reference. The prompt we use for this is shown in the following listing.
Listing F.7 Setting up the prompt template including the grading rubric
def rubric_prompt(instruction, reference_answer, model_answer): rubric = ( "You are a fair judge assistant. You will be given an instruction, " "a reference answer, and a candidate answer to evaluate, according " "to the following rubric:\n\n" "1: The response fails to address the instruction, providing " "irrelevant, incorrect, or excessively verbose content.\n"
"2: The response partially addresses the instruction but contains " "major errors, omissions, or irrelevant details.\n" "3: The response addresses the instruction to some degree but is " "incomplete, partially correct, or unclear in places.\n" "4: The response mostly adheres to the instruction, with only " "minor errors, omissions, or lack of clarity.\n" "5: The response fully adheres to the instruction, providing a " "clear, accurate, and relevant answer in a concise and efficient " "manner.\n\n" "Now here is the instruction, the reference answer, and the " "response.\n"
)prompt = ( f"{rubric}\n" f"Instruction:\n{instruction}\n\n" f"Reference Answer:\n{reference_answer}\n\n" f"Answer:\n{model_answer}\n\n" f"Evaluation: ")return promptThe model_answer in the rubric_prompt is intended to represent the response produced by our own model in practice. For illustration, I’ve hardcoded a plausible model answer here rather than generating it dynamically. Feel free to use the Qwen3 model we loaded in section F.2.1 to generate a real model_answer.
Next, let’s generate the rendered prompt for the Ollama model:
rendered_prompt = rubric_prompt( instruction=( "If all birds can fly, and a penguin is a bird, " "can a penguin fly?" ), reference_answer=( "Yes, according to the premise that all birds can fly, " "a penguin can fly." ), model_answer=( "Yes - under those premises a penguin would be able to fly." ))print(rendered_prompt)The output is as follows:
You are a fair judge assistant. You will be given an instruction, a reference answer, and a candidate answer to evaluate, according to the following rubric:
1: The response fails to address the instruction, providing irrelevant, incorrect, or excessively verbose content. 2: The response partially addresses the instruction but contains major errors, omissions, or irrelevant details.
3: The response addresses the instruction to some degree but is incomplete, partially correct, or unclear in places. 4: The response mostly adheres to the instruction, with only minor errors, omissions, or lack of clarity. 5: The response fully adheres to the instruction, providing a clear, accurate, and relevant answer in a concise and efficient manner.
Now here is the instruction, the reference answer, and the response.
Instruction: If all birds can fly, and a penguin is a bird, can a penguin fly?
Reference Answer: Yes, according to the premise that all birds can fly, a penguin can fly.
Answer: Yes – under those premises a penguin would be able to fly.
Evaluation:
Ending the prompt with “Evaluation: ” incentivizes the model to generate the answer. Let’s see how the gpt-oss:20b model judges the response:
result = query_model(rendered_prompt, ollama_model) print(result)The response is as follows:
Score: 5
The candidate answer directly addresses the question, correctly applies the given premises, and concisely states that a penguin would be able to fly. It is accurate, relevant, and clear.
As you can see, the answer receives the highest score, which is reasonable because it is indeed correct.
This was a simple example of stepping through the process manually. We could take this idea further and implement a for loop that iteratively queries the model (such as the Qwen3 model from chapter 2 that we loaded in section F.2.1) with questions from an evaluation dataset, evaluates it via gpt-oss, and calculates the average score. By doing this for two models (such as the Qwen3 base and reasoning models), we could compare the models to each other.
Scoring intermediate reasoning steps with process reward models
In addition to symbolic verifiers and LLM judges, there is a class of learned models called process reward models (PRMs). Like judges, PRMs can evaluate reasoning traces beyond just the final answer, but unlike general judges, they focus specifically (continued) on the intermediate steps of reasoning. Unlike verifiers, which check correctness symbolically and usually only at the outcome level, PRMs provide step-by-step reward signals during reinforcement learning training. We can categorize PRMs as “step-level judges,” which are predominantly developed for training rather than for pure evaluation. (In practice, PRMs are difficult to train reliably at scale. For example, DeepSeek R1 did not adopt PRMs and instead combined verifiers for reasoning training.)
Judge-based evaluations offer advantages over preference-based leaderboards, including scalability and consistency, because they do not rely on large pools of human voters. However, while leaderboards are usually based on human preference rankings, it is technically possible to outsource the preference-based rating behind these leaderboards to LLMs. Either way, LLM judges share weaknesses with human voters: results can be biased by model preferences, prompt design, and answer style. There is also a strong dependency on the choice of judge model and rubric, and they lack the reproducibility of fixed benchmarks.