When a language model is trained with reinforcement learning against unit tests, it typically writes several attempts per problem and is rewarded only for attempts that pass every test. On hard problems, every attempt often fails. The training signal for that problem is then exactly zero, even though one attempt may have parsed the input correctly before botching the final loop, and another may have written a correct final loop on top of broken parsing. We propose to recombine such failures during training. The method runs each failed program on the test inputs, records the values of its live variables at line boundaries, and looks for points where two different attempts reach the same program state. At those points it splices the first attempt's prefix onto the second attempt's suffix, then re-runs the unit tests on the spliced program. Splices that pass become new successful examples, scored by the policy with a single forward pass and added to the training batch. Producing them requires no new generation, no learned judge of intermediate steps, and no larger teacher model.
The idea transfers trajectory stitching to code. Offline reinforcement learning uses that term for building a good trajectory out of fragments of bad ones that pass through a shared state, and here the program's execution state supplies the shared state. Learning methods for language models have so far lacked a trustworthy notion of "the same state": two text prefixes are almost never identical. A program's runtime state, however, is the actual Markov state of the computation, and the unit-test oracle can check any splice exactly. If this works, it attacks three costs at once. Hard prompts stop wasting their rollouts, stitched successes are much cheaper to produce than new generations, and the method should need fewer generated samples to reach a given accuracy.
Core Claim
In reinforcement learning with verifiable rewards (RLVR, training against a programmatic pass/fail checker), groups of rollouts that all fail on hard coding prompts often contain complementary correct fragments that meet at equivalent execution states. Splicing at those states and re-verifying with the tests turns these zero-gradient groups into informative ones. Matched for compute, this beats spending the same budget on extra rollouts, on resampling continuations from a failed prefix, or on self-repair from error messages. The ingredient we claim is new is a stitching criterion based on runtime state equivalence and checked by deterministic tests. It sits inside the training loop and acts across different trajectories.
Why This Gap Is Real
Stitching is the central capability in offline reinforcement learning. D4RL built its AntMaze and Maze2D tasks to show that a learner which cannot stitch is capped at the best single trajectory in its data. Value-based methods such as Conservative Q-Learning stitch implicitly through Bellman backups over shared states. Graph methods such as BASS stitch explicitly through a reachability graph over bottleneck states. These works supply the concept we borrow, but all of them operate on low-dimensional states that genuinely recur. Offline RL with Observation Histories identifies the limiting factor: when histories are unique, stitching collapses unless the learner can recognize that two different histories reach equivalent underlying states. Token histories of language models are the extreme case. Our response is to stop matching text and match the program state the text produces.
In the language-model world, stitching so far happens only at inference time. SNDT assembles high-scoring steps from many noisy diffusion rollouts into a composite rationale and hands it to an autoregressive solver. It reports gains averaging 23.9 points over vanilla diffusion baselines at 8B scale. That paper motivates us, because locally correct steps really are scattered across failed attempts. It also constrains us. SNDT relies on a neural process reward model, a learned scorer of intermediate steps, and the authors name that scorer's false positives as the main failure mode. SNDT also never updates the model's weights. R-Stitch stitches between a small and a large model by token entropy to speed up decoding, again without training and without any correctness signal. We differ from both: we stitch during training, across rollouts of one policy, and we accept a splice only if deterministic tests pass it.
On the RLVR side, several papers attack the zero-signal problem without recombining trajectories. VIP shows that gradient variance per prompt scales as $p(1-p)$, where $p$ is the probability the current policy solves the prompt. It reallocates rollouts toward prompts of intermediate difficulty, but if a hard prompt still fails everywhere, its data is discarded. SDPO prompts the model with its own failed attempt plus the compiler or test feedback and distills the corrected distribution back into the policy. It reaches 48.8% on LiveCodeBench v6 against 41.2% for GRPO with Qwen3-8B, and it uses four times fewer generations. SDPO, however, works within a single trajectory, and it degrades at 1.5B parameters, where the model cannot reliably diagnose its own errors. AHEAD gets step-level credit from an external frontier-model analyzer, which adds substantial cost. Re² teaches the model to abandon a doomed attempt and restart, which throws away the valid prefix. FEST injects 128 human demonstrations under a decaying weight. Its finding that off-policy positives destabilize training unless they are down-weighted over time directly shapes how we add stitched samples.
Research Program
The first component is a stitcher. Every failed program in a group is instrumented at top-level statement boundaries. At each boundary we record, for each test input, the live variables and their values, with structured values canonicalized. Two rollouts A and B match at boundaries $i$ in A and $j$ in B when a variable renaming exists under which A's state after line $i$ equals B's state after line $j$ on every test input. We find candidate renamings by matching value fingerprints and only then substitute names. For each match we form the program A[:i] followed by the renamed B[j:], run the full test suite, and keep it if it passes. We prioritize pairs in which A's earliest state divergence from a passing reference is late, so that its prefix is likely correct, and B's divergence is early, so that its suffix may be correct. When no reference exists we fall back to exhaustive matching, capped per group. Everything here is CPU work in the same sandbox the reward computation already uses.
The second component decides how stitched programs enter the update. A stitched program $\tilde y$ was never sampled from the policy, so we treat it as an off-policy positive. We compute its log-probability under the current policy by teacher forcing, which costs one forward pass. We then add it to its group with reward 1, so the group-relative advantages of the original failures become negative and informative, and we clip its importance weight. Following FEST, an optional decaying coefficient reduces the influence of stitched samples as the policy's own success rate on the prompt rises.
The third component guards against spurious success. Stitched programs pass the visible tests by construction. Recombination might exploit weak test suites in the way Spurious Rewards and Outcome Rewards Do Not Guarantee Verifiable or Causally Important Reasoning warn about for outcome-only signals. We therefore validate splices on a held-out set of tests not used for matching, and we report how often the two sets disagree.
Baselines
The naive reference is GRPO run under the same prompts, model, sandbox, and total generation budget, with all-failed groups contributing nothing. Any gain must exceed this to matter at all.
The strongest existing method on our main benchmark is SDPO (Reinforcement Learning via Self-Distillation). It is the strongest competitor because it targets exactly our failure case, all-failed groups on code under unit-test feedback, and it reports 48.8% on LiveCodeBench v6 with Qwen3-8B. We run it from the same Qwen3-8B checkpoint on the same training prompts. We count its self-teacher forward passes as compute alongside our stitching forward passes, and we give both methods the same hyperparameter search budget. Beating it means exceeding its LiveCodeBench v6 accuracy at equal generated tokens, or matching it with clearly fewer. We also run both methods at 1.5B parameters, where SDPO is reported to fall below vanilla reinforcement learning. Our method does not rely on the model's in-context self-diagnosis, so a clear win at 1.5B would be the most distinctive result.
VIP (Adaptive Rollout Allocation) is the strongest compute-allocation competitor. It reports +12.3 Pass@32 on AIME2024 for Qwen2.5-Math-1.5B. We found no reported VIP result on Lacuna for LiveCodeBench, so we re-implement it on our code prompts with an identical rollout budget. Because stitching and allocation are complementary, we also run VIP combined with stitching.
Three ablations isolate the key ingredient. Brute-force splicing tries all line-boundary splice pairs up to the same cap and keeps those that pass the tests, with no state matching. It tells us whether state equivalence matters for yield or only saves test executions. Prefix resampling takes the same matched prefix A[:i] and samples fresh continuations from the policy instead of borrowing B's suffix, spending the generation compute we save. It tells us whether cross-trajectory recombination adds anything beyond branching from a good prefix. Finally, a version that adds stitched samples with constant rather than decaying weight tests FEST's stability concern in our setting.
Why not just…?
Why not just spend the saved compute on more rollouts for hard prompts? This is VIP's logic, and it helps whenever $p$ is small but nonzero. When $p$ is effectively zero, extra rollouts mostly produce more failures, whereas stitching manufactures successes from failures already paid for. The real question is the exchange rate. We will plot accuracy against generated tokens for VIP, VIP with stitching, and stitching alone. If VIP matches stitching at equal tokens, stitching offers no advantage on this budget, and we will report that.
Why not just resample continuations from the best failed prefix? This is the most serious threat. Tree-style branching from a prefix needs no splicing machinery, and the policy that wrote a correct prefix may write a correct suffix given a few more tries. The prefix-resampling ablation settles it directly by holding the prefix fixed and comparing a borrowed suffix with freshly sampled ones at matched cost. Stitching's argument is that the borrowed suffix is free and already demonstrated correct from that state. If resampling wins at equal compute, the contribution shrinks to locating the right prefix through execution state, which is still useful but much smaller.
Why not just let the model repair its own failure from the error message, as SDPO does? Self-repair is strong at 8B and sees richer information than our stitcher. It depends, though, on the model reading tracebacks well, which SDPO itself reports breaks down at 1.5B, and it never uses the correct fragments sitting in other rollouts. We expect the two to be complementary, so we test SDPO with stitching as well as each alone. A result where SDPO dominates at 8B while stitching wins at 1.5B would still be informative.
Why not just collect a few demonstrations, as FEST does? Demonstrations work, but they cost human effort per domain and arrive as whole trajectories. Stitching is self-supervised, and for prompts that have no demonstration it is the only source of positives. We include FEST with 128 demonstrations as a reference point on prompts where we can obtain reference solutions, and we test whether stitching closes most of the gap without them.
Proposed Experiments
The first check is diagnostic and decides whether the project proceeds. Using Qwen3-8B and Qwen2.5-1.5B-class base models on APPS-style training prompts, we sample groups of eight to sixteen rollouts. We then measure what fraction of all-failed groups yield at least one splice that passes both visible and held-out tests. If that fraction is below a few percent, the signal is too rare to matter and we stop. We also record whether state matching raises yield per test execution compared with brute-force splicing.
The main experiment trains with GRPO, GRPO with stitching, SDPO, SDPO with stitching, VIP, and VIP with stitching at equal generated-token budgets. Evaluation uses LiveCodeBench v6 as the uncontaminated primary benchmark, with HumanEval+ and MBPP+ as secondary benchmarks. Metrics are pass@1, accuracy as a function of cumulative generated tokens and of wall-clock time, the fraction of groups that contribute zero gradient, and mean solution length. Stitched solutions excise the failed regions of both parents, so we expect shorter outputs, which answers the overthinking concern from Re². We also track a diversity measure in the spirit of BODHI, since stitched positives drawn from multiple parents might slow the narrowing of solution strategies that RLVR is known to cause.
The decisive outcomes are three. First, at equal generated tokens, GRPO with stitching must beat GRPO on LiveCodeBench v6 and reduce the fraction of zero-gradient groups. Second, stitching must beat prefix resampling at matched compute. Third, at 1.5B scale, stitching must outperform SDPO, which would show that verifiable recombination works where self-diagnosis fails. As an extension, if code succeeds, tool-integrated math reasoning on DAPO-Math-17K is the natural next domain, with Python cell outputs serving as the execution states. We would scope that only after the code results are in.
References
- D4RL: Datasets for Deep Data-Driven Reinforcement Learning.
- Conservative Q-Learning for Offline Reinforcement Learning
- Bottleneck-Guided Spectral Subgoals For Offline Goal-Conditioned RL
- Offline RL with Observation Histories: Analyzing and Improving Sample Complexity
- Test-Time Scaling with Diffusion Language Models via Reward-Guided Stitching
- R-Stitch: Dynamic Trajectory Stitching for Efficient Reasoning
- Adaptive Rollout Allocation for Online Reinforcement Learning with Verifiable Rewards
- Reinforcement Learning via Self-Distillation
- AHEAD: Adaptive Hindsight with Environment-Augmented Distillation for Agentic RL
- $\textbf{Re}^{2}$: Unlocking LLM Reasoning via Reinforcement Learning with Re-solving
- Boosting Reinforcement Learning with Verifiable Rewards via Randomly Selected Few-Shot Guidance
- Spurious Rewards: Rethinking Training Signals in RLVR
- Outcome Rewards Do Not Guarantee Verifiable or Causally Important Reasoning
- BODHI: Do LLMs Branch Out and Discover Heterogeneous Inferences?