You have probably done this: you write a prompt, run it on twenty examples, squint at the failures, tweak a sentence, run it again, and repeat until the number stops moving. It works, but it is slow, it is unprincipled, and the prompt you end up with is the one you happened to try last, not the best one you could have found.

DSPy has an optimizer that does this loop for you, and it does it better than the manual version. It is called GEPA (Genetic-Pareto), and it is DSPy's recommended optimizer for complex workloads in 2026. You give it a program, a training set, and a metric that returns both a score and a sentence of feedback. GEPA runs your program, reads the feedback on the failures, and asks a second language model — the reflection model — to rewrite the instruction. It keeps a Pareto frontier of the best candidates and repeats until the budget runs out. What you keep at the end is a better instruction plus the few-shot examples that earned their place.

This tutorial runs the whole thing locally, with no API key and no account: a Qwen3-0.6B model answers the questions, a Qwen3-1.7B model does the reflecting, both served by llama.cpp on one CPU-only machine. The task is 40 two-step arithmetic word problems, generated with known answers so the metric is exact. The baseline prompt scores 1/8 (12.5%) on a held-out test set; the GEPA-optimized program scores 3/8 (37.5%). Every number below was measured on this machine, and the code is short enough to read in one sitting.

1. The problem with hand-tuned prompts#

A prompt is a program you cannot debug. When a model gets a question wrong, the failure could be the instruction, the format, the examples, or the model's arithmetic — and the prompt gives you no stack trace. So people iterate by feel: add "think step by step", remove it, add an example, change the wording, and keep whichever version scores best on the twenty examples they happen to have open. That is a search over a huge space with a sample size of one person and no memory of what was tried.

Prompt optimizers replace the feel with a search. DSPy has several — MIPROv2 does Bayesian search over instructions and few-shot sets, COPRO does coordinate ascent, BootstrapFewShot picks the best demonstrations. GEPA is different in one important way: it reads your metric's feedback. A metric that returns only a number tells the optimizer "this failed". A metric that returns a number plus "the correct answer is 366, but the model answered 112 — it multiplied 28 by 8 and got 192" tells the optimizer what to fix. The reflection model turns that into a new instruction. That feedback channel is the whole point of GEPA, and it is why the metric you write matters more than the optimizer settings.

The second thing that matters is the reflection model. The documentation's standard configuration pairs a cheap task model with a strong reflection model — the classic example is a GPT-5 task moved to a small Qwen model, optimized with GEPA, ending up roughly 75x cheaper and 2x more reliable. We will do the same shape with local models only: a 0.6B model does the work, a 1.7B model does the thinking about the work.

2. What you'll need#

  • Python 3.10 or later (this tutorial used 3.12.3) and pip install dspy — GEPA is built into DSPy 3.5.0, no separate package.
  • llama.cpp — this tutorial used release b12823 (server version 1.1.0-dev). Any recent release works.
  • Two GGUF models: Qwen3-0.6B-Q8_0.gguf (639 MB) as the task model and Qwen3-1.7B-Q8_0.gguf (1.83 GB) as the reflection model, both from Qwen's official GGUF repos. Total download about 2.5 GB.
  • About 4 GB of RAM and a CPU. No GPU, no API key, no account. Everything below ran on a 4-core virtual machine with 1.5 shared CPUs.
  • Time: the GEPA run itself took 35 minutes with a 200-metric-call budget. Most of that is the 1.7B reflection model generating at about 1.4 tokens per second on CPU. On a GPU it would be minutes.

One warning before you start: Qwen3 models are "thinking" models. Left to themselves they spend 200+ tokens thinking before they answer, which on CPU turns every call into a minute. This tutorial disables thinking entirely with a modified chat template — the models answer directly, and the prompt optimization is what makes them accurate. The trade-off is real (thinking helps small models on hard math), and it is discussed in the limits section.

Diagram: two local models, one job. Qwen3-0.6B answers the questions, Qwen3-1.7B rewrites the instruction, DSPy orchestrates
Diagram: state in, probabilities out — one forward pass, zero generated tokens. AI-generated illustration for AI Frontier Post.

