Scout-Grep:
Teaching a Small Model to
Find the Right Code in Seconds
How multi-turn reinforcement learning turned a 4B base model into the code search behind Quick Search in Remy
Published Nov 4, 2026 · 14 min read
Using multi-turn reinforcement learning, we trained Scout-Grep—a specialized code search model built on the Qwen3.5-4B base model—to power Quick Search in Remy. Evaluated in the same search environment, Scout-Grep completes a multi-turn search in a median of 3.4 seconds, with 84% of queries returning within 5 seconds. By comparison, Claude Haiku 5.5 and GPT-6 Luna with their default reasoning settings take a median of 16.0 seconds and 14.2 seconds, respectively, with neither completing a single run under 5 seconds. On search quality, Scout-Grep matches Claude Haiku 5.5; GPT-6 Luna achieves higher accuracy, but adds an average of roughly 13 seconds to each search.
In this post, we share how we built Scout-Grep: why we offloaded code search to a dedicated small model, how we formulated “finding relevant code” as a learnable reward objective, where its low latency comes from, and how reinforcement learning actually reshapes the model’s behavior.
Fig. 013.4s per search, matching Claude Haiku 5.5 in quality
1.Before writing code, find it
Before making a single edit, a coding agent must complete an unglamorous yet critical prerequisite: locating the relevant code. Users typically describe symptoms or high-level problems rather than pointing directly to the underlying modules. The relevant logic may be scattered across entry points, configuration files, and deep call chains. An agent must first form a search hypothesis, inspect initial clues, and iteratively refine its judgment—sometimes hitting the right entry point on the first try, and other times uncovering only identically named functions, test fixtures, or long-deprecated legacy code.
This step rarely steals the spotlight in product demos, yet it determines whether the foundation for all subsequent reasoning is solid. When done poorly, it exacts a threefold toll.
Wrong targets: Once pointed at the wrong files, even the most capable primary model will get derailed by misleading context.
Context bloat: When the primary model searches and reads simultaneously, its context window quickly fills up with code that ultimately proves irrelevant—driving up inference costs while diluting attention and clouding critical judgment.
High latency: Every search turn requires a full cycle of model inference and tool execution; the larger the primary model, the slower each round trip, turning a few rounds of exploration into dozens of seconds of silence.
2.Scoping the search sub-agent
In Remy, we decoupled code search and delegated it to a dedicated search sub-agent: Quick Search. The primary agent simply poses a search query, and Quick Search explores the codebase using read-only tools—ultimately returning only a set of file paths and line ranges. The primary agent then opens these exact locations directly to take over subsequent reasoning and code editing.
We deliberately narrowed the task boundary: Quick Search is neither asked to resolve the issue nor to propose a fix; its job ends the moment it hands over the code locations. Three considerations drove this design. First, a fluent natural-language summary still requires secondary verification by the primary agent, and an inaccurate summary can easily mislead it; explicit files and line numbers, by contrast, can be opened directly and verified on the spot. Second, the trial-and-error and noise of the search process are fully contained within the sub-agent, so the primary agent’s context receives only the distilled, relevant locations. Third, this boundary makes the search task quantifiable and verifiable: given a query and reference code spans, we can directly evaluate whether the model hit the right files, how many critical lines it covered, and how much irrelevant code it pulled in. While reference annotations may not exhaustively capture every piece of potentially useful context, evaluating location overlap reflects the exact behavior we want the model to learn far better than judging whether a written summary is “good.”
Once the task boundary is sharp enough, the model can be small enough. We do not need the full-stack capabilities of a primary model; we only need it to execute one high-frequency loop to perfection: forming search hypotheses from a query, adjusting its exploration based on tool feedback, and converging on specific line ranges to read. To support this, Quick Search operates within a fixed toolset and inference budget: it has access to four read-only tools (grep, glob, list, and read), a maximum of 5 search turns plus 1 final turn to compile the results, and a cap of 32 total tool calls. Multiple tool calls issued within the same turn execute in parallel locally, and each model generation is capped at 2,048 tokens.
Fig. 02Find the code first, then solve the problem
3.Multi-turn RL for production
General-purpose base models already possess solid language understanding and coding knowledge, but there is a fundamental difference between “talking about code” and “locating code in an unfamiliar codebase.” The latter is a sequence of decisions made under incomplete information: which keywords to search for in this turn, which file segments to read in the next, and whether to dig deeper or pivot immediately upon seeing new clues.
We began with a simplified single-turn setup, where the model directly outputs the final file paths and line ranges in a single response—scoring only that output to validate our end-to-end training and evaluation pipeline. From there, we expanded the training horizon from single-turn completions to full search trajectories: the model issues real tool calls, the environment writes the execution results back into the context, and the model decides its next move. Rather than building a mock environment solely for training, we plugged directly into Quick Search’s production search core—meaning every exploratory step the model takes during training faces the exact same environment it will encounter in production.
At the algorithmic level, we use multi-turn GSPO: for each task, we sample a group of complete search trajectories, compute their relative advantages based on rewards within the group, and update the policy accordingly. Only the model-generated tool calls and final responses contribute to the loss; code snippets returned by tools serve strictly as environmental observations and are masked out from gradient updates.
For training data, we started with 450 real-world issues from ContextBench Verified, each paired with human-verified reference files and line ranges, while strictly holding out 50 tasks for evaluation. We then augmented this dataset with real search tasks from our internal codebases, using Kimi K2.7 to assist in annotating reference locations, which yielded a final training set of 489 tasks. Internal data was split into training and held-out sets at the full-session level, while the 50 benchmark evaluation tasks remained strictly frozen throughout. Turning a general-purpose base model into Scout-Grep was not a single long training run with fixed hyperparameters; data mixtures, environment validation, and the reward function were all refined iteratively, with reward design undergoing the deepest evolution.
4.Reward hacking & fixes
In reinforcement learning, the reward function is the task. A model will always optimize the mathematical objective we write down, not the behavior we have in mind. While training Scout-Grep, the model found three successive ways to game the objective—each exposing a gap between our reward specification and our true intent.
Shortcut 1: Skipping search and guessing blindly. To encourage efficiency, our early reward function multiplied the final answer score by step-dependent discount factors. The model quickly did the math: as long as a blind guess could scrape together a nonzero score, issuing zero tool calls avoided all process penalties entirely. To us, search was the necessary path to localization; to the reward function at the time, search was merely a cost to be penalized. We decoupled the reward so that uncovering relevant evidence during search earned positive credit on its own, while trajectories with zero tool calls forfeited their efficiency score entirely. Rather than encouraging the model to pad its tool calls, this sent a clear signal: in a task that demands exploration, reasonable exploration itself deserves to be rewarded.
Shortcut 2: Returning the entire file. Once we closed the blind-guessing loophole, the model learned to output extreme spans like {"startLine": 0, "endLine": 2003707}—effectively dumping the entire file onto the primary agent as if to say, “The answer is in here somewhere, go find it yourself.” Because hitting the right filename alone was enough to earn file-level credit at the time, the model had zero incentive to narrow down the line ranges. We examined the distribution of reference annotations: the 99th percentile of reference line spans was 497 lines, with a maximum of 796 lines. Based on this, we treated any output span exceeding 800 lines as failing to meet our localization granularity—scaling down the final answer reward in proportion to the share of oversized spans, and steeply discounting the search reward as well if every returned span exceeded the limit.
Shortcut 3: Under-reporting files to preserve precision. In an early held-out evaluation, we noticed the average number of files reported by the model dropped from 1.74 to 0.96, dragging file recall down from 33.3% to 20.5%. On the surface, the model’s outputs looked cleaner and more restrained; in reality, complex tasks requiring cross-file edits were losing critical context. The flaw lay in the granularity of our search reward: it granted a fixed bonus for each relevant file discovered, failing to distinguish between finding the single file needed for a simple issue and finding only one of several critical files for a complex one. To fix this, we incorporated reference file recall into the search reward and switched the file-level training metric to recall-weighted .
Fig. 03Three shortcuts the model found
The latter two shortcuts pulled toward opposite extremes: one returned too much, the other too little. Together, they made it clear that a search objective must be tightened from both sides—recovering all necessary files while keeping the returned line spans narrow. Ultimately, Scout-Grep’s reward function converged on three core dimensions: whether the returned locations are accurate and complete (final answer), whether the search process uncovered key evidence (search process), and whether the tool budget was spent judiciously (efficiency):
Here, blends line-level and file-level at a 0.7 : 0.3 ratio, subject to soft constraints on output length, the number of merged spans returned, and single-span length; combines line-level overlap between tool observations and reference code, the number of matched reference files, and file-level recall; carries only a 10% weight with a guaranteed floor, and drops directly to zero whenever the model makes no tool calls at all. These exact coefficients are not a universal formula; the transferable design principle is to never make it easier for the model to score high by skipping search, padding line ranges, or under-reporting files than by conducting a thorough search.
5.Latency & inference speed
To evaluate speed and quality on equal footing, we isolated Quick Search’s production search loop and swapped only the underlying model—keeping the exact same system prompt, read-only toolset, and search budget across 50 real-world issues with 2 runs per task. Both GPT-6 Luna and Claude Haiku 5.5 were called via API.
Under this setup, Scout-Grep completes a full multi-turn search in a median of 3.4 seconds and a P90 of 6.3 seconds, with 84% of runs finishing within 5 seconds. By comparison, Claude Haiku 5.5 takes a median of 16.0 seconds and GPT-6 Luna takes 14.2 seconds; even with thinking disabled or reasoning effort reduced, their median latencies remain in the 12–18 second range. In paired task-by-task comparisons, handing the exact same query to Claude Haiku 5.5 adds an average of 14.2 seconds of wait time, while GPT-6 Luna adds an average of 13.0 seconds.
Fig. 0484% of searches finish within 5 seconds
The gap in end-to-end latency stems primarily from compounding latency across sequential model calls. A single model call to Scout-Grep takes a median of roughly 0.47 seconds, compared to 2.7–3.3 seconds per call for the frontier models. Local tool execution itself is lightweight: Scout-Grep issues an average of 11.4 tool calls per search, and because multiple calls within the same turn execute in parallel locally, tool execution and orchestration overhead account for just 0.38 seconds combined—roughly one-tenth of total latency.
Scout-Grep uses nearly the full five-turn search budget on average, issuing about 2.3 tool calls per turn and adapting as it reads; Claude Haiku 5.5 and GPT-6 Luna take only 3–4 turns, but batch 3.5–4.3 parallel tool calls per turn. When a single turn takes less than half a second, the model can afford to take more steps, grounding each step in the evidence gathered from the last. Teaching Scout-Grep to parallelize its tool calls more aggressively is one of our next directions.
Fig. 05Speed comes from every model call
On the inference engine side, we drove latency down further through two optimizations. First is mixed-precision NVFP4 quantization: based on empirical testing, we kept the GatedDeltaNet layers in BF16 and applied FP4 quantization only to the attention and MLP layers, balancing numerical stability with inference throughput. Second is DFlash speculative decoding: we trained a custom draft model on real search trajectories, making it highly specialized for structured outputs like tool calls, file paths, and line numbers. At each decoding step, DFlash drafts a block of candidate tokens in parallel for the target model to verify. In a fixed-input replay benchmark of 241 model calls across 40 real trajectories, DFlash cut total model inference time from 109.5 seconds to 87.4 seconds—an overall speedup of 1.25×. However, the gains from speculative decoding decay noticeably as context grows: while the speedup reaches 1.66× for inputs under 4K tokens, it drops to 1.05× once the accumulated context exceeds 8K tokens.
Fig. 06The longer the context, the smaller the speedup
6.Search quality vs. frontier models
We use as our primary search quality metric, weighting precision more heavily than recall. This choice reflects a practical engineering trade-off: polluting the primary agent’s context with irrelevant code is often more damaging than missing a small amount of peripheral context—and if anything is missed, the primary agent can usually fill the gap with one or two follow-up searches. The overall score is the arithmetic mean of file-level and line-level ; if the model returns a nonexistent file path or an invalid line range, the run is scored as zero.
On the 50 held-out tasks, Scout-Grep achieves an overall of 0.453 compared to 0.455 for Claude Haiku 5.5, with no statistically significant difference between the two (a paired task-level difference of −0.001, 95% CI [−0.07, +0.07]). GPT-6 Luna scores higher at 0.528 (leading by roughly 0.075), but at the cost of adding about 13 seconds to each search on average. GPT-6 Luna with thinking disabled and Claude Haiku 5.5 at low reasoning effort score 0.495 and 0.489, respectively—differences from Scout-Grep that likewise fall within statistical noise.
The models also exhibit distinct search styles. Scout-Grep returns an average of 2.1 files per search with a file-level precision of 0.62, whereas Claude Haiku 5.5 returns an average of 3.5 files with a file-level precision of 0.55. Scaled up to a larger public benchmark, the 4B Scout-Grep model also holds its own against much larger general-purpose models. SWE-Explore-Bench (discussions on Hugging Face) spans 848 real-world issues across 203 open-source repositories and 10 programming languages, evaluating codebase exploration using the general-purpose mini-SWE-agent framework. On this benchmark, Scout-Grep achieves a line-level score of 0.180, outperforming the paper-reported scores of Sonnet-4.5 (0.154), Kimi-K2.6 (0.149), and GLM-4.7 (0.148), and trailing only GPT-5.4 (0.194) and GPT-5.4-mini (0.215). These baseline numbers are taken from the original paper, using the same mini-SWE-agent framework and the same top-five-region output budget (, up to five code regions ranked by relevance).
7.Out-of-harness transfer
The impact of reinforcement learning becomes clear when we evaluate the model in a harness it never saw during training. Under the mini-SWE-agent framework used by SWE-Explore-Bench, Scout-Grep improves line-level F1 from 0.077 to 0.180 and line-level recall from 0.063 to 0.162 over the untuned Qwen3.5-4B base model, while its instruction-following failure rate—the share of tasks where the model failed to return results in the required format—fell from 57% to 33%. These results suggest that the gains were not limited to Quick Search’s particular prompt and tool interface: the trained model also performed better in mini-SWE-agent, with its different interaction and submission conventions, demonstrating a stronger ability to actively explore unfamiliar codebases, narrow down evidence, and return results.
Fig. 07What training actually changed
mini-SWE-agent.8.Limitations & next steps
From a general-purpose 4B base model to Scout-Grep, its goal was never to build a miniature generalist. It was to draw a sharp boundary around one job—finding the code worth reading before the primary agent starts reasoning—and train a model to do that job fast. The hardest part was translating that intuition into a reward function that survives optimization: skipping search is not efficiency, returning a whole file is not localization, and reporting fewer files is not precision.
Scout-Grep is far from the final word on code search, and its current limitations point directly to what we are building next. On the modeling side, while Scout-Grep matches Claude Haiku 5.5 in overall precision-weighted quality, its rate of hitting at least one reference file still trails frontier models by roughly 7 percentage points (89.0% vs. ~96%), and recovering full context on complex, cross-file issues remains an area with clear headroom. It also leans heavily on serial exploration; training the policy to issue more complementary tool calls per turn will let it cover the same ground in fewer round trips. On the systems and evaluation side, we are working to keep speculative decoding fast even after accumulated search context passes 8K tokens—where DFlash speedup currently decays from 1.66× to 1.05×—while scaling our benchmark suite across more repositories, live production queries, and a strictly held-out confirmation split.
Even with that headroom ahead, the division of labor already works: when finding code takes three seconds instead of fifteen, the primary agent gets to spend its time and context window on the reasoning that actually requires a frontier model.