How Reasoning LLMs Work: From Chain of Thought to Qwen3 and DeepSeek-R1

What a thinking model computes, how reinforcement learning trains it, and what its visible reasoning does not prove

Enrique Tomás Martínez Beltrán

16 min read
How Reasoning LLMs Work: From Chain of Thought to Qwen3 and DeepSeek-R1
In this article

A reasoning LLM such as Qwen3 or DeepSeek-R1 has no separate logic module. It is the same transformer that predicts the next token, trained to write a long intermediate sequence (the "chain of thought") before it answers. That sequence gives the model more computation steps, a place to store partial results, and the chance to check and correct what it has already written.

What turned a prompting trick into a family of models was reinforcement learning with verifiable rewards: the model is rewarded when its final answer is correct according to an automatic checker, and the habits of thinking longer, verifying and backtracking emerge because they raise that reward. This note explains the mechanism, the published training recipe, the GRPO algorithm, what changes in Qwen3, and what the visible reasoning text does not prove.

1. What reasoning means for an autoregressive model

An autoregressive language model computes, for each position, a distribution over the next token. Computation per token is fixed: the same number of layers and operations whether the token is a comma or the result of a five digit multiplication. If an answer needs more steps than fit into a single forward pass, the model can only spread them across several tokens.

That is why intermediate tokens matter. Every generated token is fed back as context, so the text written so far works as external working memory. If xx is the question, zz the reasoning trace and yy the answer, the model first generates zz and then yy conditioned on both:

pθ(y∣x)=∑zpθ(z∣x) pθ(y∣x,z).p_\theta(y \mid x) = \sum_{z} p_\theta(z \mid x)\, p_\theta(y \mid x, z).If the formula does not fit, focus it and use the left and right arrows, or scroll horizontally.

In practice nobody sums over every possible trace: one (or a few) is sampled and the answer is read at the end. Training a reasoning model means raising the probability of traces zz that lead to correct answers, without telling the model in advance what those traces should look like.

A simple example shows the difference. Asked "how many primes are there between 80 and 100?", a model that answers directly must solve everything while computing the first token. A model that writes "81 = 3 × 27, 83 prime, 85 = 5 × 17, ..." turns a one step problem into a series of small checks, each within its capacity.

2. From chain of thought prompting to models that think

The first systematic evidence came from prompting. Wei and colleagues (2022) showed that including worked, step by step examples in the prompt improved arithmetic and symbolic reasoning in large models. Kojima and colleagues (2022) obtained a similar effect with no examples by simply adding "Let's think step by step". Wang and colleagues (2022) proposed self-consistency: sample several chains and keep the most voted answer.

All of these techniques act at inference time and rely on the model already knowing how to produce useful chains. STaR (Zelikman et al., 2022) went further: generate rationales, keep those that reach the correct answer and fine-tune on them. It is an early form of what would later be done with reinforcement learning.

The change of scale came in September 2024, when OpenAI introduced o1 and described a model trained with reinforcement learning to "think" before answering, whose performance improved both with more training compute and with more thinking time at inference. OpenAI did not publish the recipe. The first open, detailed description arrived in January 2025 with DeepSeek-R1, and soon afterwards the QwQ and Qwen3 models from Alibaba's Qwen team adopted a comparable scheme with open weights.

3. What happens inside a thinking block

In Qwen3 and DeepSeek-R1 the reasoning is written between special tags, usually <think> and </think>, followed by the final answer. Architecturally these tokens are nothing special: they are vocabulary tokens the model has learned to use to delimit a scratchpad. The chat template and the application decide whether the block is shown, hidden or discarded.

Reading real traces reveals recurring patterns:

PatternHow it appears in the traceWhat it is for
Decomposition"First I compute X, then Y"Splits the problem into steps that fit in a few tokens
Verification"Check: 7 × 13 = 91, correct"Catches errors before committing to an answer
Backtracking"Wait, that contradicts the statement"Abandons a wrong line of solution
Exploration"Another way to see it would be..."Tries an alternative approach when the first one stalls
Summary"So the answer is..."Condenses the trace before the final output

None of these patterns is programmed. They emerge because, during training, traces that verify and correct themselves reach correct answers more often and collect more reward. The DeepSeek-R1 report describes exactly this: average response length grew steadily during training, and spontaneous re-evaluations appeared that the authors called an "aha moment".

One practical consequence: a reasoning model may generate thousands of tokens before the answer. Those tokens cost time, KV cache memory and money, even when the user never sees them.

4. How it is trained: the published DeepSeek-R1 recipe

The DeepSeek-R1 report describes two models, and it helps to keep them apart.