3. Step 1: Serve two local models#

Download the models and the llama.cpp release. The Qwen3-0.6B GGUF repo ships only a Q8_0 file — there is no Q4_K_M for the 0.6B — so take what is there and check the size when it lands.

mkdir -p ~/gepa && cd ~/gepa
curl -L -o Qwen3-0.6B-Q8_0.gguf \
  https://huggingface.co/Qwen/Qwen3-0.6B-GGUF/resolve/main/Qwen3-0.6B-Q8_0.gguf
curl -L -o Qwen3-1.7B-Q8_0.gguf \
  https://huggingface.co/Qwen/Qwen3-1.7B-GGUF/resolve/main/Qwen3-1.7B-Q8_0.gguf
curl -L -o llama.tar.gz \
  https://github.com/ggml-org/llama.cpp/releases/download/b12823/llama-b12823-bin-ubuntu-x64.tar.gz
mkdir llama-bin && tar xzf llama.tar.gz -C llama-bin --strip-components=1
ls -la Qwen3-0.6B-Q8_0.gguf Qwen3-1.7B-Q8_0.gguf
# expect: 639446688 and 1834426016 bytes

Now the thinking switch. Qwen's official chat template emits an empty <think> block — which makes the model skip thinking — only when enable_thinking is false, and llama.cpp does not forward that flag from DSPy's requests. The reliable fix is a copy of the template with the condition removed, so thinking is off for every request. Take the template from the Qwen3-0.6B repo's tokenizer_config.json (chat_template field) and replace this block:

{%- if enable_thinking is defined and enable_thinking is false %}
        {{- '<think>\n\n</think>\n\n' }}
    {%- endif %}

with just the middle line:

{{- '<think>\n\n</think>\n\n' }}

Save it as chat_template_nothink.jinja and start both servers with it. The 0.6B model answers questions on port 8080; the 1.7B model reflects on port 8081.

cd ~/gepa/llama-bin
LD_LIBRARY_PATH=. ./llama-server -m ../Qwen3-0.6B-Q8_0.gguf \
  --port 8080 --host 127.0.0.1 -c 4096 \
  --chat-template-file ../chat_template_nothink.jinja &
LD_LIBRARY_PATH=. ./llama-server -m ../Qwen3-1.7B-Q8_0.gguf \
  --port 8081 --host 127.0.0.1 -c 4096 \
  --chat-template-file ../chat_template_nothink.jinja &
sleep 30
curl -s http://127.0.0.1:8080/health && curl -s http://127.0.0.1:8081/health

Verify the 0.6B model answers directly, without a hidden thinking phase. This call took about 10 seconds and 7 completion tokens — with thinking on, the same question took 62 seconds and 240 tokens, 232 of them hidden reasoning.

curl -s http://127.0.0.1:8080/v1/chat/completions -H 'Content-Type: application/json' -d '{
  "model": "qwen3-0.6b", "max_tokens": 60, "temperature": 0,
  "messages": [
    {"role": "system", "content": "Reply with a single number and nothing else."},
    {"role": "user", "content": "Maya buys 4 notebooks at $3 each and 2 pens at $2 each. How much does she spend in total?"}
  ]}' | python3 -c "import json,sys; print(json.load(sys.stdin)['choices'][0]['message']['content'])"
# 3 * 4 + 2 * 2 = 12 + 4 = 16.

Notice what the model did: told to reply with a single number, it still wrote a one-line derivation and then the answer. That is fine — the metric below takes the last number in the output, so a short derivation is harmless and usually helps.

4. Step 2: Build the task and the metric#

GEPA needs three things: a program, a training set, and a metric. The program is one DSPy signature — a question in, an answer out — with a deliberately plain starting instruction:

import dspy

class MathQA(dspy.Signature):
    """Solve the word problem. Reply with a single number and nothing else."""
    question: str = dspy.InputField()
    answer: str = dspy.OutputField()

