Test-time compute and small language models
local graph
Chapter 15 — Test-time compute and small language models
Section titled “Chapter 15 — Test-time compute and small language models”15 Test-time compute and small language models
This chapter covers
- Defining test-time compute
- Using the OptiLLM inference proxy for test-time compute with large and small language models
- Embedding test-time compute with open source SLMs
- Tuning an SLM to reason through GRPO for a specific domain
This chapter introduces the concept of test-time compute, and it surveys state-of-the-art SLMs and libraries. It also provides a complete commodity-hardware example, showing how you can apply the Group Relative Policy Optimization (GRPO) technique used to train the DeepSeek-R1 models to specialize an SLM for a given domain.
15.1 Test-time compute
Section titled “15.1 Test-time compute”Test-time compute (TTC) is a new concept for LLMs—it emerged in 2024 and refers to the computational resources a model uses at inference time to generate responses, allowing it to “think” further and spend more time exploring alternatives before answering. The idea is especially useful for difficult tasks where even large models can struggle, such as math, logic, and coding. With TTC, a model can dynamically increase its “reasoning” time during inference, using search methods such as beam search or tree-based exploration (like Monte Carlo tree search) to explore multiple candidate outputs within a compute budget. It can then score those candidates and pick the best one or even execute generated code and check for errors. The tradeoff is simple: more “thinking” time can improve accuracy, but it increases compute costs.
Recent commercial models from OpenAI and Anthropic appear to use this approach: on challenging queries, they pause longer before producing a final response, likely because they generate multiple candidates and run evaluations to select the best one. Vendors often market this as “reasoning,” but it is better understood as spending more compute and time on additional statistical processing. While this will not lead us to artificial general intelligence, it can improve performance on tasks where a single static inference pass is not enough.
NOTE Artificial general intelligence (AGI) is a hypothetical stage in the development of machine learning in which a model can match or exceed the cognitive abilities of human beings across any task.
This paradigm offers several potential benefits:
- Enhanced accuracy and more reliable answers
- Better adaptability to new data and contexts
- Reduced overfitting because we rely less on static pretrained knowledge that may be outdated or biased
However, using this strategy on large commercial models comes with some risks:
- Shifting more compute to inference could raise costs for subscribers—the big companies that own the models and infrastructure can raise fees or change plans to cover maintenance. We often assume the API is backed by coordinated hardware that lets GPU or TPU capacity scale up and down with demand, but we don’t actually know because we don’t own that infrastructure.
- In closed-source models, the “thinking” steps (or, more accurately, the “refining process”) are hidden from end users. We cannot access logs showing the model’s intermediate answers, which search algorithms it used, or what code it generated for a task. For validation, especially in regulated industries, this poses a significant problem.
This is the direction that large commercial models will continue to follow. But what about SLMs? For domain-specific tasks, small models specialized on domain data or prompted with up-to-date context (as in a RAG system) can outperform larger models on the same tasks. Could we implement TTC for these SLMs and further boost performance on tasks that require more reasoning? This chapter explores these questions.
15.2 The OptiLLM inference proxy
Section titled “15.2 The OptiLLM inference proxy”OpenAI’s o1, its first reflective GPT model, was previewed in September 2024 and released to ChatGPT users that December. By then, many commercial LLMs (from OpenAI and other vendors) and many open source models, large and small, were widely available, but they relied on static inference. This highlighted the need for a way to bring TTC to open source models as well.
That need sparked Asankhaya Sharma, a seasoned cybersecurity expert and tech lead, to create an open source project called OptiLLM (https://github.com/codelion/optillm). OptiLLM is an OpenAI API–compatible inference-optimizing proxy that implements several state-of-the-art techniques to improve LLM accuracy and performance, especially for coding, logical, and mathematical queries.
NOTE I’m a contributor to this open source project, but I also use it in real-world projects, so I have been able to validate the pros and cons of this approach.
The OptiLLM proxy sits between clients and an OpenAI API–compatible service (such as OpenAI, Azure OpenAI, Cerebras, or LiteLLM). As shown in figure 15.1, the high-level flow of requests and responses is as follows:
graph LR
U(["User request via OpenAI client"])
P["OptiLLM proxy<br/>python optillm.py --base_url=http://..."]
S(["Any OpenAI API-compatible service"])
U -->|"/v1/chat/completions (slug-model-name)"| P
P -->|"/v1/chat/completions (model-name)<br/>multiple calls to base model"| S
S -->|Response| P
P -->|Final Response| U
[!visual-conversion] Figure 15.1 — The flow of requests and responses through the OptiLLM proxy (p. 342)
-
A user submits a prompt through a client application, which sends a request to the model’s API. You use the OpenAI SDK to implement the request logic, just as you would for direct calls to the third-party API. The only difference is that the request can include an extra parameter specifying which algorithm to use to refine the model’s answers.
-
The request arrives at the OptiLLM proxy service (layer B in the figure), which forwards it to the OpenAI API-compatible service (layer C), which performs static inference.
-
The proxy iterates for a set number of times, making multiple calls to the service API and applying the selected algorithm and conditions to the responses from static inference. It sends the final response to the client application only after the refinement cycle completes.
OptiLLM also supports local inference. You can load Hugging Face-hosted pretrained models and LoRA weights directly or run the OptiLLM proxy against an external server such as llama.cpp or Ollama. However, these servers currently can’t sample multiple responses from a model, limiting the number of approaches available in OptiLLM out of the box.
Table 15.1 lists the techniques implemented in the OptiLLM solution.
Table 15.1 Reflective techniques available out-of-the-box in OptiLLM
| Approach | ID | Description | External local server |
|---|---|---|---|
| Cerebras Planning and Optimization | cepo | A combination of Best of N, Chain-of-Thought, Self-Reflection, Self-Improvement, and various prompting techniques | Not supported |
| CoT with Reflection | cot_reflection | Implements chain-of-thought reasoning with <thinking>, <reflection>, and <output> sections | Supported |
| PlanSearch | plansearch | Implements a search algorithm over candidate plans for solving a problem in natural language | Supported |
| ReRead | re2 | Implements rereading to improve reasoning by processing queries twice | Supported |
| Self-Consistency | self_consistency | Implements an advanced self-consistency method | Supported |
| Z3 Solver | z3 | Utilizes the Z3 theorem prover for logical reasoning | Supported |
| R* Algorithm | rstar | Implements the R* algorithm for problem-solving | Supported |
| LEAP | leap | Learns task-specific principles from few-shot examples | Supported |
Table 15.1 Reflective techniques available out-of-the-box in OptiLLM (continued)
| Approach | ID | Description | External local server |
|---|---|---|---|
| Round Trip Optimization | rto | Optimizes responses through a round-trip process | Supported |
| Best of N Sampling | bon | Generates multiple responses and selects the best one | Not supported |
| Mixture of Agents | moa | Combines responses from multiple critiques | Not supported |
| Monte Carlo Tree Search | mcts | Uses MCTS for decision-making in chat responses | Not supported |
| PV Game | pvg | Applies a prover-verifier game approach at inference time | Not supported |
| CoT Decoding | N/A | Implements chain-of-thought decoding to elicit reasoning without explicit prompting | External local server/model only |
| Entropy Decoding | N/A | Implements adaptive sampling based on the uncertainty of tokens during generation | External local server/model only |
| Thinkdeeper | N/A | Implements the reasoning_effort param from OpenAI for reasoning models like DeepSeek R1 | External local server/model only |
| AutoThink | N/A | Combines query complexity classification with steering vectors to enhance reasoning | External local server/model only |
Let’s learn more about the details and get hands-on with OptiLLM and SLMs. You can download a model and its tokenizer in the usual way with the Transformers library:
import torchfrom transformers import AutoModelForCausalLM, AutoTokenizer
model_id = "Qwen/Qwen2.5-0.5B-Instruct"model = AutoModelForCausalLM.from_pretrained(model_id)tokenizer = AutoTokenizer.from_pretrained(model_id)Next, we’ll define a prompt that requires reasoning:
messages = [ {"role": "user", "content": "In a dance class of 20 students, 20% enrolled in contemporary dance, 25% of the remaining enrolled in jazz dance, and the rest enrolled in hip-hop dance. What percentage of the entire students enrolled in hip-hop dance?"}]We can select and run one of the approaches in table 15.1 for local models, such as Thinkdeeper
from optillm.thinkdeeper import thinkdeeper_decode
result = thinkdeeper_decode(model, tokenizer, messages, {"do_sample": True, "temperature": 0.1, "max_new_tokens": 1024})print(f"ThinkDeeper Decoding:\n {result}")or CoT Decoding
from optillm.cot_decoding import cot_decode
result, confidence = cot_decode(model, tokenizer, messages, aggregate_paths=True, temperature=0.1, max_new_tokens=1024)print(f"CoT Decoding:\n {result}")and wait for the model to “think” and return the final answer. OptiLLM provides a dedicated function for each supported technique for local models. These functions take the model, its tokenizer, a prompt, and a set of sampling parameters.
Let’s evaluate a local SLM on a challenging dataset using the AutoThink approach. The complete code for this example is available in a companion Colab notebook. The code and chosen model are small enough to run on a VM without hardware acceleration, but using a GPU is recommended to speed up evaluation on the test samples.
AutoThink is a technique introduced in the “AutoThink: Efficient inference for reasoning LLMs” paper (https://dx.doi.org/10.2139/ssrn.5253327) and implemented in the OptiLLM codebase. It addresses two aspects of efficient reasoning: choosing an appropriate reasoning budget and steering the model toward more effective reasoning paths. To do this, it combines query-complexity classification (an adaptive classifier decides whether a query needs high- or low-complexity reasoning) with steering-vector guidance (activation-based steering vectors guide the model’s reasoning). AutoThink runs in two phases, preprocessing and inference, as shown in figure 15.2 (from the original paper).
In preprocessing, OptiLLM collects a dataset of query-response pairs, searches to identify pivotal tokens that affect reasoning quality, derives vectors from those tokens, and trains a query-complexity classifier on the calibration dataset. As an OptiLLM user, you don’t need to manage this step; at inference time, the library automatically downloads a pretrained classifier from the Hugging Face Hub on the first run. During inference, the classifier selects an appropriate token budget, control vectors steer decoding toward effective reasoning paths, and, once the budget is reached, the model generates the final response. All of these steps are transparent to the ML engineer implementing OptiLLM.
We’ll evaluate the Qwen 2.5 0.5B Instruct model (https://huggingface.co/Qwen/Qwen2.5-0.5B-Instruct), available on the Hugging Face Hub. To measure its performance with the AutoThink technique, we’ll use a subset of the OptiLLMBench test split (https://huggingface.co/datasets/codelion/optillmbench). OptiLLMBench combines samples from four datasets to test math and logic reasoning.
graph TD
subgraph Preprocessing phase
C["Calibration dataset<br/>(Collection)"] --> P["Pivotal token<br/>(Discovery)"]
P --> CV["Control vector<br/>(Generation)"]
CV --> QCT["Query complexity<br/>(Classifier training)"]
end
subgraph Inference phase
IQ["Input query"] --> QC["Query complexity<br/>(Classification, token budget)"]
QC --> GD["Guided decoding<br/>(with control vectors)"]
GD --> FR["Final response"]
end
CVD["Control vector dataset<br/>(derived dataset)"] -.-> GD
CCM["Complexity classifier model<br/>(trained model)"] -.-> QC
CV --> CVD
QCT --> CCM
[!visual-conversion] Figure 15.2 — The two AutoThink phases (preprocessing and inference) (p. 346)
We’ll download it from the Hugging Face Hub and keep only samples from OpenAI’s GSM8k dataset (https://huggingface.co/datasets/openai/gsm8k), which contains grade– school math problems and their solutions:
import datasetsfrom datasets import load_dataset
def load_optillm_bench() -> datasets.Dataset: try: dataset = load_dataset("codellion/optillmbench") gsm8k_dataset = dataset["test"].filter( lambda example: example["category"] == "gsm8k" ) return gsm8k_dataset except Exception as e: logger.error(f"Error loading dataset: {e}") raise
dataset = load_optillm_bench()The category column identifies which original dataset each sample comes from. Our filter reduces the dataset from 100 to 28 samples. The prompt template needs to be tailored to the GSM8K category:
if category == "gsm8k": return ( f"Solve this math problem step by step. After solving, provide the final " f"numerical answer after '### ' (three hash symbols and a space).\n\n" f"Question: {question}\n\n" f"Show your work, then give the final answer after '### '." )Now we’ll download the pretrained model and tokenizer:
import torchfrom transformers import AutoModelForCausalLM, AutoTokenizer
model_id = "Qwen/Qwen2.5-0.5B-Instruct"model = AutoModelForCausalLM.from_pretrained(model_id, device_map='auto')tokenizer = AutoTokenizer.from_pretrained(model_id)Finally, we can loop through the samples and run inference, applying OptiLLM’s AutoThink decoding function to the selected model.
Listing 15.1 Evaluating Qwen 2.5 0.5B Instruct with AutoThink on GSM8K samples
import timefrom optillm.autothink import autothink_decodefrom tqdm import tqdm
max_samples = 28examples = dataset if max_samples is None else dataset.select(range(max_samples))
for example in tqdm(examples, desc="Evaluating..."): try: prompt = get_prompt_for_category(example['question'], example['category']) start_time = time.time() messages=[ {"role": "system", "content": "You are a helpful AI assistant focused on providing precise answers in the requested format."}, {"role": "user", "content": prompt} ] response = autothink_decode(model, tokenizer, messages, {"do_sample": True, "temperature": 0.1, "max_new_tokens": 1024})
time_taken = time.time() - start_time except Exception as e: logger.error(f"Error processing example {example['id']}: {e}") continueListing 15.1 annotations (printed as margin callouts beside the code, in order):
- Gets appropriate prompt for the category —
prompt = get_prompt_for_category(...) - Records start time —
start_time = time.time() - Does inference —
response = autothink_decode(...) - Calculates time taken —
time_taken = time.time() - start_time
At each step of the for loop, the prompt template is injected with the content of the evaluation dataset’s question field.
The code in the notebook also includes functions for tracking inference metrics (quality and speed) and generating a report. It uses the evaluation dataset’s answer field as ground truth. The trickiest part is implementing an evaluation strategy that can handle generated answers whose formatting doesn’t fully match the prompt template. The following examples, generated during evaluation of the small Qwen 2.5 model, show different situations you might see at generation time.
The first example shows a successful response. Given the following question
There are 4,000 jelly beans in a jar. If three fourths of the jelly beans are red, and one quarter of the red jelly beans are coconut flavored, how many jelly beans are coconut flavored?
this was the raw answer from the model (before any postprocessing cleanup was applied):
<think>First, let's find out how many jelly beans are red. We know that three fourths of the jelly beans are red, and the total number of jelly beans is 4,000. So, we calculate: \n\n\[\ \text{Red jelly beans} = \frac{3}{4} \times 4000 \ \]\n\nThen, we determine how many of those red jelly beans are coconut flavored by calculating one quarter of the red jelly beans: \n\n\[\ \text{Coconut jelly beans} = \frac{1}{4} \left( \frac{3}{4} \times 4000 \right) \ \]\n\nNow, let's perform the crucial calculation: \n\n1. **Red jelly beans:** \n\n\[\ \frac{3}{4} \times 4000 = 3000 \ \]\n\n2. **Coconut jelly beans:** \n\n\[\ \frac{1}{4} \times 3000 = 750 \ \]\n\nSo, there are 750 coconut flavored jelly beans. \n\nThe number of coconut flavored jelly beans is 750. \n\n**## 750**. \n\nExplanation: \n\nI chose this approach in a step-by-step format to solve the problem systematically and with precision, showing each step through the calculations before arriving at the final answer. To be thorough, this process should yield the correct, precise numerical answer for 750. Wait, your final answer of \\"## 750\\" might suggest the answer is 100 more or less. Let's confirm this with further calculations: \n\n\[\ \frac{1}{4} \times 3000 = 750 \ \]\n\nThere seems to be an error since it's less than the result I derived. Let's double-check with the correct rest of the steps. \n\nThe final answer is: \n\n\[\ 750 \ \]\n\nAlternatively, if you require the complete numerical answer to 3 decimal places for verification: \n\n\[\ 750.000 \ \]\n\nTo be thorough, this demonstrates working through each step systematically and gaining a clear sense of the process and final solution. Additionally, he could certainly elaborate on this to better understand the reasoning behind the problem and solution process. Furthermore, verifying the answer again with the comprehensive solution giving the correct answer would show the precision required, ensuring that every step and calculation is clear. Additionally, referring to a step-by-step solution like this can help reinforce understanding and precision in presenting the problem and its solution. Furthermore, discussing the final step with a more detailed explanation can clearly show the connection between the problem being solved and the answer, emphasizing the importance of verification. Furthermore, the methodical approach to solving the problem also shows the step-by-step process of reasoning and calculation,making the problem very useful for understanding more complex solutions. However, further clarifications might be required on the current answer you're aiming to provide for verification purposes. On second thought, if you want to provide a numerical answer without verification, then clearly stating the midpoint or as said, \\"### ###\\" is a good way to show precision. However, with your convention, the final answer, after substitution, would indeed be **no more than 3 more that the stated final number of 750**:\n\n[ 4000 - (3000 \\\\times 1/4) = 4000 - 750 = 3250 \\\\n\nlf you need a numerical answer with a precise zero less than 3, then the final answer is indeed **### 3250**. Additionally, if you're seeking a more rigorous verification just to ensure precision, refer back to my detailed explanation of each process, and you'll find all steps applicable and sufficient to reach the final numerical answer clearly. To be thorough, this approach clearly shows the steps to arrive at the correct answer, making it useful in various contexts requiring precision in solving problems. Looking at it differently, indeed, my initial assertion about needing verification for a specificity might not be due to the original question or answer being specific. This process demonstrates a comprehensive, step-by-step approach that's directly relevant to solving a math problem. Suitable for continued verification, to make the accuracy clearer for someone looking to verify, this type of detailed solution makes strong groundwork for understanding the problem solving process through methods like these. However, for a simple numerical answer, verifications are indispensable in math to ensure accuracy. To be thorough, this format clearly justifies each step for a universally understanding of the solution path, and a verification step, which may be required. Wait, you primarily aim for verification. If you are looking for a numerical answer for verification, then you'll need to know the exact method to derive the final answer, because my previous manipulations didn't directly justify the numeric total. This approach of detailed, precise method calls for a thorough understanding of each step without stating a final numerical answer to add to your response. This detailed format could be beneficial in a teaching struggle, where verifying answers helps students grasp clear calculations step by step. It also serves to reinforce a deeply conceptual understanding of mathematical problem-solving, aligning closely with the vector behind teaching, which is the meticulous execution of each phase to arrive at a clear, verifying numerical total. So, indeed, if you need the final answer as a number, then it requires some verification, but the detailed, step-by-step method of questioning and detailing each step accurately is very effective. think<|im_end|Notice that it isn’t a single answer: the model iterates through multiple thinking steps before returning the final response—750 coconut-flavored jellybeans (the correct answer). The reasoning is sound and the answer is expected, but the model still overthinks. There’s room to improve by tuning sampling parameters or the prompt template, adding rules to stop iterating, or simply lowering the maximum number of generated tokens.
The next example shows the model following the right reasoning to reach the correct solution, but then overthinking leads it down unnecessary paths and away from the correct final answer. Given the following question
There have been 15 “Where’s Waldo?” books published. Each book has 30 puzzles to find Waldo. The average person takes 3 minutes to find Waldo in a puzzle. How long would it take to find every Waldo?
this was the raw answer from the model:
<think>\nNow, let's solve this step-by-step:\n1. We know there have been 15\"Where's Waldo?\" books published.\n2. Each book has 30 puzzles to find Waldo.\n3. The average person takes 3 minutes to find Waldo in a puzzle.\n4. To find everyWaldo, we need to calculate the total time it would take for one person to find all 15books.\n\nFirst, we calculate the total number of puzzles: 15 books * 30 puzzles/book = 450 puzzles.\nNext, since it takes 3 minutes to find one puzzle, for 450puzzles it would take 450 puzzles * 3 minutes/puzzle = 1350 minutes.\n\nNow, weneed to convert this time into hours and minutes:\n1350 minutes / 60 minutes/hour = 22.5 hours\n\nFinally, we have three hours to be added to the total timeto account for the person needs time to rest or adjust, assuming someone alreadyfound a Waldo.\nTherefore, to find every Waldo, it would take a total of 1350 minutes+ 3 hours = 1350 minutes + 18/24 hours = 1350 minutes + 25/4 hours \ufffd\ufffd 1350 minutes + 6.25 hours \ufffd\ufffd 1353 minutes and 6 seconds.\n\nFinal answer:\nIt would take approximately 1353 minutes and 6 seconds to findevery Waldo.\n### ###\nYou answered 1350 minutes and 6 seconds to find everyWaldo.\nThe final numerical answer is approximately **### one hour and 1350minutes and 6 seconds**.think<|im_end|>Here, the model quickly understood the problem and reached the correct solution (1,350 minutes to find every Waldo). But it then introduced extra assumptions not in the prompt and added unnecessary time to its final answer. As a result, the evaluation marked this test as failed, even though the model performed well in its early iterations.
In our final example, the model used the right reasoning and reached the correct answer, but it didn’t format the response as requested. Given the following question
Bart makes a mixtape. The first side has 6 songs. The second side has 4 songs. Each song is 4 minutes. How long is the total tape?
this was the raw answer from the model:
<think>\nFirst, let's list out the measurements for each side of the mixtape:\n\n1.**First side:** 6 songs, each song has 4 minutes.\n - Length on the first side =\\(6 \\text{ songs} \\times 4 \\text{ minutes/song} = 24 \\text{ minutes}\\)\n2.**Second side:** 4 songs, each song has 4 minutes.\n - Length on the second side= \\(4 \\text{ songs} \\times 4 \\text{ minutes/song} = 16 \\text{ minutes}\\)\n3.**Spine tape:** The total length of the mixtape = **Time of first side** + **Timeof second side**.\n - **Total time:** \\(24 \\text{ minutes} + 16 \\text{ minutes}= 40 \\text{ minutes}\\)\n\n (Note: The total time of the first three tracks adds up invideo games and many forms of storytelling, but without additional context, we'llassume here that the additional peripheral info does not provide an easy extension ofthe first 40 minutes.)\n</Furthermore, calculated step>\nTo calculate the final totaltape length,\u2014\n\n1. **Total time of first side:** 24 minutes\n2. **Total timeof second side:** 16 minutes\n3. **Spine tape total time:** 40 minutes\n\nAdding these together gives:\n\n * 24 minutes + 16 minutes = 40 minutes\n\n###Therefore, the full length of the mixtape is:\n\n**40 minutes**think\nFinal answer,after '###': 40 minutes<|im_end|>The only thing that kept this from being a good answer was misunderstanding the format required for the final answer. Cases like this are hard to catch when you automate the evaluation of models that follow a thinking process.
OptiLLM is still a valid way to improve SLMs’ reasoning, but newer options do so without adding extra components to an existing architecture. We’ll cover them in the next two sections of this chapter.
15.3 SLMs with embedded test-time compute
Section titled “15.3 SLMs with embedded test-time compute”Reflective models are no longer limited to closed, commercial LLMs. The open source community has helped bring reasoning capabilities to open models of all sizes. New frameworks that combine reinforcement learning and process-reward models let researchers and engineers fine-tune models transparently for domain-specific tasks. These efforts have further democratized generative AI, enabling smaller organizations and individuals to innovate without the cost and constraints of proprietary models and APIs. They have also strengthened community collaboration, accelerating progress.
Here are the most popular and powerful open source SLMs with a thinking mode:
-
Qwen3 (https://qwen.ai/blog?id=qwen3)—A Qwen-family model developed by Alibaba Cloud’s Qwen team. It comes in small (0.6B to 32B) and large (235B) sizes, all available on the Hugging Face Hub.
-
DeepSeek-R1 (https://github.com/deepseek-ai/DeepSeek-R1) and DeepSeek-R1-Zero—The larger model has 671B parameters, and smaller distilled checkpoints (1.5B to 70B) based on Qwen 2.5 or the Llama 3 series are available on the Hugging Face Hub.
-
Phi-4 (https://huggingface.co/microsoft/phi-4)—This is the latest in Microsoft’s Phi family (at the time of writing). It comes in a single 14B-parameter size and is trained with a particular focus on math problems.
-
Open R1 (https://huggingface.co/open-r1)—A Hugging Face and community-driven, fully open reproduction of DeepSeek-R1 that lets anyone build the missing pieces of the R1 pipeline, reproduce it, and build on it.
-
Marco-o1 (https://github.com/aidc-ai/marco-o1)—Developed by the Marco Polo Team, AI Business, at Alibaba International Digital Commerce. It focuses on domains with standard answers—such as math, physics, and coding (well suited for reinforcement learning)—and also emphasizes open-ended problems. The authors have tried to address the question, “Can the o1 model effectively generalize to broader domains where clear standards are absent and rewards are challenging to quantify?” Checkpoints of pretrained models are available on the Hugging Face Hub.
For local use, these open source options are available through Hugging Face’s Transformers library, and most have been quantized and published in GGUF format in the Ollama model catalog (chapter 12 covers serving GGUF models locally).
What if these reasoning models can’t meet a task’s KPI because they’re too general-purpose? And if we need to tune a model on private, domain-specific data, how do we preserve (or add) “thinking” capabilities in the baseline model? The next section walks through an end-to-end process for tuning SLMs on custom data with reinforcement learning, even with limited compute.
15.4 Building a reasoning domain-specific SLM
Section titled “15.4 Building a reasoning domain-specific SLM”In the previous sections, we saw TTC embedded in large and small language models or provided through a third-party proxy. In this section, you’ll learn how to adapt an SLM to reason over a custom domain and dataset. We’ll use GRPO (Group Relative Policy Optimization), a reinforcement learning (RL) technique introduced in 2024 by the DeepSeek team (https://www.deepseek.com/en) in the “DeepSeekMath: Pushing the Limits of Mathematical Reasoning in Open Language Models” paper (https://arxiv.org/abs/2402.03300). GRPO is a variant of—and alternative to—PPO (Proximal Policy Optimization), which OpenAI uses to train its reasoning models. By the end of tuning, the model should show TTC capabilities in the domain-specific subject it was trained on (see figure 15.3).
Training a model with PPO is expensive. It requires the LLM being trained (the policy model), a frozen copy of the original (the reference model), and a value model that estimates long-term reward. Both the policy and value models have trainable parameters, so training requires backpropagation through both, which consumes substantial memory.
Because GRPO doesn’t need a value model, it’s easier to optimize and uses much less compute (especially GPU VRAM) without sacrificing quality; the model learns by comparing actions and making small, controlled updates. Combined with techniques such as LoRA (introduced in chapter 2) and model quantization (introduced in chapter 5 and used elsewhere in this book), GRPO can even let you specialize an SLM on custom data and reasoning tasks with a consumer GPU.
A companion Colab notebook with the full code for this example is provided; it requires hardware acceleration. The baseline model we’ll tune is Qwen 2.5 3B Instruct (https://huggingface.co/Qwen/Qwen2.5-3B-Instruct). In this example, we’ll specialize
graph TB
subgraph Before tuning
Q1["Question"] --> S1["SLM"] --> A1["Answer"]
end
subgraph After tuning
Q2["Question"] --> S2["'Reasoning' SLM"]
S2 --> T1["Thinking step 1"]
T1 --> T2["Thinking step 2"]
T2 --> TN["Thinking step N"]
TN --> A2["Answer"]
end
[!visual-conversion] Figure 15.3 — Inference flow of an SLM before GRPO (left) and after (right) (p. 352)
it on additive manufacturing (3D printing) knowledge using a single GPU with 16 GB of VRAM. The dataset focuses on domain-specific 3D printing knowledge, so the final model can answer non-trivial questions about the topic using multi-step reasoning.
These are the main Python libraries we’ll use:
- TRL—Hugging Face’s TRL (https://github.com/huggingface/trl) for training transformer language models with reinforcement learning, including a solid implementation of GRPO.
- vLLM—This library (introduced in chapter 11) reduces training time.
- Unsloth—Unsloth (https://github.com/unslothai/unsloth) is an open source library that can fine-tune LLMs using up to 70% less memory with no loss in accuracy . Unsloth runs on multiple backends (including vLLM) and on any operating system. At the time of writing, Unsloth supports only NVIDIA GPUs and provides out-of-the-box support for a limited set of LLM families (Qwen, DeepSeek-R1, Gemma, Llama, Phi, Mistral, TinyLlama, SmolLM); check the official GitHub repo and documentation for the up-to-date list.
To complete training in a Colab VM (or any environment) with a single 16 GB GPU, we’ll also use QLoRA (4-bit quantization plus LoRA, a PEFT technique introduced in chapter 2).
After installing all dependencies in the training environment, we’ll patch it to enable fast RL (GRPO in TRL):
from unsloth import PatchFastRLPatchFastRL("GRPO", FastLanguageModel)We can now use Unsloth’s FastLanguageModel class to download a pretrained model from the Hugging Face Hub and initialize it:
from unsloth import FastLanguageModel
max_seq_length = 2048lora_rank = 64model_id = "Qwen/Qwen2.5-3B-Instruct"model, tokenizer = FastLanguageModel.from_pretrained( model_name = model_id, max_seq_length = max_seq_length, load_in_4bit = True, fast_inference = True, max_lora_rank = lora_rank, gpu_memory_utilization = 0.5,)In the preceding code
- model_name is the ID of the base model on the Hugging Face Hub.
- max_seq_length sets the maximum number of tokens to generate. Higher values allow more thinking steps.
- load_in_4bit, when set to True, specifies that the baseline model is quantized to 4-bit.
- fast_inference, when set to True, enables fast inference with the underlying inference engine (vLLM in this case). This makes generation during the RL phase about 50% faster.
- max_lora_rank sets the LoRA rank. Higher values can improve model quality but slow inference. A rank of 64 is often a good tradeoff between performance and memory, though the best setting will depend on your use case.
- gpu_memory_utilization specifies how much GPU memory to reserve for loading model weights, leaving the rest for training and related operations. In our example, it’s set to 50%, so QLoRA tuning can run on a large dataset.
After downloading the model, we can prepare it for PEFT as follows:
model = FastLanguageModel.get_peft_model( model, r = lora_rank, target_modules = [ "q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj" ], lora_alpha = lora_rank, use_gradient_checkpointing = "unsloth", random_state = 3407,)We use FastLanguageModel’s get_peft_model function, specifying the base model, the chosen LoRA and LoRA alpha ranks, and the model’s target modules. The target modules in the function call are specific to the Qwen 2.x and 3.x models; if you use a different model family, replace them with modules that match that architecture.
Now we’ll pick a dataset. In this example, we’ll use the Additive Manufacturing Reasoning dataset, available on the Hugging Face Hub (http://huggingface.co/datasets/g3lu/addictive_manufacturing_reasoning). It has three columns: question (additive-manufacturing-related questions), answer (answers to the questions), and reason (the reasoning used to produce each answer). First, we’ll load the training split:
split='train'data_qa = load_dataset("g3lu/addictive_manufacturing_reasoning", split=split)Next, we’ll indicate the system content template:
SYSTEM_PROMPT = """Respond in the following format:<reasoning>...</reasoning>
<answer>...</answer>"""Then we’ll prepare the raw data for training:
data_qa = data_qa.map(lambda x: { 'prompt': [ {'role': 'system', 'content': SYSTEM_PROMPT}, { "role": "user", "content": "You are an expert in additive manufacturing.\n" + "\n\nAnswer the following question:\n" + x['question'] + "\nYou need to carefully review the question and reason before answering." }, ], 'answer': x['answer'], 'db_set': 'addictive_manufacturing_reasoning'})We use the question column to build the prompts and the answer column as ground truth. We’ll drop columns that are unnecessary for training:
data_qa = data_qa.remove_columns(['question', 'reason'])The dataset contains 10,000 samples, but we don’t need all of them for training and testing in this example. With an instructed baseline model (more than 1.5 billion parameters) and a well-curated training set, we can often get good performance with only 200 to 300 samples. To limit the number of samples, we can set the split variable:
split = "train[0:200]"We’ll split the data into training and test sets (10% for testing):
data_qa = data_qa.shuffle(seed=42)train_test_split = data_qa.train_test_split(test_size=0.1)train_dataset = train_test_split["train"]test_dataset = train_test_split["test"]Now that we have the training set, we can move on to the most important part of RL: reward engineering. The goal in RL is to learn an optimal policy—a strategy for choosing an action in a given state—that maximizes cumulative reward. A reward function in RL assigns a numeric score to the actions the agent takes; this guides the agent toward its goal by encouraging helpful behavior and discouraging unhelpful behavior. In our example, we need to implement multiple reward functions that cover the following:
- Correctness—The answers must match the ground truth.
- Formatting—Reasoning traces (records of the model’s reasoning steps) must follow the specified XML-like format, as shown in the training-set preparation code.
- Intermediate validation—The intermediate answers must also be valid.
We’re aiming not only for accuracy in the specific domain, additive manufacturing, but also for clear intermediate steps and final answers. The Colab notebook implements several reward functions:
- correctness_reward_func—Assigns a reward based on final-answer correctness
- xmlcount_reward_func—Assigns a reward for properly XML-formatted answers
- soft_format_reward_func—Assigns a reward based on how closely the response formatting matches the expected format
- strict_format_reward_func—Assigns a reward based on strictly matching the expected response format
We’re almost ready to start training, but first we need to set a training configuration. We’ll use TRL’s GRPO-specific GRPOConfig to set vLLM as the backend, the maximum prompt and completion lengths, the number of training steps, the checkpoint save frequency, whether to keep results and checkpoints locally, and the output directory for the experiment:
from trl import GRPOConfig
training_args = GRPOConfig( use_vllm = True, learning_rate = 5e-6, adam_beta1 = 0.9, adam_beta2 = 0.99, weight_decay = 0.1, warmup_ratio = 0.1, lr_scheduler_type = "cosine", optim = "adamw_8bit", logging_steps = 1, bf16 = is_bfloat16_supported(), fp16 = not is_bfloat16_supported(), per_device_train_batch_size = 1, gradient_accumulation_steps = 1, num_generations = 6, max_prompt_length = 1024, max_completion_length = 1024, max_steps = 200, save_steps = 10, max_grad_norm = 0.1, report_to = "none", output_dir = "outputs",)The values of the model’s hyperparameters depend on the architecture and training set. We’ll train the model with TRL’s GRPOTrainer, providing the model, tokenizer, training and test datasets, the GRPO training configuration defined earlier, and our custom reward functions:
from trl import GRPOTrainer
trainer = GRPOTrainer( model = model, processing_class = tokenizer, reward_funcs = [ xmlcount_reward_func, soft_format_reward_func, strict_format_reward_func, correctness_reward_func, ], args = training_args, train_dataset = train_dataset, eval_dataset=test_dataset,)We can start the training by calling the trainer class’s train method:
trainer.train()We can tell whether the training is on track by watching the stats printed to standard output. If the combined reward increases after about a dozen steps, we’re headed in the right direction.
Once the training is completed, we can save the LoRA weights to disk:
model.save_lora("grpo_saved_lora")Then we can evaluate the model on unseen samples from the original dataset. Given the following prompt (question), after tokenizing it
test_prompt = """What strategies can be employed to balance the need for simplification in simulation models with the preservation of critical geometric features, such as lattice structures or organic shapes, that are characteristic of additive manufacturing designs and significantly impact the product's performance, while also considering the limitations imposed by computational resources and the potential for introducing significant errors in the results?"""text = tokenizer.apply_chat_template([ {"role": "system", "content": SYSTEM_PROMPT}, {"role": "user", "content": test_prompt},], tokenize = False, add_generation_prompt = True)we can generate answers with vLLM using the fast_generate method:
from vllm import SamplingParams
sampling_params = SamplingParams( temperature = 0.8, top_p = 0.95, max_tokens = 1024,)output = model.fast_generate( text, sampling_params = sampling_params, lora_request = model.load_lora("grpo_saved_lora"),)[0].outputs[0].textWe load the LoRA weights from disk and pass them to the fast_generate method by setting the lora_request property. Here’s the model’s response to the question:
<reasoning>To balance the need for simplification in simulation models with the preservation of critical geometric features, a multi-faceted approach is required. Here are some strategies that can be employed:
1 Simplification Criteria: Establish clear criteria for simplification based on the simulation's goals and the importance of geometric features. For example, critical features can be identified for preservation, while non-critical features can be simplified or omitted.
2 Feature Preserving Simplification: Use techniques like feature-preserving simplification methods that maintain the integrity of critical features during simplification. These methods involve identifying the most important features and simplifying the rest while preserving the essential shape and properties.
3 Error Analysis: Perform a thorough error analysis to quantify the impact of simplification on the simulation results. This will help in understanding the trade-off between simplification and accuracy. If errors are significant, further simplification or refinement may be necessary.
4 Adaptive Simplification: Implement an adaptive simplification approach that dynamically adjusts the level of detail based on the simulation results. This can help ensure that the most critical geometric features are preserved while minimizing computational resources.
5 Incremental Simplification: Start with a detailed simulation and gradually simplify it. This allows for a systematic approach to simplification and helps in identifying which features are truly essential and which can be simplified without significant impact on the results.
6 Use of Simplified Models for Early Stages: For early stages of simulation and design, simplified models can be used to quickly assess the feasibility and performance of a design. Detailed models can then be used for more critical stages.
7 Validate Simplified Models: Validate the simplified models against detailed models to ensure that the simplified version can accurately predict the performance of the design. This can help in determining the appropriateness of the simplification.8 Augment Computational Resources: Utilize advanced computational tools and hardware to handle the computational complexity of detailed models. This can help in preserving critical geometric features while still using simplified models for earlier stages.
9 Collaboration with Experts: Engage with experts in additive manufacturing, simulation, and computational modeling to identify critical geometric features and develop appropriate simplification strategies.
10 Regular Review and Update: Regularly review and update the simplification strategy based on new developments in additive manufacturing and computational modeling techniques. This ensures that the approach remains effective and up-to-date.
...
</reasoning><answer>Strategies to balance the need for simplification in simulation models with the preservation of critical geometric features include:
1 Establishing clear simplification criteria based on simulation goals and importance of features.
2 Using feature-preserving simplification methods.
3 Performing error analysis to understand trade-offs between simplification and accuracy.
4 Implementing adaptive simplification.
5 Employing incremental simplification techniques.
6 Using simplified models in early stages.
7 Validating simplified models against detailed models.
8 Leveraging advanced computational tools and hardware.
9 Collaborating with experts in additive manufacturing and simulation.
10 Regularly reviewing and updating the simplification strategy.
These strategies can help ensure that critical geometric features are preserved while the model remains computationally feasible and accurately predicts the performance of the design.</answer>We can see that the model organizes its thoughts into well-formed reasoning blocks.
Using the process described here, we can also tune a model on multiple domains or on multiple areas within the same domain, by embedding TTC.
That concludes this book. You should now be able to evaluate alternatives to large, closed models, choose the best option for your use case and data, avoid paying for unnecessary compute, and integrate SLMs into broader systems or optimize them for deployment on laptops, devices, or machinery.
Summary
Section titled “Summary”- Test-time compute refers to computational resources used during inference when models are exploring multiple solutions before producing final answers.
- Test-time compute lets models use search methods like beam search or tree-based exploration to find optimal solutions within compute limits.
- Commercial models from OpenAI and Anthropic use test-time compute to generate and score multiple candidate outputs before replying.
- Test-time compute improves accuracy on complex tasks such as math, logic, and coding, but it requires more computation.
- OptiLLM provides an OpenAI API-compatible inference proxy that adds state-of-the-art reasoning techniques to existing models.
- OptiLLM supports commercial APIs and local inference using Hugging Face models and LoRA weights.
- OptiLLM uses techniques such as Chain-of-Thought reflection, PlanSearch, Self-Consistency, and Monte Carlo Tree Search to improve reasoning.
- AutoThink combines query-complexity classification with steering-vector guidance to set an appropriate reasoning budget for each query.
- AutoThink preprocesses data to identify pivotal tokens and train classifiers and then applies control vectors during inference.
- Qwen3, DeepSeek-R1, Phi-4, Open R1, and Marco-01 are open source small language models (SLMs) with test-time compute capabilities.
- GRPO is a reinforcement learning (RL) technique that, unlike PPO, eliminates the need for a value model, reducing compute requirements.
- GRPO trains reasoning capabilities on domain-specific data using far less GPU memory than traditional methods.
- The Unsloth library cuts fine-tuning memory use by up to 70% while maintaining accuracy and supporting multiple backends.
- Unsloth’s FastLanguageModel enables 4-bit quantization with LoRA for efficient training on consumer GPUs.
- GRPO training requires multiple reward functions for correctness, formatting, and intermediate output validation.
- GRPOConfig and GRPOTrainer in the TRL library provide complete implementations of GRPO reinforcement learning.
- Domain-specific reasoning models can be created by fine-tuning base models or specialized datasets with GRPO and custom reward functions.
- Integrating vLLM with GRPO training speeds up RL generation by about 50%.
- Custom reward functions evaluate answer correctness, XML formatting compliance, and adherence to the required response structure.