DeepSeek-R1-Zero starts from the DeepSeek-V3-Base model and applies reinforcement learning directly, with no prior supervised fine-tuning. The rewards are rules, not a learned reward model:

  • Accuracy reward: in mathematics, the final answer must match the solution, written in a format that allows it to be extracted; in programming, the code must pass test cases.
  • Format reward: the reasoning must appear between the thinking tags.

With only that, the model learned to reason at length and to correct itself, and it improved sharply on mathematics benchmarks. It also showed problems: hard to read traces and language mixing within a single answer.

DeepSeek-R1 fixes those defects with a four stage pipeline:

  1. Cold start: supervised fine-tuning on a few thousand long, readable reasoning examples, so that reinforcement learning starts from a stable format.
  2. Reasoning oriented RL: the same scheme as R1-Zero, plus a language consistency reward that penalizes mixing languages in the trace.
  3. Rejection sampling and new supervised fine-tuning: the model generates many answers, the correct and readable ones are kept (about 600,000 reasoning samples according to the report) and combined with about 200,000 samples from general tasks such as writing or factual questions.
  4. RL for all scenarios: a final stage that combines rule based rewards for reasoning with preference models for helpfulness and harmlessness.

The report adds two results that have shaped the field. First, distillation: fine-tuning smaller dense models (from the Qwen2.5 and Llama families) only on the 800,000 samples generated by R1 transferred much of the reasoning ability, more than applying reinforcement learning directly at that size. Second, a section on unsuccessful attempts: process reward models and Monte Carlo tree search did not work well at their scale, partly because steps are hard to define and partly because the model could exploit the evaluator.

5. GRPO: reinforcement learning without a critic

R1's reinforcement learning algorithm is GRPO (Group Relative Policy Optimization), introduced in DeepSeekMath. It is a variant of PPO that removes the value network (the critic), which for an LLM would be about as large as the model itself.

The idea is to use the group as the baseline. For each question qq, GG answers o1,…,oGo_1,\ldots,o_G are sampled from the current policy, each is scored with reward rir_i, and the relative advantage is computed:

A^i=ri−mean⁡(r1,…,rG)std⁡(r1,…,rG).\hat{A}_i = \frac{r_i - \operatorname{mean}(r_1,\ldots,r_G)}{\operatorname{std}(r_1,\ldots,r_G)}.If the formula does not fit, focus it and use the left and right arrows, or scroll horizontally.

Answers better than the group mean get a positive advantage and worse ones a negative advantage. The objective is PPO's clipped objective, averaged over the tokens of each answer, with a divergence penalty against a reference model:

J(θ)=E[1G∑i=1G1∣oi∣∑t=1∣oi∣min⁡ ⁣(ρi,tA^i, clip⁡(ρi,t,1−ε,1+ε)A^i)−β DKL ⁣(πθ ∥ πref)],\mathcal{J}(\theta) = \mathbb{E}\left[\frac{1}{G}\sum_{i=1}^{G}\frac{1}{|o_i|}\sum_{t=1}^{|o_i|} \min\!\Big(\rho_{i,t}\hat{A}_i,\ \operatorname{clip}(\rho_{i,t},1-\varepsilon,1+\varepsilon)\hat{A}_i\Big) - \beta\, D_{\mathrm{KL}}\!\left(\pi_\theta \,\|\, \pi_{\mathrm{ref}}\right)\right],If the formula does not fit, focus it and use the left and right arrows, or scroll horizontally.

where ρi,t\rho_{i,t} is the ratio between the probability of token tt of answer ii under the new policy and under the policy that generated the samples. Clipping with ε\varepsilon prevents overly large updates, and the KL term keeps the model from drifting too far from its initial behavior.

A hypothetical example with a group of four answers to the same question, with reward rir_i and advantage A^i\hat{A}_i:

AnswerCorrect?RewardAdvantage
o1o_1Yes1+1
o2o_2No0-1
o3o_3No0-1
o4o_4Yes1+1

The mean is 0.5 and the standard deviation 0.5. Every token of o1o_1 and o4o_4 is reinforced and every token of o2o_2 and o3o_3 is penalized. Two details follow from the table:

  • Credit assignment is coarse. A brilliant step inside a wrong answer is penalized just like a mistake. The model only learns what worked by comparing many answers over the course of training.
  • A uniform group teaches nothing. If all four answers are right or all four are wrong, the deviation is zero and there is no signal. That is why the difficulty of the training set matters: questions that are too easy or impossible waste compute. Later work such as DAPO filters those groups and adjusts clipping and length normalization.

6. Verifiable rewards and their pitfalls

The piece that makes the scheme work is the verifier. In mathematics it is enough to compare the final answer; in programming, to run tests. This kind of training is known as reinforcement learning with verifiable rewards (RLVR), and it explains why reasoning models improved first in mathematics and code.