program = dspy.Predict(MathQA)

The task is 40 two-step arithmetic word problems, generated from ten templates (change from a bill, a discount, splitting a bill, fencing a garden, and so on) with seeded random numbers, so every answer is computed by the same arithmetic the question describes. The split is train 16, validation 16, test 8 — and the test set is touched only at the end. A few examples:

A train travels 66 km per hour for 2 hours, then 78 km per hour for 3 hours.
How far does it travel in total?  -> 366
A garden is 11 m long and 6 m wide. A fence costs $8 per metre.
How much does fencing the whole garden cost?  -> 272
Zoe earns $19 per hour and works 7 hours a week for 4 weeks.
How much does Zoe earn in total?  -> 532

The metric is where GEPA gets its leverage. It returns a dspy.Prediction with a score and feedback — returning a bare float, or a dict with the same fields, crashes dspy.Evaluate under DSPy 3.2+, so use the Prediction object. The feedback names the correct answer and the model's answer, which is exactly what the reflection model needs to diagnose the failure.

import re

def extract_number(text):
    """Last integer in the text, or None."""
    if not text:
        return None
    nums = re.findall(r"\d[\d,]*", str(text).replace("$", ""))
    return int(nums[-1].replace(",", "")) if nums else None

def math_metric(gold, pred, trace=None, pred_name=None, pred_trace=None):
    got = extract_number(pred.answer)
    if got is None:
        return dspy.Prediction(
            score=0.0,
            feedback="The answer contained no number at all. Reply with a single number.")
    if got == gold.answer:
        return dspy.Prediction(score=1.0, feedback="Correct.")
    return dspy.Prediction(
        score=0.0,
        feedback=(f"Wrong: the correct answer is {gold.answer}, but the model "
                  f"answered {got}. Check the arithmetic step by step."))

Two details worth noting. First, the metric is strict: a right method with a wrong final number scores 0. That is the honest choice for arithmetic, and it makes the feedback unambiguous. Second, the gold answers are integers stored on the example — the metric compares numbers, not strings, so $16, 16. and 16 muffins all count.

5. Step 3: Measure the baseline#

Before optimizing anything, measure the starting point on the validation and test sets. The models are configured as OpenAI-compatible endpoints — DSPy's dspy.LM("openai/...") with an api_base pointing at llama.cpp — with the task model deterministic (temperature=0) so the baseline is reproducible.

task_lm = dspy.LM("openai/qwen3-0.6b", api_base="http://127.0.0.1:8080/v1",
                  api_key="local", temperature=0.0, max_tokens=80)
dspy.configure(lm=task_lm)

evaluator = dspy.Evaluate(devset=valset, metric=math_metric, num_threads=2)
evaluator(program)   # Average Metric: 6.0 / 16 (37.5%)
evaluator = dspy.Evaluate(devset=testset, metric=math_metric, num_threads=2)
evaluator(program)   # Average Metric: 1.0 / 8 (12.5%)

The baseline is 6/16 (37.5%) on validation but only 1/8 (12.5%) on the held-out test set. That gap is the story of this tutorial: the plain instruction is brittle. Look at the raw test outputs and the failure mode is obvious — arithmetic slips, not format failures:

gold=144  $28 * $8 - $10 * $8 = $28 * $8 - $80 = $192 - $80 = $112   (28 x 8 is 224, not 192)
gold=22   $24.00
gold=34   $10
gold=72   $19 * $9 = $171 / $11 * $9 = $99 / $171 - $99 = $72        (correct)
gold=8    4
gold=66   60
gold=45   40
gold=82   $84                                                        (forgot the $2 discount)

The model knows the shape of the solution — it writes the right derivation structure almost every time — and then fumbles a multiplication or drops a term. That is precisely the kind of failure a better instruction and a few good demonstrations can fix: tell it to compute each multiplication separately, and show it what a careful derivation looks like.

