Small Models Guiding Large Models: An Engineering Guide to Recursive Self-Improvement for Code Generation
This article examines a Recursive Self-Improvement (RSI) framework that separates strategy formulation from code implementation in code generation. It explains the division of labor between a small policy model and a large execution model, the responsibilities of the core control layer, workspace, and evaluation environment, KL-UCB-based direction selection, strategy memory and reusable assets, structured Proposer-Worker handoff, cloud-native deployment considerations, and validation and risk controls. Readers gain an engineering view of module inputs, outputs, failure handling, observability metrics, and deployment trade-offs, without assuming that the dual-model approach is universally superior.
Introduction
In code generation, a common problem with large models is the lack of challenge to the initial approach. When a program reports an error, the model usually changes a parameter, adds a conditional branch, or tries another coding style and continues patching. If the original algorithm idea is flawed, such local adjustments can hardly expose the problem.
The Recursive Self-Improvement (RSI) framework attempts to address this issue. It separates “thinking through what to do” from “writing the code” and assigns them to two models. This article explains how this separation works, what inputs each module needs, what outputs it produces, and what must be validated during implementation.
1. Dual-Model Division of Labor
The framework has two types of roles. One is a smaller policy model, illustrated here at the 9B level, which proposes algorithm directions and adjusts them based on experimental results. The other is a large model, which turns strategies into runnable code, debugs it, and runs tests.
The rationale for this division is clear responsibility. The policy model does not write code; it only answers “which direction should be tried next.” The execution model receives only explicit strategies and is responsible only for implementation and validation. The two exchange information through a shared search state.
Whether a small model is better than a large model in policy diversity has no universal conclusion yet. Its value must be confirmed through controlled experiments: under the same budget, compare the dual-model approach with a single-model baseline on the same benchmark set.
2. Three Core Modules
The framework usually includes a core control layer, a workspace, and an evaluation environment. The table below lists each module’s responsibilities and the operating parameters that need attention.
| Module | Input | Output | Failure handling | Observability metrics |
|---|---|---|---|---|
| Core control layer | Shared search state, remaining budget | Nodes to expand in the next round and strategy instructions | Roll back to the previous version snapshot if state writing fails | Nodes selected per round, budget consumption rate |
| Workspace | Code versions that pass evaluation, experiment logs | Reusable code snippets, applicable conditions, prohibited rules | Mark reuse conflicts for manual review; do not auto-merge | Reuse count, pass rate after reuse |
| Evaluation environment | Code and test configuration submitted by the Worker | Metrics, pass or reject decision, failure reason | Retry once on a single timeout; record as failure beyond the limit | Pass rate, timeout rate, latency distribution |
When the budget is exhausted, the control layer stops new exploration, keeps only the current best version for small improvements, and outputs an experiment report. This avoids exhausting the budget on low-value directions.
3. How KL-UCB Selects Directions
The control layer uses two strategy-learning mechanisms. The first is UCB-based selection, specifically KL-UCB.
Many illustrative code samples write KL-UCB as “average reward plus an exploration term,” which differs from standard KL-UCB. The standard approach is to find a confidence upper bound that remains compatible with the observed mean in the KL-divergence sense.
For the Bernoulli case with rewards between 0 and 1, let the mean reward of a node be p̂, the number of attempts be n, and the total number of rounds be t. The KL-UCB index q is the maximum value satisfying:
n × KL(p̂, q) ≤ log t + c × log log t
where KL(p, q) = p log(p/q) + (1−p) log((1−p)/(1−q)). c is a constant, often set to 0 or around 3, and must be tuned experimentally. The left side increases as q increases, so q can be found by binary search.
The code below gives the selection logic. It assumes rewards have been normalized to between 0 and 1. If the evaluation metric is not in this range, apply a linear mapping first and document the mapping method.
import mathdef kl_bernoulli(p, q, eps=1e-12):p = min(max(p, eps), 1 - eps)q = min(max(q, eps), 1 - eps)return p * math.log(p / q) + (1 - p) * math.log((1 - p) / (1 - q))def kl_ucb_index(mean_reward, n_trials, t_total, c=0.0, iters=50):if n_trials == 0:return float("inf")budget = (math.log(t_total) + c * math.log(math.log(t_total))) / n_trialslo, hi = mean_reward, 1.0for _ in range(iters):mid = (lo + hi) / 2if kl_bernoulli(mean_reward, mid) <= budget:lo = midelse:hi = midreturn lodef select_node(nodes, t_total):# Each element in nodes contains reward_mean and n_trials fieldsreturn max(nodes, key=lambda nd: kl_ucb_index(nd.reward_mean, nd.n_trials, t_total))
In use, t_total should be the total number of attempts and at least 3; otherwise log log t is meaningless. The selection result must also be used together with a budget check. When the budget is insufficient, even the node with the highest index can only undergo low-cost validation.
4. Strategy Memory and Workspace
The second mechanism is memory-based strategy learning. The system writes effective practices from historical experiments into strategy entries. Each record includes the practice itself, the applicable data scale or task type, known failure conditions, and the most recent verification time.
New experiments strengthen, revise, or retire these entries. If a strategy fails consecutively on new datasets, lower its weight or flag it for review rather than deleting it directly. After deletion, the failure reasons can no longer be investigated.
The workspace turns memory into reusable assets. It manages three types of content: code snippets, performance characteristics of algorithms on specific datasets, and rules that prohibit certain uses. Before reusing code, the system must check whether interfaces are compatible and dependency versions match. Code that fails these checks should enter a manual review queue.
Version management is equally important. Each code version should carry a parent version ID, the strategy ID that generated it, and evaluation results. When a regression occurs, the system can roll back along the evolution chain to the most recent validated version.
5. Proposer-Worker Handoff Format
The handoff between the two roles should use a structured format to avoid ambiguity in natural-language descriptions.
The Proposer output should include the following fields:
- Hypothesis: one sentence stating what the root problem of the current method is believed to be
- Scope of change: modules or functions involved, and parts explicitly not to be changed
- Acceptance criteria: metric name, target value, and test set name
- Budget cap: allowed compute time or number of calls for this experiment
- Abandonment conditions: results that should cause this direction to stop
The Worker response should include: code version ID, run logs, metrics, failure category (such as syntax error, timeout, test failure, or metric regression), and whether the acceptance criteria are met.
The validation gate is determined uniformly by the evaluation environment. Only versions that meet acceptance criteria, pass regression tests, and complete a security scan are written to the shared search state. High-risk changes involving permissions, data deletion, or external calls should be added to manual review.
6. Cloud-Native Deployment Considerations
The dual-model architecture has two types of infrastructure requirements. The small model needs frequent low-latency inference, while the large model needs high-throughput code generation. Their load curves differ, so they are suitable for separate deployment and scaling.
Common practices are as follows:
- Configure independent container services for the policy model and the execution model, and scale GPU instances separately based on request queue length.
- Connect the Proposer and Worker with a message queue. When large-model code generation takes longer, the small model can continue analyzing other historical results, avoiding a full pipeline wait.
- Store strategy memory and the code version graph in object storage or a database, and record the success rate, latency, and resource consumption of each iteration.
- Set a cost cap for each iteration and pause automatically when the cap is exceeded.
Separate scaling may reduce idle costs, but the effect depends on the magnitude of load fluctuation. Before deployment, run load tests with real or simulated traffic, compare the unit cost of fixed and elastic configurations, and then decide which approach to use.
7. Validation and Risk Control
RSI frameworks are prone to improvements that look plausible but are actually ineffective. To avoid misjudgment, consider the following.
First, set a fixed baseline: under the same tasks and the same budget.