The alternatives have known costs:

  • Outcome reward: looks only at the final answer. It is cheap and hard to game if the checker is robust, but it accepts flawed reasoning that happens to land on the right answer.
  • Process reward: scores each step. Lightman and colleagues (2023) showed that step level supervision, with human labels, selected better mathematical solutions. It requires expensive annotation and an evaluator model that the trained model can learn to exploit.
  • Preference model: useful for style or helpfulness, but it is a learned judge and therefore manipulable if optimized against for too long.

The cross-cutting risk is reward hacking: if the checker has gaps, the model finds them. A code checker that only verifies that a program exits without errors will reward programs that do nothing useful. In domains such as security incident analysis there is no equally clean automatic verifier, so transferring these techniques requires careful design of what can be checked: an indicator extracted from a log, a query that returns the expected result, a detection rule that fires on a labeled set.

7. Qwen: from QwQ to Qwen3

Alibaba's Qwen team released QwQ-32B-Preview in November 2024 as an experimental reasoning model, and QwQ-32B in March 2025, trained with large scale reinforcement learning on a 32 billion parameter model. According to the team, its mathematics and coding performance approached DeepSeek-R1 at a much smaller size.

Qwen3 (April 2025, with a technical report in May) introduced three relevant ideas:

  1. Thinking and non-thinking modes in a single model. The same weights can reason in a <think> block or answer without one. This is controlled with the enable_thinking parameter of the chat template and, within a conversation, with the /think and /no_think instructions. In non-thinking mode the template inserts an empty thinking block.
  2. Thinking budget. Because the model can answer with or without reasoning, its thinking can be cut off at a token count and the model asked to answer with what it has. The report shows performance rising fairly smoothly with the allocated budget, which lets you choose the balance between quality and latency.
  3. Strong to weak distillation. The flagship models (including the 235B MoE with 22B active parameters and the 30B MoE with 3B active) go through the full pipeline; the small models learn mostly from their outputs, at a fraction of the cost of repeating reinforcement learning. The note on Mixture of Experts explains what active parameters mean.

Post-training for the flagship models has four stages reminiscent of R1: a long reasoning cold start, reasoning RL, thinking mode fusion (supervised fine-tuning on data with and without thinking so that one model masters both), and general RL for instruction following, formatting and tool use.

In July 2025 the team released updated versions (suffix 2507) that again separated an Instruct model and a Thinking model, stating that training them separately gave better quality than the hybrid mode. It is a good reminder that these design decisions remain open. This note describes what is documented in the cited technical reports; later versions may change training or usage details.

8. Test-time compute: thinking longer is not always thinking better

Reasoning models made a second scaling axis explicit: besides training larger models, you can spend more compute when answering. Snell and colleagues (2024) showed that, for certain problems, allocating inference compute well can make up for a considerably smaller model. The main strategies are:

StrategyHow it worksMain cost
Longer traceThe model thinks for more tokens before answeringSequential latency
Self-consistencySeveral independent traces and a majority voteCompute multiplied by the number of samples
Best-of-N with a verifierSeveral answers and an evaluator picks oneCompute and evaluator reliability
Budget controlForcing the thinking to stop or continuePossible quality loss if cut too early

The s1 paper (Muennighoff et al., 2025) called a very simple form of control budget forcing: to extend reasoning, suppress the closing token and append "Wait"; to shorten it, force the closing token. With only about 1,000 supervised fine-tuning examples, it obtained gains that grew with the budget.

More tokens do not guarantee more accuracy. Chen and colleagues (2024) documented overthinking: models that spend hundreds of tokens on "2 + 3" and re-check answers that were already correct. For many everyday queries the non-thinking mode is faster, cheaper and just as good. The right choice depends on the task and must be measured.

9. What visible reasoning does not prove

Reading the trace is tempting: it looks like an explanation of the process. There are three reasons not to treat it that way.

The trace may be unfaithful. Turpin and colleagues (2023) introduced biases into prompts (for example, making the correct answer in the examples always option A) and found that models changed their answer because of the bias without mentioning it in their explanation. Lanham and colleagues (2023) truncated or corrupted chains and observed that, depending on the task, the final answer depended heavily or barely at all on them. In 2025, Chen and colleagues repeated the analysis with reasoning models: when a hint in the prompt changed the answer, the model acknowledged it in its trace only in a minority of cases.

Reinforcement learning may sharpen more than it expands. Yue and colleagues (2025) compared base models and RLVR trained models using pass@k with large values of k. The trained model succeeds more often in a single attempt, but with enough attempts the base model solves a similar or larger share of problems. Their interpretation is that reinforcement learning concentrates probability on paths the base model could already take. The question is still debated, but it argues against crediting reinforcement learning with new capabilities without measuring them.