Diagram: the GEPA loop. A candidate prompt is scored, the failures are reflected on, a new candidate is proposed, and only the best survive on the Pareto frontier
The confidence gate: auto-route what the model is sure about, send the rest to a human. AI-generated illustration for AI Frontier Post.

6. Step 4: Run GEPA#

The optimizer call is five lines. Three decisions matter: the metric (already written), the reflection model (the 1.7B, at temperature=1.0 so its proposals vary), and the budget. GEPA enforces exactly one of auto, max_full_evals, or max_metric_calls. This run uses max_metric_calls=200 — a hard ceiling on metric invocations, which bounds the whole run to roughly an hour on CPU. auto="light" is the equivalent preset (about six candidate prompts), and auto="medium" roughly doubles it.

reflection_lm = dspy.LM("openai/qwen3-1.7b", api_base="http://127.0.0.1:8081/v1",
                        api_key="local", temperature=1.0, max_tokens=512)
optimizer = dspy.GEPA(metric=math_metric, reflection_lm=reflection_lm,
                      max_metric_calls=200, num_threads=2,
                      log_dir="gepa_logs", track_stats=True)
optimized = optimizer.compile(program, trainset=trainset, valset=valset)

What happens inside compile: GEPA scores the base program on the validation set, then iterates. Each iteration it takes a minibatch of training examples (three by default), runs the current candidate on them, collects the metric's scores and feedback, and hands the failures to the reflection model, which proposes a rewritten instruction. The new candidate is scored on the train and validation sets, and it joins the Pareto frontier only if it beats the current best on validation. Failed candidates are discarded; the frontier keeps the winners. With this budget the run evaluates 200 rollouts in total.

One practical note: GEPA's reflection calls are the slow part on CPU. The 1.7B model generates at roughly 1.4 tokens per second here, and a reflection response runs to a few hundred tokens, so each mutation costs minutes. That is why the reflection model gets max_tokens=512 — enough room to write a new instruction, not enough to ramble. The task evaluations are the cheap part: the 0.6B model answers in about 10 seconds a question.

7. Step 5: Read the results#

The run finished in 35 minutes. The headline numbers:

ProgramValidation (16)Test (8)
Baseline instruction6/16 (37.5%)1/8 (12.5%)
GEPA-optimized7/16 (43.8%)3/8 (37.5%)

The optimized instruction GEPA settled on is:

Solve the word problem and provide the correct answer as a single number. Ensure the solution is accurate by performing the necessary arithmetic steps and verifying the calculations. Use clear and step-by-step reasoning to solve the problem, and provide the final answer in a box.

And here is what the optimized program does on four held-out test questions, verbatim:

gold=144  pred=144  $28 * $8 = $224  
$10 * $8 = $80  
$224 - $80 = $144  
gold=22  pred=24  $24
gold=34  pred=40  40
gold=72  pred=19  19

The optimized program fixes the baseline's dominant failure mode. Where the baseline compressed the whole derivation into one line and slipped a multiplication (28 x 8 = 192), the optimized instruction makes the model write each multiplication separately — $28 * $8 = $224, $10 * $8 = $80, $224 - $80 = $144 — and it gets that question right. Two of the eight held-out questions flip from wrong to right, and validation moves from 6/16 to 7/16. The remaining five test failures are the same kind of slip (the model still answers 70 where the answer is 66 or 45), which is what a 0.6B model does: the instruction can reduce the slips, not eliminate them. That is the honest size of the win here — a real improvement from prompt search alone, on the same model and the same hardware, with the small-sample caveat that eight test questions make each question worth 12.5 points.

8. Step 6: Save and reuse the optimized program#

An optimized DSPy program is a file, not a feeling. Save it and load it in any later script — the optimized instruction travels with it (this run added no few-shot demos; GEPA can add them when they help), and it runs against the same local endpoint.

optimized.save("optimized_program.json")

# later, in another script:
import dspy
dspy.configure(lm=dspy.LM("openai/qwen3-0.6b",
                          api_base="http://127.0.0.1:8080/v1",
                          api_key="local", temperature=0.0, max_tokens=80))
