The Research Report
Your LLM Already Knows the Answer. It Just Needs Better Instructions.
How ContraPrompt extracts optimization rules from the gap between failure and success — and beats GEPA across the board.
Every prompt engineer has seen it. Your model fails on a question. You feed it a hint. It retries and nails it. Then you move on.
The failed trace goes in the trash. The successful trace gets a passing nod. Nobody asks the obvious question: what exactly changed between those two attempts?
A paper published on arXiv last week asks that question and builds an entire optimization system around the answer. The paper is ContraPrompt: Contrastive Prompt Optimization via Dyadic Reasoning Trace Analysis, authored by Rishav Rishav, Pushpak Pujari, and Pushpendre Rastogi from Vizops AI. It was submitted for the ICLR 2026 Workshop.
The results speak for themselves. ContraPrompt outperforms GEPA — the current state-of-the-art reflective prompt optimizer from Agrawal et al. (2026) — on all four benchmarks tested. On HotPotQA, the gap is +8.29 percentage points. On GDPR-Bench, +2.21pp. On GPQA Diamond, +7.14pp. On BBH (BIG-Bench Hard), +0.74pp.
But the more interesting story is how it gets there. ContraPrompt is the first method to extract optimization signal from the reasoning process itself — not just from final answers.
The Problem with Existing Prompt Optimization
Current prompt optimization falls into three camps.
Monadic failure analysis. Methods like TextGrad and ProTeGi read a single failed trace and ask "what went wrong?" They get a diagnosis with no positive target. It is like asking a doctor to fix a patient after seeing only the symptoms, never the recovery.
Evolutionary search. Methods like OPRO, APE, and GEPA generate populations of prompt variants and compare their outputs across examples. They get population-level signal but no within-example comparison. GEPA, the strongest of these, maintains a Pareto frontier of candidate prompts and mutates them based on cross-example performance. It works well, but it never asks why the same model on the same input sometimes fails and sometimes succeeds.
Preference and contrastive methods. DPO compares final outputs (preferred vs. dispreferred answers) and fine-tunes model weights. Other contrastive prompting methods compare prompt phrasings. Both operate on final outputs or prompt inputs. Neither touches intermediate reasoning.
All three camps share a blind spot. They treat the transition from failure to success on the same input as a byproduct of retry mechanics. ContraPrompt treats it as the primary data source.
Dyadic Traces: The Core Idea
Here is the insight that powers ContraPrompt.
When a language model fails on a task, then succeeds on a retry with error feedback, you get two complete chain-of-thought traces on the same input. One failed. One succeeded. Call them τ⁻ and τ⁺.
This pair is a controlled comparison in ways that no cross-example comparison can be.
- Same model. Same weights, same parameters.
- Same input. Same question, same context.
- Same base prompt. No prompt variants muddying the signal.
- Same task difficulty. Not comparing easy vs. hard examples.
The only things that differ between the two traces are the reasoning strategy and the appended error feedback. The delta between τ⁻ and τ⁺ is a step-level signal. It tells you which specific inference step was present in success and absent in failure — not just that the answer was wrong, but why the model got there the wrong way and then found the right way.
This is what the authors call dyadic reasoning trace analysis. The word "dyadic" refers to the pair structure. You are not analyzing one trace in isolation (monadic). You are analyzing the difference between two traces that share nearly everything except outcome.
The paper formalizes a prerequisite condition called the capability-application gap. A model exhibits this gap when its retry success rate (the fraction of first-attempt failures that recover on retry) is meaningfully above zero. Across the four benchmarks, the authors observe:
- HotPotQA: ~37% retry success rate
- GDPR-Bench: ~25%
- GPQA Diamond: ~24%
- BBH: ~20%
These numbers tell you something important. The model can produce the correct reasoning. It just does not do so reliably on first attempt. That gap between capability and reliable application is exactly where ContraPrompt operates.
If the retry success rate were near zero, there would be no signal to extract. The model would simply lack the capability. But 20–37% of failures self-correcting means there is a rich vein of contrastive data sitting in every retry loop, waiting to be mined.
How ContraPrompt Works
The system runs in five phases per iteration.
Phase 1: Instrumented Agentic Retry Loop
For each training example, the model gets up to 3 attempts. The first attempt uses the base prompt with no additional context. If it fails, error feedback from the scoring function gets appended as context for attempt two. If that fails, the accumulated feedback feeds attempt three.
Task solving runs at temperature 1.0. This is deliberate. At lower temperatures, retries tend to reproduce the same failed reasoning with surface-level variations. At temperature 1.0, each retry samples a different region of the model's reasoning strategy distribution. A successful retry is more likely to represent a genuinely distinct approach.
Every attempt produces a complete chain-of-thought trace. The retry loop generates the raw material — paired traces of failure and success on the same input — without any human annotation.
Phase 2: Contrastive Pair Mining
After the retry loop completes, the system identifies contrastive pairs: examples where the model failed on one attempt and succeeded on another. These are the (τ⁻, τ⁺) pairs.
Not every example produces a contrastive pair. Some examples pass on the first attempt. Some fail all three attempts. Both outcomes are tracked — the all-fail bucket feeds a separate aggregated failure analysis — but the contrastive pairs are the high-value signal.
Phase 3: Rule Extraction
A language model examines each contrastive pair and extracts a rule describing the reasoning delta. What did the successful trace do differently? Was it an evidence-attribution step that the failure skipped? A unit-consistency check? An explicit state enumeration?
Crucially, the extractor is prompted to focus on reasoning approach changes rather than the change in conditioning context (the appended error feedback). The pair does not hold conditioning context fixed — the successful attempt saw error feedback that the failed attempt did not — so the extractor needs to distinguish strategy shifts from information shifts. This decomposition is approximate, and the authors acknowledge it as a limitation.
Phase 4: Input-Aware Decision Tree
As rules accumulate, dumping all of them into the prompt creates noise. Rules irrelevant to a given input type can confuse the model. The system organizes extracted rules into a decision tree that routes instructions by observable input features.
For a HotPotQA question about comparing two entities, the tree delivers rules about comparative reasoning. For a GDPR compliance question about data processing, it delivers rules about legal framework analysis. Each input gets only the rules relevant to its structure.
This is analogous to how memory and context engineering systems gate retrieved content by relevance — but the routing rules are derived from contrastive trace evidence, not from hand-designed heuristics.
Phase 5: Checkpoint Evaluation
After each iteration, the system evaluates the augmented prompt on held-out validation data. Learned rules that degrade performance get pruned. The system includes early stopping after 3 iterations without improvement. This prevents prompt degradation from accumulating bad rules.
The Benchmark Results
The paper evaluates ContraPrompt against GEPA on four reasoning and compliance benchmarks, all under a single-module constraint on the same underlying model. (GEPA's published HotPotQA numbers use a four-module architecture and are not directly comparable.)
| Benchmark | Task Type | ContraPrompt vs. GEPA |
|---|---|---|
| HotPotQA | Multi-hop QA | +8.29pp (+20.8% relative) |
| GDPR-Bench | GDPR compliance | +2.21pp (+18.2% relative) |
| GPQA Diamond | Graduate-level science | +7.14pp (+10.6% relative) |
| BBH | BIG-Bench Hard | +0.74pp (+0.85% relative) |
The gains are not uniform. HotPotQA and GPQA Diamond show the largest improvements. BBH shows the smallest. The authors observe a suggestive pattern: gains track with retry success rate. HotPotQA has the highest retry rate (~37%) and the biggest gain. BBH has the lowest (~20%) and the smallest gain. With only n=4 benchmarks, this is a pattern worth watching but not yet a statistical finding.
Beyond the four main benchmarks, the paper tests generalization in two additional domains:
Black-box function optimization. On 53 EvalSet problems, ContraPrompt beats GEPA head-to-head on 11, ties on 41, and loses on 1. Same budget, same model. The contrastive mechanism transfers beyond prompt optimization for reasoning tasks.
Financial named entity recognition. On FiNER-139, a 139-class classification task on financial documents, ContraPrompt achieves +7.77pp over the unoptimized baseline (+11.6% relative) and +1.94pp over GEPA (+2.66% relative). The input-aware decision tree produces branch conditions that align with standard US GAAP financial-instrument categories. This is notable. The system did not know about GAAP categories beforehand. It discovered them from the contrastive traces.
The Ablation That Matters
The ablation study is where the paper makes its strongest case.
Removing dyadic contrastivity — replacing trace-pair comparison with single-trace failure analysis — causes a -16% relative average performance drop across all four benchmarks. This is the same magnitude of degradation as replacing contrastive mining with answer-only comparison.
In other words, the reasoning traces carry information that final answers alone do not. When you compare only final outputs, you learn that one answer was preferred over another. When you compare complete chain-of-thought traces, you learn which inference step made the difference. Strip out the traces, and you strip out the signal.
The ablations also test removing the input-aware decision tree. Without conditional routing, all rules get injected into every prompt. Performance drops because irrelevant rules create noise. The tree is not a nice-to-have. It is load-bearing.
Using ContraPrompt: pip install vizpy
ContraPrompt is available as part of the VizPy package, an open-source drop-in replacement for DSPy's optimization layer.
import dspy
from vizpy import ContraPromptOptimizer
# Define your module
module = dspy.ChainOfThought("question -> answer")
# Define your metric
def metric(example, prediction):
score = 1.0 if prediction.answer == example.answer else 0.0
return dspy.Score(
score=score,
feedback=f"Expected: {example.answer}, Got: {prediction.answer}",
is_correct=score > 0
)
# Optimize
optimizer = ContraPromptOptimizer(metric=metric)
optimized = optimizer.compile(
module=module,
train_examples=train_data,
)
The key design decision: you supply a Metric that returns a Score object with a numeric score, textual feedback, and an optional error type. More specific feedback produces better optimization. "Expected a 3-digit number but got a sentence" beats "Wrong."
The default configuration runs 5 iterations, 3 retry attempts per example, and early stopping after 3 iterations without improvement. Rules are validated individually before being applied, preventing harmful changes from degrading the prompt. The maximum accumulated rules defaults to 8.
Advanced features include:
- Progressive rules: Maintain improvements across iterations with periodic re-validation and pruning. Useful for runs of 5+ iterations.
- Contrastive demos: Include concrete examples of improved reasoning in the optimized prompt. Requires chain-of-thought modules.
- Failure-focused mode: After iteration 1, focus on the hardest examples where the model is inconsistent.
- Diversity mining: Use embedding-based clustering to ensure the optimizer addresses all error categories, not just the most common one.
Practical Implications for Production
ContraPrompt has several properties that matter for real-world deployment.
No model modification required. The system extracts prompt rules from contrastive trace evidence without touching model weights. You can use it with any LLM that supports chain-of-thought reasoning. No fine-tuning, no RLHF pipeline, no custom training.
Self-generating training data. The retry loop generates contrastive pairs automatically. You do not need human annotators to label which traces are good and which are bad. The scoring function you already have — the one that tells you whether the answer is correct — drives everything.
Diagnostic value. The extracted rules tell you why your prompt is failing, not just that it is failing. When the input-aware tree produces branch conditions aligned with GAAP categories on FiNER-139, that is the system discovering domain structure from the data. This is useful beyond optimization. It is a window into what the model is struggling with.
Budget-aware. The system includes built-in early stopping and rule validation. More iterations yield diminishing returns after 3–5. The default configuration is tuned for general use. You can increase maxiterations and maxattempts for harder tasks, but you pay in LLM calls.
The capability-application gap is a prerequisite. If your model's retry success rate is near zero — if it genuinely cannot solve the task — ContraPrompt will not help. The authors offer a simple diagnostic: run 20 failed examples through a retry with a nudge. If more than 30% self-correct, ContraPrompt will deliver strong gains. If the model fails consistently, you need a bigger model or a different task formulation, not prompt optimization.
The axes are complementary. ContraPrompt operates on a within-prompt, within-example axis. GEPA operates on a cross-prompt, cross-example axis. These are orthogonal. A hybrid combining GEPA's population-level search with ContraPrompt's instance-level trace deltas is a natural direction for future work. If you are already using GEPA, ContraPrompt is not a replacement. It is an addition.
What Makes This Different
The core contribution is not the benchmark numbers, impressive as they are. It is the reframing of prompt optimization from an output-level problem to a process-level problem.
Every other method in this space looks at what the model produced. ContraPrompt looks at how the model reasoned. The difference between a failed trace and a successful trace on the same input is not noise. It is signal. It tells you which reasoning steps matter, which checks the model skips, and which strategies the model abandons too early.
This is also why the ablation hits so hard. Removing dyadic contrastivity causes a -16% drop. Replacing trace comparison with answer-only comparison causes the same -16% drop. The reasoning process carries information that the final answer discards. When you throw away the traces, you throw away the most valuable part of the signal.
The input-aware decision tree adds another layer. Rules are not one-size-fits-all. Different input types need different instructions. The system learns to route rules conditionally, and the routing conditions it discovers can be genuinely insightful — like recovering GAAP category structure from financial NER traces.
Limitations and Open Questions
The authors are straightforward about limitations.
The confound. The (τ⁻, τ⁺) pair does not hold conditioning context fixed. The successful attempt sees error feedback that the failed attempt did not see. The rule extractor is prompted to focus on reasoning-approach changes rather than conditioning changes, but this decomposition is approximate. A cleaner experiment would retry without feedback at temperature 1.0 to isolate pure strategy variation. That is future work.
Temperature dependency. The retry loop runs at temperature 1.0 to maximize strategy diversity. At lower temperatures, contrastive pairs collapse toward identical reasoning with surface variation. This means ContraPrompt generates its training data under different conditions than many production deployments, which tend to use lower temperatures for reliability. The extracted rules should still transfer, but the data-generation pipeline requires temperature 1.0.
The n=4 problem. The pattern of gains tracking retry success rate is suggestive but comes from only four benchmarks. More benchmarks are needed to confirm the relationship.
Not a replacement for GEPA. The two methods operate on orthogonal axes. The paper's head-to-head comparison uses GEPA as the primary baseline and beats it, but a hybrid approach is likely stronger than either alone.
Where This Goes Next
The most interesting direction is combining ContraPrompt's dyadic trace analysis with GEPA's population-level evolutionary search. GEPA searches broadly across prompt variants. ContraPrompt searches deeply within trace pairs. A system that does both — using dyadic traces to identify specific reasoning failures and evolutionary search to explore prompt variants that address them — could outperform either method alone.
The financial NER result is also worth watching. When a prompt optimization system discovers domain structure (GAAP categories) from its own trace data, that suggests the approach has diagnostic and interpretive value beyond raw performance. You could use extracted rules not just to improve prompts, but to understand what your model is struggling with in production.
The paper is available at arxiv.org/abs/2604.17937. Reproduction artefacts, including optimized prompts, are at github.com/rishvv/contraprompt_artefacts. The VizPy package is available at pypi.org/project/vizpy or via pip install vizpy.
ContraPrompt: Contrastive Prompt Optimization via Dyadic Reasoning Trace Analysis. Rishav Rishav, Pushpak Pujari, Pushpendre Rastogi. Vizops AI. arXiv:2604.17937, April 2026.