<think> small : Building a Reasoning SLM

Kiran Kunapuli · Independent project

This project is part of a series where I learn by building. How can a small language model learn to work through a problem before giving an answer?

I disabled Gemma 4 E2B’s built-in thinking mode and fine-tuned it on worked examples from a Python solver.

Explore the held-out results or compare captured answers with the solver.

152/200Correct held-out answers in the requested format
6,000Distinct solver-generated training examples
24.2MTrainable LoRA parameters
4Quantitative reasoning domains

The experiment

From a problem specification to a scored answer.

The solver generates the worked solutions and grades the final values. Gemma generates its own solutions during evaluation.

What happens to a question, from generation to a scored answer
  1. Draw a specDomain, products, quantities, rate, date, holidays
  2. Emit the traceTemplate walks the spec, one arithmetic step per line
  3. VerifyReplay the solver and compare the stored steps and value
  4. Mask and trainPrompt tokens at −100; only the trace and answer carry loss
  5. Score pairedBase and tuned answer the same items; resample items, not runs

Why turn off built-in thinking?

Both models use enable_thinking=False to isolate what the adapter adds to Gemma’s ordinary response. The inference check measures what changes when thinking is enabled.

Data generation and response masking

6,000 training rows, 240 validation, 200 test, generated from seeded problem specifications.

Four task families and the calculation each requires
DomainThe questionSkill tested
tiered_pricingLine items, tier multipliers, discount, and taxOrder of operations; tier boundaries; rounding at each stage
unit_chainkm → mi → ft, then a unit price and a flat feeRounding between conversions compounds
business_daysN working days after a date, weekends and 2026 holidays excludedCarry calendar boundaries and exclusions
rate_allocationSplit an amount by weights, floor to cents, distribute leftover cents by descending weightRemainder assignment must be exact

Only assistant tokens contribute to the loss. Prompt labels are masked with −100.

<bos> system question <reasoning> step 1 step 2 <answer> <turn|>

Struck-through tokens provide context.

Replay checks each stored trace and answer. Equivalent specs stay in one split. The four templates are shared across splits.

Training on solver traces

One epoch of response-only fine-tuning with Unsloth and QLoRA.

Training settings for the released adapter
SettingValue
Data6,000 train, 240 validation, 200 test
Baseunsloth/gemma-4-E2B-it with 4-bit base weights
LoRARank 16, alpha 32, dropout 0.05
Schedule375 steps, BF16, learning rate 2e-4, sequence length 768, batch 2 × 8 accumulation

24.2M adapter parameters trained against a frozen 4-bit base. Calendar targets count workdays by week. Allocation targets show exact fractions of cents before flooring.

Worked conversion from the solver
<reasoning>
2.5 km × 0.621371 = 1.5534 mi
1.5534 mi × 5280 = 8201.952 ft
8201.952 ft × 3.9 ≈ 31987.61
31987.61 + 40.00 = 32027.61
</reasoning>
<answer>32027.61</answer>
One row, from spec to loss
spec → question + solver trace + answer
prompt → masked labels
assistant trace + answer + terminator → supervised labels
frozen 4-bit Gemma weights + trainable LoRA adapter

Paired evaluation

Same prompts, greedy decoding, thinking off.

152/200 correct in the requested format. The held-out set was frozen before training, with 50 questions per domain and no equivalent training specs.

Shared held-out test with a 384-token generation budget
MetricBaseWith reasoning adapter
Tiered pricing0/5040/50
Unit conversion0/5043/50
Business days0/5024/50
Weighted allocation0/5045/50
Correct value in the requested format0/200152/200
Valid trace format0/200199/200
Reached the generation limit195/2001/200

The base hit the 384-token limit on 195/200 questions. Strict success requires a valid trace followed by the exact final value.

Paired gain: +76 percentage points (95% bootstrap interval +70 to +82). The adapter won 152 pairs, the base won zero, and 48 tied. Exact McNemar p = 3.50 × 10−46 under this prompt and generation cap.

What the token budget changes

On 40 shared questions, doubling the cap to 768 increased the base’s correct tagged values from 1 to 8, with strict success rising from 0 to 1. The tuned model stayed at 27 strict successes.

Evaluation summary · Base outputs · Tuned outputs · Budget-check counts

Built-in thinking doubled token use at the same tuned score

The tuned model averaged 222 generated tokens with thinking off, versus 458 with thinking on. Both settings scored 27/40. Thinking off used 52% fewer generated tokens on this sample.

Same 40 questions and a shared 768-token cap, including thinking tokens
ModelThinkingAvg. tokens Correct tagged valuesValid tracesBoth Hit capGeneration time
BaseOff7228/402/401/4030/40115s
BaseOn7680/400/400/4040/40111s
TunedOff22227/4040/4027/400/4074s
TunedOn45827/4039/4027/401/40176s