loaded = dspy.Predict(MathQA)
loaded.load("optimized_program.json")
print(loaded(question="A baker makes 32 muffins and puts 4 in each tray. "
                      "How many trays does the baker fill?").answer)

That is the deliverable: a program that is measurably better than the one you started with, with the measurement attached. If you change the task, you re-run the optimizer on new data; you do not re-tune the prompt by hand.

9. Which approach should you use?#

  • GEPA vs hand-tuning: hand-tuning wins when you have five examples and an afternoon. GEPA wins when you have a real training set and a metric — it searches systematically, remembers what it tried, and its result is reproducible from the same data and budget. If you cannot write a metric with feedback, GEPA loses its advantage and MIPROv2 is the better choice.
  • GEPA vs MIPROv2: MIPROv2 is stronger when your metric is a bare number and you want Bayesian search over instructions and demos. GEPA is stronger when your metric can explain failures in words. For arithmetic, classification with per-class feedback, and anything with a checkable answer, GEPA's feedback channel is the deciding factor.
  • Local reflection model vs a frontier API model: the documentation's standard setup uses a frontier model (GPT-5-class) as the reflection LM, and it is better at writing instructions. The local 1.7B worked here — the optimized program measurably improved — but a stronger reflector would likely find a better instruction faster. If you have API access, use a frontier reflection LM and keep the small model as the task LM; the reflection calls are only a handful per run, so the cost stays small. If you do not, a bigger local sibling (1.7B reflecting for 0.6B, as here) is a workable substitute.
  • Task model size: the 0.6B model is the smallest Qwen3, and it shows — its failures are arithmetic slips, not reasoning failures. A 1.7B or 4B task model would start higher and finish higher, at the cost of slower evaluations. The method is the same at every size; the budget is what changes.
  • Budget size: 200 metric calls is the right first run: tens of minutes on CPU. auto="medium" evaluates roughly twice as many candidates and is worth it once the pipeline works — it is also the point where a GPU for the task model starts to pay for itself.

10. Limits and honest caveats#

  • Small test set. Eight held-out questions means one question is 12.5 points, and sixteen validation questions means one is 6.25 points. The improvement reported here is directional, not a benchmark claim. If you adopt this for real work, use a validation set of at least 50 examples — GEPA's own guidance is to maximize the training set and keep validation just large enough to represent the distribution.
  • CPU speed. Everything here ran on 1.5 shared CPU cores. The 0.6B model generates at about 4 tokens per second and the 1.7B at about 1.4. A GPU would make the same run take minutes instead of 35 minutes. The method does not change; only the wall clock does.
  • Thinking was off. Disabling thinking made the runs fast enough to be practical, but it cost accuracy: the same 0.6B model with thinking on would solve more of these problems, at roughly 60 seconds a question. If your task model runs on a GPU, leave thinking on and let GEPA optimize around it.
  • The reflector is small. A 1.7B reflection model writes decent instructions, but it is not a frontier model. The optimized instruction it produced is good, not brilliant. Expect better instructions from a stronger reflector.
  • GEPA optimizes the metric, not the task. Our metric rewards the right final number and nothing else. If the model finds a way to guess the number without doing the work, the metric will reward it. Keep the metric honest and the test set held out, and the optimization stays honest.

11. The takeaway#

Prompt tuning is a search problem, and searches belong to programs, not to people squinting at twenty examples. GEPA turns your metric's feedback into better instructions, keeps only the candidates that beat the best on validation, and hands you back a saved program with the measurement attached. The whole loop runs locally: a 0.6B model doing the work, a 1.7B model doing the reflecting, both served by llama.cpp, no API key anywhere. The baseline prompt scored 1/8 (12.5%) on held-out questions; the optimized program scored 3/8 (37.5%) — same model, same hardware, better prompt, found by search instead of by feel.

Start with auto="light", a metric that explains failures in words, and a held-out test set you do not touch until the end. Then let the optimizer do the iterating.