The trace is a security surface. It can contain sensitive data from the context, reproduce instructions injected through a document or a tool, and it should not be treated as an audit log. In agent systems, prompt injection evaluation must also cover what the model writes in its thinking block, even if the end user never sees it.

10. Using Qwen3 in practice

With the transformers library, thinking mode is enabled through the chat template. The following snippet follows the usage documented in the Qwen3 model cards:

Python
from transformers import AutoModelForCausalLM, AutoTokenizer

model_name = "Qwen/Qwen3-8B"
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype="auto", device_map="auto")

messages = [{"role": "user", "content": "How many primes are there between 80 and 100?"}]
prompt = tokenizer.apply_chat_template(
    messages,
    tokenize=False,
    add_generation_prompt=True,
    enable_thinking=True,  # False for a direct answer
)
inputs = tokenizer([prompt], return_tensors="pt").to(model.device)

output = model.generate(
    **inputs,
    max_new_tokens=4096,
    do_sample=True,
    temperature=0.6,
    top_p=0.95,
    top_k=20,
)
new_tokens = output[0][inputs.input_ids.shape[1]:].tolist()
end_think = tokenizer.convert_tokens_to_ids("</think>")
split = len(new_tokens) - new_tokens[::-1].index(end_think) if end_think in new_tokens else 0
thinking = tokenizer.decode(new_tokens[:split], skip_special_tokens=True)
answer = tokenizer.decode(new_tokens[split:], skip_special_tokens=True)
print(answer.strip())

Three recommendations from the Qwen3 documentation are worth following:

  • Do not use greedy decoding in thinking mode. The model card recommends temperature 0.6, top-p 0.95 and top-k 20, and warns that greedy decoding can cause endless repetition. For non-thinking mode it suggests temperature 0.7 and top-p 0.8.
  • Do not send the thinking back in multi-turn conversations. The history should contain only the final answers. The official template already does this, but a custom integration can reintroduce the traces and fill the context.
  • Leave token headroom. If max_new_tokens is small, the model may exhaust the limit while thinking and never answer. For a strict budget it is better to cut the thinking explicitly and ask for the final answer.

11. How to evaluate a reasoning model before using it

In cyber defense, a reasoning model is attractive for correlating alerts, interpreting logs or proposing hypotheses about an incident. Before using one, I suggest measuring at least the following on a reviewed golden set from your own domain:

  1. Accuracy with and without thinking, with the same model and the same prompts. If non-thinking mode performs the same in a category, the trace is not worth paying for.
  2. Thinking tokens and p95 latency per task category, not just the mean.
  3. Stability across seeds: several runs per case. A model that is right in one run out of three is not reliable for an analyst.
  4. Sensitivity to irrelevant hints: introduce a misleading detail (for example, an internal IP presented as malicious) and check whether the conclusion changes and whether the trace mentions it.
  5. Behavior with hostile content: documents or tool outputs with injected instructions, reviewing both the answer and the thinking block.

A hypothetical reading of the results: if thinking mode raises accuracy on temporal correlation questions but not on indicator extraction, and multiplies latency for both, the reasonable decision is to enable it only for the first category. The operational metrics for LLMs help place those measurements next to quality, and the guide to LLMs for cybersecurity describes how to integrate the model into an evidence first workflow.

Frequently asked questions

Does a reasoning LLM really think?

It runs more computation steps before answering and uses the generated text as working memory, which lets it solve problems it cannot solve by answering immediately. That does not mean the visible trace is a faithful description of how it reached the answer, as studies on chain of thought faithfulness show.

What is the difference between Qwen3 in thinking and non-thinking mode?

The weights are the same and the template differs. In thinking mode the model writes a <think> block before answering; in non-thinking mode that block is empty. The first is usually more accurate on mathematics, code and multi-step problems, at the cost of more tokens and latency; the second is preferable for simple or conversational queries.

What is GRPO and why is it used instead of PPO?

It is a PPO variant that estimates each answer's advantage by comparing it with other answers to the same question, instead of using a value network. It saves the memory and training of that critic, which for an LLM would be almost as large as the model itself, and it fits binary right or wrong rewards well.

Are reasoning models useful for tasks without a verifiable answer?

They can help, because the habit of decomposing and reviewing partly transfers to other tasks, and the final training stages include general data. But the largest documented gains are in domains with an automatic checker. On open-ended tasks, measure whether thinking mode actually improves the result and watch for overthinking. The trustworthy AI topic gathers other notes on evaluating these systems and their limits.

Estimated text reading time: 16 minutes. Equations, code and references may take longer.

LLMs · Large Language Models · Reasoning · Reinforcement Learning · Trustworthy AI

Related Research