The thinking-enabled base was still thinking at cutoff on 35/40 questions. A larger budget could change its result. The tuned model gained two calendar answers and lost one calendar and one allocation answer.

Greedy decoding on the same 4-bit base, two batches of 20. Timing covers both batches. Scoring uses the visible response. Token counts include thinking. Inference scorecard · Inference script

Quantization and local inference

Use the LoRA adapter with Gemma 4 E2B, or download the merged weights and Q8_0 GGUF.

Run the Q8_0 release with Ollama
ollama run hf.co/kirankunapuli/gemma-4-e2b-think-small:q8_0

Q8_0 smoke check: the export loaded in llama.cpp and returned 60.45 on a held-out unit conversion. For custom decoding, use Gemma’s configured EOS IDs, which include the end-of-turn token <turn|>. Captured GGUF output

Inspect a model answer

Compare base and tuned responses on the same question and check each against the solver. The four examples include both correct and incorrect answers.

Equivalent decimals match. Dates use YYYY-MM-DD. The browser compares your value with the stored answer.

Ready Enter a final value to check it.

Stored benchmark reference


          


          

These four rows come from the balanced test above. The Space displays the stored reference steps and saved 4-bit completions.

Where the model gets it right and wrong

Two held-out answers, with solver references and scoring code.

Pass · The leftover cent goes to the right line

583.34 is correct. For 1250.00 split by [4, 4, 7], flooring leaves one cent. The model gives it to the line with weight 7.

Tuned output · Test row 3150055
<reasoning>
Total to allocate 1250.00 across weights [4, 4, 7], sum 15
Share 1: 500000/15 cents, floor to 33333 cents = 333.33.
Share 2: 500000/15 cents, floor to 33333 cents = 333.33.
Share 3: 875000/15 cents, floor to 58333 cents = 583.33.
Unallocated after flooring = 0.01, 1 cents
Assign remaining cents to the largest weight first: 333.33, 333.33, 583.34
The largest weight is 7 at index 3, allocated 583.34
</reasoning>
<answer>
583.34
</answer>
Reference calculation
Weight sum = 4 + 4 + 7 = 15
Floored shares in cents = 33333, 33333, 58333
Leftover = 125000 − 124999 = 1 cent
Line 3 gets the cent: 58333 + 1 = 58334
Expected answer = 583.34
Format: pass · Exact value: pass
From the allocation solver · floor each share, then sort by descending weight and earlier index
exact = [(total * Decimal(w) / Decimal(denominator)) for w in weights]
floored = [value.quantize(CENT, rounding="ROUND_FLOOR") for value in exact]
remainder_cents = int(((total - sum(floored)) / CENT).to_integral_value(rounding=ROUND_HALF_UP))
order = sorted(range(len(weights)), key=lambda i: (-weights[i], i))

Fail · The model counts the weekend

June 29 is two working days early. The model calls Friday a Sunday and counts Saturday and Sunday toward the three-day deadline.

Tuned output · Test row 3100083
<reasoning>
Start 2026-06-26, a Sunday
2026-06-27 to 2026-06-29: 3 workdays, 0 weekend days, 0 weekday holidays. Counted 3 of 3 workdays.
Advanced 3 working days from 2026-06-26 to 2026-06-29
</reasoning>
<answer>
2026-06-29
</answer>
Reference calculation · first error is the starting weekday
2026-06-26 is Friday. Start counting the next day.
2026-06-27 Saturday → skip
2026-06-28 Sunday   → skip
2026-06-29 Monday   → day 1
2026-06-30 Tuesday  → day 2
2026-07-01 Wednesday → day 3
Expected answer = 2026-07-01
Format: pass · Exact value: fail

Why both traces pass the format check

Tagged trace scorer · strict success requires both checks
ok, reason = fmt.format_ok(text)
reasoning, answer = fmt.parse_completion(text)
correct = bool(answer is not None and fmt.answers_match(answer, row["answer"]))
# Scored field
"strict_correct": bool(ok and correct)

A valid trace can end in the wrong answer. The scorer checks the tags and final value. The worked examples show where an intermediate step went wrong.

Training command · run from the repository root
python build/train_sft.py --train out/reasoning-v2/train.jsonl \
  --valid out/reasoning-v2/valid.jsonl --out out/reasoning-v2/adapter \
  --batch-size 2 --grad-accum 8 \
  --compute-dtype bfloat16 --save-steps 125 --log-every 10

375 steps · 0 rows skipped · 13.11 GiB peak CUDA allocation.

Calendar and allocation solvers · Scorer source · Run log and settings · Full questions and outputs

Reproduce the experiment

The code and pinned split recipes reproduce the dataset, training, and evaluation.